branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># woocommerce-server A tiny node server to query woocommerce stuff <file_sep>let mysql = require('mysql'); let express = require('express'); let app = express(); let bodyParser = require('body-parser'); let logger = require('morgan'); let methodOverride = require('method-override') let cors = require('cors'); let http = require('http').Server(app); var moment = require('moment'); //var momenttz = require('moment-timezone'); var qr = require('qr-image'); let shell = require('shelljs'); const util = require('util'); const exec = util.promisify(require('child_process').exec); var os = require('os'); var ifaces = os.networkInterfaces(); var ipAddressLocal = "localhost" const synctime = 10000; let clientName = 'All' let clientItensOnline = [] let errorOnSelling = [] const nodemailer = require('nodemailer'); var msgEmail = 'Olá! Obrigado por adquirir o ingresso. Segue em anexo o qrcode. <strong>https://www.megaticket.com.br</strong>' var emailFrom = '<EMAIL>' var emailSubject = 'Qr Code ingresso' var pathQRCode = './qrcodes/' var worksOnline = 0 var idUserOnline = 1 const printerLocal = 0 app.use(logger('dev')); app.use(bodyParser.json()); app.use(methodOverride()); app.use(cors()); var db_config_remote = { host: "rds001.cacasorqzf2r.sa-east-1.rds.amazonaws.com", user: "bilheteria", password: "<PASSWORD>", database: "vendas_online" }; var db_config_local = { host: "localhost", user: "root", password: "<PASSWORD>", database: "3access" }; let con; let conLocal; function handleDisconnectRemote() { con = mysql.createConnection(db_config_remote); con.connect(function(err) { if (err){ setTimeout(handleDisconnectRemote, 2000); } con.on('error', function(err) { if(err.code === 'PROTOCOL_CONNECTION_LOST') { handleDisconnectRemote(); } else throw err; }); log_("Database conectado!") log_("Aguardando conexões ...") }); } function handleDisconnectRemote() { con = mysql.createConnection(db_config_remote); con.connect(function(err) { if (err){ setTimeout(handleDisconnectRemote, 2000); } con.on('error', function(err) { if(err.code === 'PROTOCOL_CONNECTION_LOST') { handleDisconnectRemote(); } else throw err; }); log_("Database remoto conectado!") log_("Aguardando conexões ...") }); } function handleDisconnectLocal() { conLocal = mysql.createConnection(db_config_local); conLocal.connect(function(err) { if (err){ setTimeout(handleDisconnectLocal, 2000); } conLocal.on('error', function(err) { if(err.code === 'PROTOCOL_CONNECTION_LOST') handleDisconnectLocal(); else throw err; }); log_("Database local conectado!") log_("Aguardando conexões ...") }); } function startInterface(){ if(worksOnline === 1){ handleDisconnectRemote(); if(clientName === 'All') getAllProductsClient() else getProductsClient() setInterval(function(){ syncDatabases() }, synctime); } handleDisconnectLocal(); startIpAddress() } function startIpAddress(){ Object.keys(ifaces).forEach(function (ifname) { ifaces[ifname].forEach(function (iface) { if ('IPv4' !== iface.family || iface.internal !== false) return; ipAddressLocal = iface.address if(ipAddressLocal.indexOf("10.8.0.") > -1) return; }) }) } startInterface(); function log_(str){ let now = moment().format("DD/MM/YYYY hh:mm:ss") let msg = "[" + now + "] " + str console.log(msg) } var transporte = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'myrestaurantwebapp', pass: '' } }); function printFile(tipoIngresso, valorIngresso, operador, dataHora, idTicket, totalVenda, reprint){ return new Promise((resolve, reject) => { let cmd = 'sh /root/PDVi_Server/scripts/impressao.sh "' + tipoIngresso + '" ' + valorIngresso + ' ' + operador + ' "' + dataHora + '" ' + idTicket + ' ' + totalVenda if(reprint === 1){ cmd = 'sh /root/PDVi_Server/scripts/reimpressao.sh "' + tipoIngresso + '" ' + valorIngresso + ' ' + operador + ' "' + dataHora + '" ' + idTicket + ' ' + totalVenda } const { stdout, stderr, code } = shell.exec(cmd, {async: false}) console.log(cmd) if (stderr) return reject(stderr); resolve({cmd}); }); } function printFileRemote(tipoIngresso, valorIngresso, operador, dataHora, idTicket, totalVenda, reprint, ip){ return new Promise((resolve, reject) => { let cmd = 'sh /root/PDVi_Server/scripts/impressao_remoto.sh "' + tipoIngresso + '" ' + valorIngresso + ' ' + operador + ' "' + dataHora + '" ' + idTicket + ' ' + totalVenda + ' ' + ip if(reprint === 1){ cmd = 'sh /root/PDVi_Server/scripts/reimpressao_remoto.sh "' + tipoIngresso + '" ' + valorIngresso + ' ' + operador + ' "' + dataHora + '" ' + idTicket + ' ' + totalVenda + ' ' + ip } console.log(cmd) const { stdout, stderr, code } = shell.exec(cmd, {async: false}) if (stderr) return reject(stderr); resolve({cmd}); }); } function sendEmail(files, emailAddr){ let array = [] files.forEach(file => { let filename_ = file + '.png' let path_ = './qrcodes/' + filename_ array.push({filename: filename_, path: path_}) }); let emailRecipe = { from: emailFrom, to: emailAddr, subject: emailSubject, html: msgEmail, attachments: array }; transporte.sendMail(emailRecipe, function(err, info){ if(err) throw err; console.log('Email enviado! Leia as informações adicionais: ', info); }); } function coord2offset(x, y, size) { return (size + 1) * y + x + 1; } function customize(bitmap) { const size = bitmap.size; const data = bitmap.data; for (let x = 0; x < size; x++) { for (let y = 0; y < x; y++) { const offset = coord2offset(x, y, size); if (data[offset]) { data[offset] = 255 - Math.abs(x - y); } } } } function generateQrCode(ticket){ let file = pathQRCode + ticket + '.png' return qr.image(ticket, { type: 'png', customize }).pipe( require('fs').createWriteStream(file) ); } /** * Get all itens avaiable for the client on store - All categories */ function getAllProductsClient(){ let sql = "SELECT wp_term_relationships.object_id \ FROM wp_term_relationships \ LEFT JOIN wp_posts ON wp_term_relationships.object_id = wp_posts.ID \ LEFT JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id \ LEFT JOIN wp_terms ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id \ WHERE post_type = 'product' \ AND taxonomy = 'product_cat'"; //log_(sql) con.query(sql, function (err1, result) { if (err1) throw err1; populateProductClientArray(result) }); } /** * Get all itens avaiable for the client on store - By category */ function getProductsClient(){ let sql = "SELECT wp_term_relationships.object_id \ FROM wp_term_relationships \ LEFT JOIN wp_posts ON wp_term_relationships.object_id = wp_posts.ID \ LEFT JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id \ LEFT JOIN wp_terms ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id \ WHERE post_type = 'product' \ AND taxonomy = 'product_cat' \ AND name = '" + clientName + "'"; //log_(sql) con.query(sql, function (err1, result) { if (err1) throw err1; populateProductClientArray(result) }); } /** * Keep the results on clientItensOnline */ function populateProductClientArray(data){ for (var i = 0; i < data.length; i++) { object_id = data[i].object_id clientItensOnline.push(object_id) } console.log("Ids dos produtos do cliente: ", clientName, clientItensOnline) } /** * Search for new products to synchonize. * Use the specific WHERE In combination with the clientItensOline array */ function syncDatabases(){ let sql = "SELECT \ p.ID as order_id,\ p.post_date,\ max( CASE WHEN pm.meta_key = '_billing_email' and p.ID = pm.post_id THEN pm.meta_value END ) as billing_email,\ max( CASE WHEN pm.meta_key = '_billing_first_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_first_name,\ max( CASE WHEN pm.meta_key = '_billing_last_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_last_name,\ max( CASE WHEN pm.meta_key = '_billing_cpf' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_cpf,\ max( CASE WHEN pm.meta_key = '_billing_address_1' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_address_1,\ max( CASE WHEN pm.meta_key = '_billing_address_2' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_address_2,\ max( CASE WHEN pm.meta_key = '_billing_city' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_city,\ max( CASE WHEN pm.meta_key = '_billing_state' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_state,\ max( CASE WHEN pm.meta_key = '_billing_postcode' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_postcode,\ max( CASE WHEN pm.meta_key = '_shipping_first_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_first_name,\ max( CASE WHEN pm.meta_key = '_shipping_last_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_last_name,\ max( CASE WHEN pm.meta_key = '_shipping_address_1' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_address_1,\ max( CASE WHEN pm.meta_key = '_shipping_address_2' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_address_2,\ max( CASE WHEN pm.meta_key = '_shipping_city' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_city,\ max( CASE WHEN pm.meta_key = '_shipping_state' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_state,\ max( CASE WHEN pm.meta_key = '_shipping_postcode' and p.ID = pm.post_id THEN pm.meta_value END ) as _shipping_postcode,\ max( CASE WHEN pm.meta_key = '_order_total' and p.ID = pm.post_id THEN pm.meta_value END ) as order_total,\ max( CASE WHEN pm.meta_key = '_order_tax' and p.ID = pm.post_id THEN pm.meta_value END ) as order_tax,\ max( CASE WHEN pm.meta_key = '_paid_date' and p.ID = pm.post_id THEN pm.meta_value END ) as paid_date,\ ( select group_concat( order_item_name separator '|' ) from wp_woocommerce_order_items where order_id = p.ID ) as order_items \ FROM \ wp_posts p \ JOIN wp_postmeta pm on p.ID = pm.post_id \ JOIN wp_woocommerce_order_items oi on p.ID = oi.order_id \ INNER JOIN wp_woocommerce_order_items as woi on ( woi.order_id = p.ID ) \ INNER JOIN wp_woocommerce_order_itemmeta as woim on ( woim.order_item_id = woi.order_item_id ) \ INNER JOIN wp_term_relationships as wtr on ( wtr.object_id = woim.meta_value ) \ WHERE \ post_type = 'shop_order' \ AND sync = 0 \ AND post_status = 'wc-completed' \ AND wtr.object_id IN (" + clientItensOnline + ") \ GROUP BY \ p.ID" //log_(sql) con.query(sql, function (err1, result) { if (err1) throw err1; if(result.length > 0) syncDatabaseContinue(result) }); } /** * Separate the order products and create on the local base the specifics itens */ function syncDatabaseContinue(data){ log_("Sincronizando novas compras") let sqlCashier = "INSERT INTO 3a_caixa_registrado (fk_id_usuario, data_caixa_registrado, obs_log_venda) \ VALUES (" + idUserOnline + ", NOW(), 'Gerado pelo sistema PDVi Web');" log_(sqlCashier) conLocal.query(sqlCashier, function (err1, result) { if (err1) throw err1; let sql = "SELECT 3a_caixa_registrado.id_caixa_registrado \ FROM 3a_caixa_registrado \ WHERE 3a_caixa_registrado.fk_id_usuario = " + idUserOnline + " \ ORDER BY data_caixa_registrado DESC LIMIT 1" //log_(sql) conLocal.query(sql, function (err, result) { if (err) throw err; syncDatabaseFinish(data, result) }); }); } function syncDatabaseFinish(data, caixa){ let id_caixa_registrado = caixa[0].id_caixa_registrado log_("Último caixa registrado: " + id_caixa_registrado) for (var i = 0; i < data.length; i++) { let itens = data[i] let order_items = itens.order_items let arr = order_items.toString().split("|"); for (var k = 0; k < arr.length; k++) { let produto = arr[k] createTicketBaseLocal(produto, itens, i, id_caixa_registrado) } } } /** * Search information about the product on local base */ function createTicketBaseLocal(productName, itens, k, id_caixa_registrado){ let sql = "SELECT * FROM 3a_produto WHERE nome_produto = '" + productName + "';"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; let product = result[0] if(product){ let prefixo = product.prefixo_produto let prefixo_ini=prefixo*1000000; let prefixo_fim=prefixo_ini+999999; product.fk_id_caixa_venda = id_caixa_registrado let sqlPrefix = "SELECT IFNULL(MAX(id_estoque_utilizavel) + 1, " + prefixo_ini + ") AS id_estoque_utilizavel \ FROM 3a_estoque_utilizavel \ WHERE id_estoque_utilizavel \ BETWEEN " + prefixo_ini + " \ AND " + prefixo_fim + ";" conLocal.query(sqlPrefix, function (err1, result1) { if (err1) throw err1; let id_estoque_utilizavel = result1[0].id_estoque_utilizavel let id_estoque = id_estoque_utilizavel + k createTicketDatabaseLocal(product, id_estoque) createTicketBaseLocalContinue(result1, itens, product) //decrementStock(product) }); } }); } function createTicketBaseLocalContinue(data, itens, product){ let order_id = itens.order_id updateTicketsSyncIds(order_id) let order_items = itens.order_items let post_date = itens.post_date let billing_email = itens.billing_email let _billing_first_name = itens._billing_first_name let _billing_last_name = itens._billing_last_name let _billing_address_1 = itens._billing_address_1 let _billing_address_2 = itens._billing_address_2 let _billing_city = itens._billing_city let _billing_cpf = itens._billing_cpf let _billing_state = itens._billing_state let _billing_postcode = itens._billing_postcode let _shipping_first_name = itens._shipping_first_name let _shipping_last_name = itens._shipping_last_name let _shipping_address_1 = itens._shipping_address_1 let _shipping_address_2 = itens._shipping_address_2 let _shipping_city = itens._shipping_city let _shipping_state = itens._shipping_state let _shipping_postcode = itens._shipping_postcode let order_total = itens.order_total let order_tax = itens.order_tax let paid_date = itens.paid_date let id_estoque_utilizavel = data[0].id_estoque_utilizavel let sql = "INSERT INTO vendas_online (order_id, post_date, billing_email, _billing_first_name, _billing_last_name, _billing_address_1,\ _billing_address_2, _billing_city, _billing_state, _billing_postcode, _shipping_first_name, _shipping_last_name, _shipping_address_1, _shipping_address_2, _shipping_city, _shipping_state,\ _shipping_postcode, order_total, order_tax, paid_date, order_items, id_estoque_utilizavel, _billing_cpf) VALUES \ (" + order_id + ", '" + post_date + "', '" + billing_email + "', '" + _billing_first_name + "', '" + _billing_last_name + "', '" + _billing_address_1 + "', '" + _billing_address_2 + "', '" + _billing_city + "', '" + _billing_state + "', '" + _billing_postcode + "', '" + _shipping_first_name + "', '" + _shipping_last_name + "', '" + _shipping_address_1 + "', '" + _shipping_address_2 + "', '" + _shipping_city + "', '" + _shipping_state + "', '" + _shipping_postcode + "', " + order_total + ", " + order_tax + ", '" + paid_date + "', '" + order_items + "', " + id_estoque_utilizavel + ", '" + _billing_cpf + "');"; conLocal.query(sql, function (err1, result) { if (err1) throw err1; }); } function createTicketDatabaseLocal(product, id_estoque_utilizavel){ let id_produto = product.id_produto let userId = 1 let sql = "INSERT INTO 3a_estoque_utilizavel (id_estoque_utilizavel,fk_id_produto,fk_id_tipo_estoque,fk_id_usuarios_inclusao,data_inclusao_utilizavel, impresso) \ VALUES(" + id_estoque_utilizavel + ", " + id_produto + ", 1," + userId + ", NOW(), 1);" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; soldTicket(product, "ONLINE", id_estoque_utilizavel, userId) }); } function soldTicket(produto, tipoPagamento, last, userId){ let user = userId let obs = "Vendido pelo sistema online" let ip = "localhost" let validade = 1 let id_estoque_utilizavel = last let fk_id_subtipo_produto = produto.fk_id_subtipo_produto let valor = produto.valor_produto let id_produto = produto.id_produto let fk_id_caixa_venda = produto.fk_id_caixa_venda let sql = "INSERT INTO 3a_log_vendas (\ fk_id_estoque_utilizavel,\ fk_id_usuarios,\ fk_id_produto,\ fk_id_subtipo_produto,\ fk_id_caixa_registrado,\ valor_log_venda,\ data_log_venda,\ obs_log_venda,\ ip_maquina_venda,\ nome_maquina_venda,\ fk_id_tipo_pagamento,\ fk_id_validade,\ data_log_venda) \ VALUES(" + id_estoque_utilizavel + ", " + user + ", " + id_produto + ", " + fk_id_subtipo_produto + ", " + fk_id_caixa_venda + ", " + + valor + ", " + "NOW(), '" + obs + "', '" + ip + "'," + "'PDVi'," + "(SELECT 3a_tipo_pagamento.id_tipo_pagamento FROM 3a_tipo_pagamento WHERE 3a_tipo_pagamento.nome_tipo_pagamento = '" + tipoPagamento + "')," + validade + ",\ NOW());" conLocal.query(sql, function (err2, result2) { if (err2) throw err2; //log_(sql) }); } function updateTicketsSyncIds(id_order){ let sql = "UPDATE wp_posts SET sync = 1 WHERE ID = " + id_order + ";"; //log_(sql) con.query(sql, function (err1, result) { if (err1) throw err1; }); } function payProduct(req, res){ let products = req.body.products errorOnSelling = [] var promiseArray = []; let isPrePrinted = req.body.isPrePrinted let queuePrePrinted = [] for (var i = 0, len = products.length; i < len; i++) { promiseArray.push(new Promise((resolve) => { let product = products[i] let isParking = product.parking if(isParking) payParking(req, product) else if(isPrePrinted){ if(! queuePrePrinted.includes(product.id_estoque_utilizavel)){ queuePrePrinted.push(product.id_estoque_utilizavel) payProductPrePrinted(req, product) .then(() => { resolve({"success": product}) }) } } else { payProductNormal(req, product) .then(() => { resolve({"success": product}) }) } }) ) } res.json(Promise.all(promiseArray) ); } function payProductPrePrinted(req, product){ let promise = new Promise((resolve) => { let quantity = product.quantity let selectedsIds = product.selectedsIds for(var j = 0; j < quantity; j++){ let idSubtypeChanged = selectedsIds[j] if(idSubtypeChanged > 0) product.fk_id_subtipo_produto = idSubtypeChanged soldTicket(req, product, product.id_estoque_utilizavel) .then(() => { resolve(true) }) } }); return promise } function payProductNormal(req, product){ return new Promise((resolvePrincipal, reject) => { let prefixo = product.prefixo_produto let prefixo_ini=prefixo*1000000; let prefixo_fim=prefixo_ini+999999; let userName = req.body.userName let finalValue = req.body.finalValue let nome_produto = product.nome_produto let valor_produto = product.valor_produto let quantity = product.quantity let ip = req.body.ip console.log('Recebido pagamento do IP ' + ip) let sql = "SELECT IFNULL(MAX(id_estoque_utilizavel), " + prefixo_ini + ") AS TOTAL \ FROM 3a_estoque_utilizavel \ WHERE id_estoque_utilizavel \ BETWEEN " + prefixo_ini + " \ AND " + prefixo_fim + ";" conLocal.query(sql, function (err1, result) { if (err1) reject(err1); //log_(sql) payProductContinue(req, product, result) .then(() => { let id_estoque_utilizavel = result[0].TOTAL let promises = [] let data_log_venda = moment().format() for(var j = 0; j < quantity; j++){ let promise = new Promise((resolve) => { let last = ++id_estoque_utilizavel if(printerLocal === 1){ printFile(nome_produto, valor_produto, userName, data_log_venda, last, finalValue, 0) .then(() => { promises.push(promise) resolve() }) } else { printFileRemote(nome_produto, valor_produto, userName, data_log_venda, last, finalValue, 0, ip) .then(() => { promises.push(promise) resolve() }) } }) } Promise.all(promises).then(() => { resolvePrincipal() }); }) }); }) } function payParking(req, product){ let userId = req.body.userId let idPayment = req.body.idPayment let quantity = product.quantity let last = product.id_estoque_utilizavel for(var j = 0; j < quantity; j++){ soldTicket(product, idPayment, last, userId) } } function payProductContinue(req, product, data){ return new Promise((promisePrincipal, reject) => { let id_estoque_utilizavel = data[0].TOTAL let userId = req.body.userId let id_produto = product.id_produto let quantity = product.quantity let selectedsIds = product.selectedsIds let urls = product.urls if(!urls){ urls = [] } let promises = [] for(var j = 0; j < quantity; j++){ let last = ++id_estoque_utilizavel let idSubtypeChanged = selectedsIds[j] let url = urls[j] if(!url) url = "" let sql = "INSERT INTO 3a_estoque_utilizavel (id_estoque_utilizavel,fk_id_produto,fk_id_tipo_estoque,fk_id_usuarios_inclusao,data_inclusao_utilizavel, impresso, url, utilizado) \ VALUES(" + last + ", " + id_produto + ", 1," + userId + ", NOW(), 1, '" + url + "', 0);" //log_(sql) let dbquery = conLocal.query(sql, function (err1, result) { if (err1) reject(err1); if(idSubtypeChanged > 0) product.fk_id_subtipo_produto = idSubtypeChanged soldTicket(req, product, last) .then(() => { promises.push(dbquery) }) }); } Promise.all(promises).then(() => { promisePrincipal() }); }); } async function soldTicket(req, product, last){ return new Promise((resolve, reject) => { let userId = req.body.userId let userName = req.body.userName let finalValue = req.body.finalValue let idPayment = req.body.idPayment let valor_produto = product.valor_produto product.userName = userName product.finalValue = finalValue let user = userId let obs = "Vendido pelo sistema" let ip = "localhost" let validade = 1 let id_estoque_utilizavel = last let fk_id_subtipo_produto = product.fk_id_subtipo_produto let id_produto = product.id_produto let fk_id_caixa_venda = product.id_caixa_registrado product.id_estoque_utilizavel = last id_estoque_utilizavel = product.id_estoque_utilizavel if(fk_id_caixa_venda === undefined) fk_id_caixa_venda = product.fk_id_caixa_venda let sql = "INSERT INTO 3a_log_vendas (\ fk_id_estoque_utilizavel,\ fk_id_usuarios,\ fk_id_produto,\ fk_id_subtipo_produto,\ fk_id_caixa_registrado,\ valor_log_venda,\ data_log_venda,\ obs_log_venda,\ ip_maquina_venda,\ nome_maquina_venda,\ fk_id_tipo_pagamento,\ fk_id_validade) \ VALUES(" + id_estoque_utilizavel + ", " + user + ", " + id_produto + ", " + fk_id_subtipo_produto + ", " + fk_id_caixa_venda + ", " + + valor_produto + ", " + "NOW(), '" + obs + "', '" + ip + "'," + "'PDVi'," + "(SELECT 3a_tipo_pagamento.id_tipo_pagamento FROM 3a_tipo_pagamento WHERE 3a_tipo_pagamento.nome_tipo_pagamento = '" + idPayment + "')," + validade + ");" //log_(sql) conLocal.query(sql, function (err, result) { if (err){ errorOnSelling.push(id_estoque_utilizavel) reject(err); } resolve() }); }); } async function decrementStock(id_produto){ let promise = new Promise((resolve, reject) => { let sql = "UPDATE 3a_produto SET stock = (stock - 1) WHERE id_produto = " + id_produto + ";" //log_(sql) conLocal.query(sql, function (err, result) { if (err){ errorOnSelling.push(id_estoque_utilizavel) if (err) reject(err); } else resolve(true) }); }); return promise } async function decrementStockOnline(nome_produto){ let promise = new Promise((resolve, reject) => { let sql = "UPDATE vendas_online.wp_postmeta SET meta_value = (meta_value - 1) WHERE meta_key = '_stock' AND post_id = \ (SELECT wp_posts.ID FROM wp_posts WHERE wp_posts.post_title = '" + nome_produto + "' LIMIT 1);" //log_(sql) con.query(sql, function (err, result) { if (err) reject(err); else resolve(true) }); }); return promise } function confirmCashDrain(req, res){ let idUser = req.body.idUser let idSupervisor = req.body.idSupervisor let drainValue = req.body.drainValue let sql = "INSERT INTO 3a_sangria (fk_id_usuario, fk_id_supervisor, data_sangria, valor_sangria) \ VALUES (" + idUser + ", " + idSupervisor + ", NOW(), " + drainValue + ")"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function confirmCashChange(req, res){ let idUser = req.body.idUser let idSupervisor = req.body.idSupervisor let changeValue = req.body.changeValue let sql = "INSERT INTO 3a_troco (fk_id_usuario, fk_id_supervisor, data_inclusao, valor_inclusao) \ VALUES (" + idUser + ", " + idSupervisor + ", NOW(), " + changeValue + ")"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getLastCashierId(req, res){ let idUser = req.body.idUser let sqlCashier = "INSERT INTO 3a_caixa_registrado (fk_id_usuario, data_caixa_registrado, obs_log_venda) \ VALUES (" + idUser + ", NOW(), 'Gerado pelo sistema PDVi Web');" log_(sqlCashier) conLocal.query(sqlCashier, function (err1, result) { if (err1) throw err1; let sql = "SELECT 3a_caixa_registrado.id_caixa_registrado \ FROM 3a_caixa_registrado \ WHERE 3a_caixa_registrado.fk_id_usuario = " + idUser + " \ ORDER BY data_caixa_registrado DESC LIMIT 1" //log_(sql) conLocal.query(sql, function (err2, resultEnd) { if (err2) throw err2; res.json({"success": resultEnd}); }); }); } function getTicketOperator(req, res){ let idUser = req.body.idUser let start = req.body.start let end = req.body.end let sql = "SELECT *, false AS checked \ FROM 3a_estoque_utilizavel \ INNER JOIN 3a_log_vendas ON 3a_log_vendas.fk_id_estoque_utilizavel = 3a_estoque_utilizavel.id_estoque_utilizavel \ INNER JOIN 3a_caixa_registrado ON 3a_caixa_registrado.id_caixa_registrado = 3a_log_vendas.fk_id_caixa_registrado \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_estoque_utilizavel.fk_id_produto \ INNER join 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_log_vendas.fk_id_subtipo_produto \ WHERE 3a_log_vendas.fk_id_usuarios = " + idUser + " \ AND 3a_log_vendas.data_log_venda BETWEEN '" + start + "' AND '" + end + "' \ ORDER BY 3a_log_vendas.data_log_venda DESC;" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getTicketOperatorStr(req, res){ let idUser = req.body.idUser let start = req.body.start let end = req.body.end let str = req.body.str let sql = "SELECT *, false AS checked \ FROM 3a_estoque_utilizavel \ INNER JOIN 3a_log_vendas ON 3a_log_vendas.fk_id_estoque_utilizavel = 3a_estoque_utilizavel.id_estoque_utilizavel \ INNER JOIN 3a_caixa_registrado ON 3a_caixa_registrado.id_caixa_registrado = 3a_log_vendas.fk_id_caixa_registrado \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_estoque_utilizavel.fk_id_produto \ INNER join 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_log_vendas.fk_id_subtipo_produto \ WHERE 3a_log_vendas.fk_id_usuarios = " + idUser + " \ AND 3a_log_vendas.data_log_venda BETWEEN '" + start + "' AND '" + end + "' \ AND 3a_estoque_utilizavel.id_estoque_utilizavel = " + str + " \ ORDER BY 3a_log_vendas.data_log_venda DESC;" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getTicketsCashier(req, res){ let idCashier = req.body.idCashier let sql = "SELECT *, false AS checked \ FROM 3a_estoque_utilizavel \ INNER JOIN 3a_log_vendas ON 3a_log_vendas.fk_id_estoque_utilizavel = 3a_estoque_utilizavel.id_estoque_utilizavel \ INNER JOIN 3a_caixa_registrado ON 3a_caixa_registrado.id_caixa_registrado = 3a_log_vendas.fk_id_caixa_registrado \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_estoque_utilizavel.fk_id_produto \ INNER join 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_log_vendas.fk_id_subtipo_produto \ WHERE 3a_caixa_registrado.id_caixa_registrado = " + idCashier + " \ ORDER BY 3a_estoque_utilizavel.id_estoque_utilizavel DESC;" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getTicketParking(req, res){ let id_estoque_utilizavel = req.body.idTicket let sql = "SELECT 3a_produto.nome_produto,\ 3a_produto.prefixo_produto,\ 3a_produto.id_produto,\ 3a_produto.valor_produto,\ 3a_log_vendas.data_log_venda,\ 3a_ponto_acesso.nome_ponto_acesso,\ 3a_produto.fk_id_subtipo_produto,\ 3a_estoque_utilizavel.id_estoque_utilizavel,\ 3a_estoque_utilizavel.data_inclusao_utilizavel \ FROM 3a_estoque_utilizavel \ LEFT JOIN 3a_log_vendas ON 3a_log_vendas.fk_id_estoque_utilizavel = 3a_estoque_utilizavel.id_estoque_utilizavel \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_estoque_utilizavel.fk_id_produto \ INNER join 3a_ponto_acesso ON 3a_ponto_acesso.id_ponto_acesso = 3a_estoque_utilizavel.fk_id_ponto_acesso_gerado \ WHERE id_estoque_utilizavel = " + id_estoque_utilizavel + ";"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getCashDrain(req, res){ let idUser = req.body.idUser let start = req.body.start let end = req.body.end let sql = "SELECT SUM(valor_sangria) AS TOTAL \ FROM 3a_sangria where fk_id_usuario = " + idUser + " \ AND data_sangria BETWEEN '" + start + "' AND '" + end + "';"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getUsers(req, res){ let sql = "SELECT * FROM 3a_usuarios;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getUsersByName(req, res){ let name = req.body.name let sql = "SELECT * FROM 3a_usuarios WHERE login_usuarios LIKE '%" + name + "%';"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getErros(req, res){ res.json({"errorOnSelling": errorOnSelling}); } function recoverPaymentErros(req, res){ let tickets = req.body.tickets tickets.forEach(element => { let sql1 = "DELETE FROM 3a_estoque_utilizavel WHERE id_estoque_utilizavel = " + element + " LIMIT 1;"; let sql2 = "DELETE FROM 3a_log_vendas WHERE fk_id_estoque_utilizavel = " + element + " LIMIT 1;"; conLocal.query(sql1, function (err1, result) { //if (err1) throw err1; log_(sql1) }); conLocal.query(sql2, function (err1, result) { //if (err1) throw err1; log_(sql2) }); }); res.json({"success": 1}); } function getAllReceptors(req, res){ let sql = "SELECT * FROM 3a_ponto_acesso;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function systemCommand(req, res){ console.log(req.body) let cmd = req.body.cmd let idUser = req.body.idUser let ipPonto = req.body.ipPonto let sql = "INSERT INTO comando_sistema (id_comando, id_user, ip_ponto) \ VALUES (" + cmd + "," + idUser + ",'" + ipPonto + "');"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } async function systemCommandLocal(req, res) { console.log("Executando comando...") const { stdout, stderr } = await exec('xdotool key ctrl+Tab'); console.log('stdout:', stdout); console.log('stderr:', stderr); res.json({"success": stdout}); } function useTicketMultiple(req, res){ let idTotem = req.body.id let idArea = req.body.idArea let ticket = req.body.ticket log_('Totem: '+ idTotem + ' - Marcando ticket como utilizado:', ticket, idArea) let sql1 = "INSERT INTO 3a_log_utilizacao \ (3a_log_utilizacao.fk_id_estoque_utilizavel,\ 3a_log_utilizacao.fk_id_ponto_acesso,\ 3a_log_utilizacao.fk_id_area_acesso,\ 3a_log_utilizacao.fk_id_usuario,\ 3a_log_utilizacao.data_log_utilizacao) \ VALUES (" + ticket + "," + idTotem + "," + idArea + ", 1, NOW());"; conLocal.query(sql1, function (err1, result) { if (err1) throw err1; let sql_utilizacao = "UPDATE 3a_estoque_utilizavel \ SET 3a_estoque_utilizavel.utilizado = 1 \ WHERE id_estoque_utilizavel = " + ticket + " LIMIT 1;" log_(sql_utilizacao) con.query(sql_utilizacao, function (err2, result2) { if (err2) throw err2; let sql = "UPDATE \ 3a_area_acesso \ SET 3a_area_acesso.lotacao_area_acesso = 3a_area_acesso.lotacao_area_acesso + 1 \ WHERE 3a_area_acesso.id_area_acesso = " + idArea + ";" conLocal.query(sql, function (err3, result3) { res.json({"success": result}); }); }); }); } function getSessions(req, res){ let sql = "SELECT *, 0 AS lotacaoAtual FROM sessoes;" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getSessionsName(req, res){ let sql = "SELECT *, 0 AS lotacaoAtual FROM sessoes WHERE nome LIKE '%" + req.body.name + "%'; " //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getSessionsProducts(req, res){ let idSessao = req.body.idSessao let sql = "SELECT 3a_produto.nome_produto \ FROM sessoes \ INNER JOIN sessoes_produtos ON sessoes_produtos.id_sessao = sessoes.id \ INNER JOIN 3a_produto ON 3a_produto.id_produto = sessoes_produtos.id_produto \ WHERE sessoes_produtos.id_sessao = " + idSessao + ";" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getProductsTypes(req, res){ let sql = "SELECT * FROM 3a_tipo_produto;" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getProducts(req, res){ let sql = "SELECT * FROM 3a_produto ORDER BY posicao_produto_imprimivel;" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function addUsers(req, res){ let info = req.body let name = info.username //let status = info.status === "Ativo" ? 1 : 0 let status = 1 let password = <PASSWORD>.password let acl = info.acl let ip = info.ip let sql = "INSERT INTO 3a_usuarios (login_usuarios, fk_id_nivel_acesso, ativo_usuarios, senha_usuarios, senha_usuarios_pdvi, ip_pdvi) \ VALUES('" + name + "', (SELECT id_nivel_acesso FROM 3a_nivel_acesso WHERE nome_nivel_acesso = '" + acl + "' LIMIT 1), " + status + ", '" + password + "', '" + password + "', '" + ip + "');" log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function updateUsers(req, res){ let info = req.body let name = info.username let status = 1 let password = <PASSWORD> let acl = info.acl let ip = info.ip let sql = "UPDATE 3a_usuarios SET \ login_usuarios = '" + name + "', \ fk_id_nivel_acesso = " + acl + ",\ ativo_usuarios = " + status + ",\ senha_usuarios = '" + password + "' \ senha_usuarios_pdvi = '" + password + "' \ ip_pdvi = '" + ip + "' \ WHERE id = " + info.id + ";" log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function addSession(req, res){ let info = req.body.info let nome = info.nome let status = info.status === "Ativo" ? 1 : 0 let obs = info.obs let lotacao = info.lotacao let sql = "INSERT INTO sessoes (nome, status, lotacao, obs) \ VALUES('" + nome + "', " + status + ", " + lotacao + ", '" + obs + "');" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; addSessionContinue(req, res) }); } function addSessionContinue(req, res){ delSessionTipos(req, res) .then(() => { addSessionTipos(req, res) .then(() => { res.json({"success": true}); }) .catch(error => { res.json({"success": false}); }) }) .catch(error => { res.json({"success": false}); }) } function addSessionTipos(req, res){ return new Promise(function(resolve, reject){ let info = req.body.info let tipos = info.tipos let nome = info.nome let promises = [] tipos.forEach(element => { let sql = "INSERT INTO sessoes_produtos (id_produto, id_sessao) \ VALUES (\ (SELECT id_produto FROM 3a_produto WHERE nome_produto = '" + element + "' LIMIT 1), \ (SELECT id FROM sessoes WHERE nome = '" + nome + "' LIMIT 1));" //log_(sql) let dbquery = conLocal.query(sql, function (err1, result) { if (err1) reject(err1); }); promises.push(dbquery) }) Promise.all(promises).then(() => { resolve() }); }); } function delSessionTipos(req, res){ return new Promise(function(resolve, reject){ let info = req.body.info let nome = info.nome let sql = "DELETE FROM sessoes_produtos WHERE id_sessao = \ (SELECT id FROM sessoes WHERE nome = '" + nome + "' LIMIT 1);" conLocal.query(sql, function (err1, result) { if (err1) { reject(err1); } resolve() }); }); } function updateSession(req, res){ let info = req.body.info let nome = info.nome let status = info.status === "Ativo" ? 1 : 0 let obs = info.obs let lotacao = info.lotacao let sql = "UPDATE sessoes SET \ nome = '" + nome + "', \ status = " + status + ",\ lotacao = " + lotacao + ",\ obs = '" + obs + "' \ WHERE id = " + info.id + ";" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; addSessionContinue(req, res) }); } function removeSession(req, res){ let idSession = req.body.idSession let promises = [] let sql1 = "DELETE FROM sessoes WHERE id = " + idSession + " LIMIT 1;"; let sql2 = "DELETE FROM sessoes_produtos WHERE id_sessao = " + idSession + ";"; let dbquery1 = conLocal.query(sql1, function (err1, result) { if (err1) throw err1; }); let dbquery2 = conLocal.query(sql2, function (err1, result) { if (err1) throw err1; }); promises.push(dbquery1) promises.push(dbquery2) Promise.all(promises).then(() => { res.json({"success": 1}); }); } function getSessionsTicket(req, res){ let sql = "SELECT * FROM sessoes \ INNER JOIN sessoes_produtos ON sessoes_produtos.id_sessao = sessoes.id \ WHERE sessoes_produtos.id_produto = " + req.body.idProduto + ";" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } function getSessionsTicketTotal(req, res){ let nowstr = moment().format('YYYY-MM-DD') let endstr = moment().format('YYYY-MM-DD') nowstr += 'T00:00:00' endstr += 'T23:59:59' let sql = "SELECT COUNT(fk_id_estoque_utilizavel) AS lotacaoAtual \ FROM 3a_log_vendas \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_log_vendas.fk_id_produto \ INNER join 3a_tipo_produto ON 3a_tipo_produto.id_tipo_produto = 3a_produto.fk_id_tipo_produto \ WHERE 3a_tipo_produto.id_tipo_produto = " + req.body.idTipoProduto + " \ AND data_log_venda BETWEEN '" + nowstr + "' AND '" + endstr + "';" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); } app.post('/getAllOrders', function(req, res) { let start = req.body.start let end = req.body.end let sql = "SELECT * FROM vendas_online WHERE datetime BETWEEN '" + start + "' AND '" + end + "';" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getAllOrdersByName', function(req, res) { let name = req.body.name let start = req.body.start let end = req.body.end let sql = "SELECT * \ FROM vendas_online \ WHERE _billing_first_name LIKE '%" + name + "%' \ AND datetime BETWEEN '" + start + "' AND '" + end + "';" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getAllOrdersByCPF', function(req, res) { let name = req.body.name let start = req.body.start let end = req.body.end let sql = "SELECT * \ FROM vendas_online \ WHERE _billing_cpf LIKE '%" + name + "%' \ AND datetime BETWEEN '" + start + "' AND '" + end + "';" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/sendEmail', function(req, res) { let idTicket = req.body.idTicket let filename_ = idTicket + '.png' let path_ = './qrcodes/' + filename_ generateQrCode(idTicket) let emailAddr = req.body.email let email = { from: emailFrom, to: emailAddr, subject: emailSubject, html: msgEmail, attachments: {filename: filename_, path: path_} }; transporte.sendMail(email, function(err, info){ if(err) throw err; console.log('Email enviado! Leia as informações adicionais: ', info); res.json({"success": "true"}); }); }); app.post('/printTicket', function(req, res) { let userName = req.body.userName let finalValue = req.body.finalValue let ticket = req.body.ticket let nome_produto = ticket.nome_produto let valor_produto = ticket.valor_produto let data_log_venda = ticket.data_log_venda let fk_id_estoque_utilizavel = ticket.fk_id_estoque_utilizavel printFile(nome_produto, valor_produto, userName, data_log_venda, fk_id_estoque_utilizavel, finalValue, 0) res.json({"success": "true"}); }); app.post('/printTicketMultiple', function(req, res) { let tickets = req.body.tickets let userName = req.body.userName let reprint = req.body.reprint let promises = [] for (var i = 0, len = tickets.length; i < len; ++i) { let promise = new Promise((resolve) => { let ticket = tickets[i] let nome_produto = ticket.nome_produto let valor_produto = ticket.valor_produto let data_log_venda = ticket.data_log_venda let fk_id_estoque_utilizavel = ticket.fk_id_estoque_utilizavel let valor_log_venda = ticket.valor_log_venda printFile(nome_produto, valor_produto, userName, data_log_venda, fk_id_estoque_utilizavel, valor_log_venda, reprint) resolve() }); promises.push(promise) } Promise.all(promises).then(() => { res.json({"success": "true"}); resolve(console.log(promises.length + ' Todas impressões enviadas com sucesso')) }); }); app.post('/printTicketOnline', function(req, res) { let userName = req.body.userName let finalValue = req.body.finalValue let ticket = req.body.ticket let nome_produto = ticket.nome_produto let valor_produto = ticket.valor_produto let data_log_venda = ticket.data_log_venda let fk_id_estoque_utilizavel = ticket.fk_id_estoque_utilizavel printFile(nome_produto, valor_produto, userName, data_log_venda, fk_id_estoque_utilizavel, finalValue, 0) res.json({"success": "true"}); }); app.post('/printTicketMultipleOnline', function(req, res) { let tickets = req.body.tickets let userName = req.body.userName let reprint = req.body.reprint for (var i = 0, len = tickets.length; i < len; ++i) { let ticket = tickets[i] let nome_produto = ticket.nome_produto let valor_produto = ticket.valor_produto let data_log_venda = ticket.data_log_venda let fk_id_estoque_utilizavel = ticket.fk_id_estoque_utilizavel let valor_log_venda = ticket.valor_log_venda printFile(nome_produto, valor_produto, userName, data_log_venda, fk_id_estoque_utilizavel, valor_log_venda, reprint) } res.json({"success": "true"}); }); app.post('/getAreas', function(req, res) { let idTotem = req.body.id log_('Totem: '+ idTotem + ' - Verificando informações da areas: ') let sql = "SELECT 3a_area_venda.* FROM 3a_area_venda;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getPaymentsMethods', function(req, res) { let idTotem = req.body.id log_('Totem: '+ idTotem + ' - Verificando metodos de pagamento: ') let sql = "SELECT 3a_tipo_pagamento.* FROM 3a_tipo_pagamento;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getAreasByName', function(req, res) { let idTotem = req.body.id let name = req.body.name log_('Totem: '+ idTotem + ' - Verificando informações da areas por nome: ' + name) let sql = "SELECT 3a_area_venda.* FROM 3a_area_venda WHERE nome_area_venda LIKE '%" + name + "%';"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/syncStock', function(req, res) { let idTotem = req.body.id log_('Administrador: ' + idTotem + ' - Sincronizando com estoque online do cliente') let sql = "SELECT p.ID,\ p.post_title 'nome',\ MAX(CASE WHEN meta.meta_key = '_stock' THEN meta.meta_value END) 'Stock' \ FROM wp_posts AS p \ JOIN wp_postmeta AS meta ON p.ID = meta.post_ID \ LEFT JOIN \ ( \ SELECT pp.id, \ GROUP_CONCAT(t.name SEPARATOR ' > ') AS name \ FROM wp_posts AS pp \ JOIN wp_term_relationships tr ON pp.id = tr.object_id \ JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id \ JOIN wp_terms t ON tt.term_id = t.term_id \ || tt.parent = t.term_id \ WHERE tt.taxonomy = 'product_cat' \ GROUP BY pp.id, tt.term_id \ ) cat ON p.id = cat.id \ WHERE (p.post_type = 'product' OR p.post_type = 'product_variation') \ AND meta.meta_key IN ('_stock') \ AND meta.meta_value is not null \ GROUP BY p.ID"; //log_(sql) con.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getAllProducts', function(req, res) { let idTotem = req.body.id log_('Administrador: ' + idTotem + ' - Verificando todos os produtos do cliente') let sql = "SELECT 3a_produto.*, \ 3a_subtipo_produto.* \ FROM 3a_produto \ INNER JOIN 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_produto.fk_id_subtipo_produto \ INNER JOIN 3a_area_venda_produtos ON 3a_area_venda_produtos.fk_id_produto = 3a_produto.id_produto \ ORDER BY posicao_produto_imprimivel;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getProductsAttachments', function(req, res) { let idTotem = req.body.id log_('Administrador: ' + idTotem + ' - Verificando todos os produtos com anexo do cliente') let idUser = req.body.idUser let start = req.body.start let end = req.body.end let sql = "SELECT *, false AS checked \ FROM 3a_estoque_utilizavel \ INNER JOIN 3a_log_vendas ON 3a_log_vendas.fk_id_estoque_utilizavel = 3a_estoque_utilizavel.id_estoque_utilizavel \ INNER JOIN 3a_caixa_registrado ON 3a_caixa_registrado.id_caixa_registrado = 3a_log_vendas.fk_id_caixa_registrado \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_estoque_utilizavel.fk_id_produto \ INNER join 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_log_vendas.fk_id_subtipo_produto \ WHERE 3a_log_vendas.fk_id_usuarios = " + idUser + " \ AND 3a_log_vendas.data_log_venda BETWEEN '" + start + "' AND '" + end + "' \ ORDER BY 3a_log_vendas.data_log_venda DESC;" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getProductsAreaByName', function(req, res) { let name = req.body.name let idUser = req.body.idUser let start = req.body.start let end = req.body.end let idTotem = req.body.id log_('Administrador: ' + idTotem + ' - Verificando todos os produtos com anexo do cliente por ticket') let sql = "SELECT *, false AS checked \ FROM 3a_estoque_utilizavel \ INNER JOIN 3a_log_vendas ON 3a_log_vendas.fk_id_estoque_utilizavel = 3a_estoque_utilizavel.id_estoque_utilizavel \ INNER JOIN 3a_caixa_registrado ON 3a_caixa_registrado.id_caixa_registrado = 3a_log_vendas.fk_id_caixa_registrado \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_estoque_utilizavel.fk_id_produto \ INNER join 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_log_vendas.fk_id_subtipo_produto \ WHERE 3a_log_vendas.fk_id_usuarios = " + idUser + " \ AND 3a_log_vendas.data_log_venda BETWEEN '" + start + "' AND '" + end + "' \ AND 3a_estoque_utilizavel = " + name + "\ ORDER BY 3a_log_vendas.data_log_venda DESC;" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getProductsArea', function(req, res) { let idTotem = req.body.id let idArea = req.body.idArea log_('Totem: '+ idTotem + ' - Verificando produtos da areas: ' + idArea) let sql = "SELECT 3a_produto.*, \ 0 AS quantity, \ 3a_subtipo_produto.nome_subtipo_produto,\ 0.00 AS valor_total \ FROM 3a_produto \ INNER JOIN 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_produto.fk_id_subtipo_produto \ INNER JOIN 3a_area_venda_produtos ON 3a_area_venda_produtos.fk_id_produto = 3a_produto.id_produto \ WHERE 3a_area_venda_produtos.fk_id_area_venda = " + idArea + " \ ORDER BY posicao_produto_imprimivel ASC;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getProductsAreaByName', function(req, res) { let idTotem = req.body.id let idArea = req.body.idArea let name = req.body.name log_('Totem: '+ idTotem + ' - Verificando produtos da areas: ' + idArea) let sql = "SELECT 3a_produto.*, 0 AS quantity, 0.00 AS valor_total \ FROM 3a_produto \ INNER JOIN 3a_area_venda_produtos ON 3a_area_venda_produtos.fk_id_produto = 3a_produto.id_produto \ WHERE 3a_area_venda_produtos.fk_id_area_venda = " + idArea + " \ AND 3a_produto.nome_produto LIKE '%" + name + "%' \ ORDER BY 3a_produto.posicao_produto_imprimivel;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getSubtypesProducts', function(req, res) { let idTotem = req.body.id let idProduct = req.body.idProduct log_('Totem: '+ idTotem + ' - Verificando subtipos do produto: ' + idProduct) let sql = "SELECT 3a_subtipo_produto.*, 0 as quantity \ FROM 3a_subtipo_produto where fk_id_tipo_produto = " + idProduct + ";"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/payProducts', function(req, res) { payProduct(req, res) }); app.post('/getAcls', function(req, res) { let sql = "SELECT * FROM 3a_nivel_acesso;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result, "ip": ipAddressLocal}); }); }); app.post('/getAuth', function(req, res) { let email = req.body.email let password = <PASSWORD> let sql = "SELECT * FROM 3a_usuarios where login_usuarios = '" + email + "' \ AND senha_usuarios_pdvi = '" + password + "';"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result, "ip": ipAddressLocal}); }); }); app.post('/getAuthSupervisor', function(req, res) { let sql = "SELECT * FROM 3a_usuarios \ INNER JOIN 3a_nivel_acesso ON 3a_nivel_acesso.id_nivel_acesso = 3a_usuarios.fk_id_nivel_acesso \ where 3a_nivel_acesso.id_nivel_acesso <= 3;"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/getTicketParking', function(req, res) { getTicketParking(req, res) }); app.post('/getTicketOperator', function(req, res) { getTicketOperator(req, res) }); app.post('/getTicketOperatorStr', function(req, res) { getTicketOperatorStr(req, res) }); app.post('/getTicketsCashier', function(req, res) { getTicketsCashier(req, res) }); app.post('/confirmCashDrain', function(req, res) { confirmCashDrain(req, res) }); app.post('/confirmCashChange', function(req, res) { confirmCashChange(req, res) }); app.post('/getCashDrain', function(req, res) { getCashDrain(req, res) }) app.post('/getCashChange', function(req, res) { let idUser = req.body.idUser let start = req.body.start let end = req.body.end let sql = "SELECT SUM(valor_inclusao) AS TOTAL \ FROM 3a_troco where fk_id_usuario = " + idUser + " \ AND data_inclusao BETWEEN '" + start + "' AND '" + end + "';"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }) app.post('/getTotalTickets', function(req, res) { let idUser = req.body.idUser let start = req.body.start let end = req.body.end let sql = "SELECT SUM(valor_log_venda) AS TOTAL \ FROM 3a_log_vendas where fk_id_usuarios = " + idUser + " \ AND data_log_venda BETWEEN '" + start + "' AND '" + end + "';"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }) app.post('/getLastCashier', function(req, res) { getLastCashierId(req, res) }) app.post('/getUsers', function(req, res) { getUsers(req, res) }) app.post('/getUserByName', function(req, res) { getUsersByName(req, res) }) app.post('/changePasswordUser', function(req, res) { let user = req.body.user let password = <PASSWORD> let sql = "UPDATE 3a_usuarios SET senha_usuarios = '" + password + "', \ senha_usuarios_pdvi ='" + password + "' WHERE id_usuarios = " + user.id_usuarios + ";"; //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }) app.post('/getErrors', function(req, res) { getErros(req, res) }) app.post('/recoverPaymentErros', function(req, res) { recoverPaymentErros(req, res) }) /** * COMANDOS RECEPTOR */ app.post('/getAllReceptors', function(req, res) { getAllReceptors(req, res) }) app.post('/systemCommand', function(req, res) { systemCommand(req, res) }) /** * COMANDOS TOTEM ACESSO */ app.post('/goAccessTotem', function(req, res) { console.log("Comando recebido!!!!") systemCommandLocal(req, res) }); app.post('/systemCommandLocal', function(req, res) { systemCommandLocal(req, res) }) /********************** * MULTIPLO - PRE VENDA ***************************/ app.post('/checkTicket', function(req, res) { let idTotem = req.body.id let ticket = req.body.ticket log_('Totem: '+ idTotem + ' - Verificando ticket:', ticket) let sql = "SELECT * \ FROM 3a_estoque_utilizavel \ LEFT JOIN 3a_log_vendas ON 3a_log_vendas.fk_id_estoque_utilizavel = 3a_estoque_utilizavel.id_estoque_utilizavel \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_estoque_utilizavel.fk_id_produto \ INNER join 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_produto.fk_id_subtipo_produto \ WHERE 3a_estoque_utilizavel.id_estoque_utilizavel = " + ticket + ";" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/checkMultipleTickets', function(req, res) { let idTotem = req.body.id let ticketStart = req.body.ticketStart let ticketEnd = req.body.ticketEnd log_('Totem: '+ idTotem + ' - Verificando vários ticket:' + ticketStart + ' até ' + ticketEnd) let sql = "SELECT *, 0 AS quantity \ FROM 3a_estoque_utilizavel \ LEFT JOIN 3a_log_vendas ON 3a_log_vendas.fk_id_estoque_utilizavel = 3a_estoque_utilizavel.id_estoque_utilizavel \ INNER join 3a_produto ON 3a_produto.id_produto = 3a_estoque_utilizavel.fk_id_produto \ INNER join 3a_subtipo_produto ON 3a_subtipo_produto.id_subtipo_produto = 3a_produto.fk_id_subtipo_produto \ WHERE 3a_estoque_utilizavel.id_estoque_utilizavel BETWEEN " + ticketStart + " AND "+ ticketEnd + ";" //log_(sql) conLocal.query(sql, function (err1, result) { if (err1) throw err1; res.json({"success": result}); }); }); app.post('/useTicketMultiple', function(req, res) { useTicketMultiple(req, res) }); app.post('/getSessions', function(req, res) { getSessions(req, res) }); app.post('/getSessionsName', function(req, res) { getSessionsName(req, res) }); app.post('/getSessionsProducts', function(req, res) { getSessionsProducts(req, res) }); app.post('/getProductsTypes', function(req, res) { getProductsTypes(req, res) }); app.post('/getProducts', function(req, res) { getProducts(req, res) }); app.post('/addSession', function(req, res) { addSession(req, res) }); app.post('/addUsers', function(req, res) { addUsers(req, res) }); app.post('/addUsers', function(req, res) { addUsers(req, res) }); app.post('/saveUsers', function(req, res) { updateUsers(req, res) }); app.post('/removeSession', function(req, res) { removeSession(req, res) }); app.post('/getSessionsTicket', function(req, res) { getSessionsTicket(req, res) }); app.post('/getSessionsTicketTotal', function(req, res) { getSessionsTicketTotal(req, res) }); http.listen(8086);<file_sep>#!/bin/bash cd scripts cp reimpressao.zpl tmp.zpl SUBJECT=3a TICKET_TYPE_FILENAME=tmp$(date "+%Y%m%d%H%M%S%N") SEARCH_FOR_TICKET_TYPE=%1 REPLACE_WITH_TICKET_TYPE=$1 VALUE_FILENAME=tmp$(date "+%Y%m%d%H%M%S%N").zpl SEARCH_FOR_VALUE=%2 REPLACE_WITH_VALUE=$2 OP_FILENAME=tmp$(date "+%Y%m%d%H%M%S%N").zpl SEARCH_FOR_OP=%3 REPLACE_WITH_OP=$3 DATE_FILENAME=tmp$(date "+%Y%m%d%H%M%S%N").zpl SEARCH_FOR_DATE=%4 REPLACE_WITH_DATE=$4 TICKET_FILENAME=tmp$(date "+%Y%m%d%H%M%S%N").zpl SEARCH_FOR_TICKET=%5 REPLACE_WITH_TICKET=$5 TOTAL_FILENAME=tmp$(date "+%Y%m%d%H%M%S%N").zpl SEARCH_FOR_TOTAL=%6 REPLACE_WITH_TOTAL=$6 touch $TICKET_TYPE_FILENAME touch $VALUE_FILENAME touch $OP_FILENAME touch $DATE_FILENAME touch $TICKET_FILENAME touch $TOTAL_FILENAME echo "$SUBJECT" | sed -e "s/$SEARCH_FOR_TICKET_TYPE/$REPLACE_WITH_TICKET_TYPE/g" tmp.zpl > $TICKET_TYPE_FILENAME && echo "$SUBJECT" | sed -e "s/$SEARCH_FOR_VALUE/$REPLACE_WITH_VALUE/g" $TICKET_TYPE_FILENAME > $VALUE_FILENAME && echo "$SUBJECT" | sed -e "s/$SEARCH_FOR_OP/$REPLACE_WITH_OP/g" $VALUE_FILENAME > $OP_FILENAME && echo "$SUBJECT" | sed -e "s/$SEARCH_FOR_DATE/$REPLACE_WITH_DATE/g" $OP_FILENAME > $DATE_FILENAME && echo "$SUBJECT" | sed -e "s/$SEARCH_FOR_TICKET/$REPLACE_WITH_TICKET/g" $DATE_FILENAME > $TICKET_FILENAME && echo "$SUBJECT" | sed -e "s/$SEARCH_FOR_TOTAL/$REPLACE_WITH_TOTAL/g" $TICKET_FILENAME > $TOTAL_FILENAME && lpr -P Zebra_Technologies_ZTC_GC420t_ -o raw $TOTAL_FILENAME rm $TICKET_TYPE_FILENAME rm $VALUE_FILENAME rm $OP_FILENAME rm $DATE_FILENAME rm $TICKET_FILENAME rm $TOTAL_FILENAME
0b6c2148f9eefe4342b6b005db9a46ec11a8374f
[ "Markdown", "JavaScript", "Shell" ]
3
Markdown
DBLTecnologia/PDVi_Server
c416452ffbbfa788e48f29382752e049fcca086e
36c2e53353366b3576f61765c03cb19925cf0864
refs/heads/master
<repo_name>Andre113/testeCidades<file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Lista/ListaTableViewDelegate.swift // // ListaTableViewDelegate.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit extension ListaTableViewController{ // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return self.sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sections[section].itemsInSection.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sections[section].sectionTitle } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cidadeCell", for: indexPath) as! CidadeTableViewCell let cidade = self.sections[indexPath.section].itemsInSection[indexPath.row] cell.setCidade(cidade: cidade) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.performSegue(withIdentifier: "goToResultado", sender: indexPath) } func updateTableView(){ self.tableView.reloadData() self.tableView.layoutIfNeeded() } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Home/HomeViewController.swift // // HomeViewController.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class HomeViewController: UIViewController { @IBOutlet weak var cidadeTextField: UITextField! @IBOutlet weak var estadoTextField: UITextField! @IBOutlet weak var buscarButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.setLayout() self.setConfiguration() } // MARK: - Layout func setLayout(){ self.setBuscarButtonLayout() } func setBuscarButtonLayout(){ self.buscarButton.layer.cornerRadius = 5.0 } // MARK: - Config func setConfiguration(){ self.configCidadeTextField() self.configEstadoTextField() } func configCidadeTextField(){ self.cidadeTextField.delegate = self self.cidadeTextField.tag = 10 } func configEstadoTextField(){ self.estadoTextField.delegate = self self.estadoTextField.tag = 11 } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else{ return } switch identifier{ case "goToResultados": self.doGoToResultadosSetup(segue: segue) break default: break } } func doGoToResultadosSetup(segue: UIStoryboardSegue){ let listaView = segue.destination as! ListaTableViewController listaView.cidadeParam = self.cidadeTextField.text ?? "" listaView.estadoParam = self.estadoTextField.text ?? "" } // MARK: - Other override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) self.view.endEditing(true) } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Lista/CidadeCell/CidadeTableViewCell.swift // // CidadeTableViewCell.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class CidadeTableViewCell: UITableViewCell { @IBOutlet weak var cidadeLabel: UILabel! @IBOutlet weak var estadoLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } // MARK: - Set func setCidade(cidade: CidadeModel){ self.cidadeLabel.text = cidade.nome self.estadoLabel.text = cidade.estado } } <file_sep>/TesteCidades/TesteCidades/Util/Constants/REST.swift // // REST.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import Foundation struct REST { static let base_url = "http://wsteste.devedp.com.br/Master/CidadeServico.svc/rest/" static let lista_url = base_url + "BuscaTodasCidades" static let busca_pontos_url = base_url + "BuscaPontos" } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Cidade/CidadeViewController.swift // // CidadeViewController.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class CidadeViewController: UIViewController { @IBOutlet weak var cidadeLabel: UILabel! let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) var cidade: CidadeModel! var presenter: CidadePresenter! override func viewDidLoad() { super.viewDidLoad() self.setLayout() self.setConfiguration() self.setupPresenter() } // MARK: - Layout func setLayout(){ self.setActivityViewLayout() } func setActivityViewLayout(){ self.activityView.frame = CGRect(x: 0, y: 0, width: 50, height: 50) self.activityView.color = UIColor.defaultBlue self.view.addSubview(self.activityView) } // MARK: - Config func setConfiguration(){ self.setActivityViewConfiguration() } func setActivityViewConfiguration(){ self.activityView.isHidden = true self.activityView.hidesWhenStopped = true self.view.addSubview(self.activityView) } // MARK: Presenter func setupPresenter(){ self.presenter = CidadePresenter() self.presenter.attachView(cidadeView: self) self.presenter.loadPontos(cidade: self.cidade) } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Lista/ListaTableViewController.swift // // ListaTableViewController.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class ListaTableViewController: UITableViewController { let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) var cidadeParam: String = "" var estadoParam: String = "" var presenter: ListaPresenter! var sections: [SectionInfo] = [] override func viewDidLoad() { super.viewDidLoad() self.setLayout() self.setConfiguration() self.setupPresenter() } //MARK: - Layout func setLayout(){ self.setTableViewLayout() self.setActivityViewLayout() } func setTableViewLayout(){ self.tableView.tableFooterView = UIView() } func setActivityViewLayout(){ self.activityView.frame = CGRect(x: 0, y: 0, width: 50, height: 50) self.activityView.color = UIColor.defaultBlue self.view.addSubview(self.activityView) } // MARK: - Config func setConfiguration(){ self.setTableViewConfiguration() self.setActivityViewConfiguration() } func setTableViewConfiguration(){ self.tableView.register(UINib(nibName: "CidadeTableViewCell", bundle: nil), forCellReuseIdentifier: "cidadeCell") } func setActivityViewConfiguration(){ self.activityView.isHidden = true self.activityView.hidesWhenStopped = true self.view.addSubview(self.activityView) } // MARK: Presenter func setupPresenter(){ self.presenter = ListaPresenter() self.presenter.attachView(listaView: self) self.presenter.loadCidadesWithFilter(cidade: self.cidadeParam, estado: self.estadoParam) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else{ return } switch identifier{ case "goToResultado": self.doGoToResultadoSetup(segue: segue, sender: sender) break default: break } } func doGoToResultadoSetup(segue: UIStoryboardSegue, sender: Any?){ let indexPath = sender as! IndexPath let resultadoView = segue.destination as! CidadeViewController resultadoView.cidade = self.sections[indexPath.section].itemsInSection[indexPath.row] } } <file_sep>/TesteCidades/TesteCidades/Util/Extension/UINavigationControllerExtension.swift // // UINavigationControllerExtension.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit extension UINavigationController { //Mostrar alertas na view func showAlert(mensagem: String){ let alertController = UIAlertController(title: "Cidades", message: mensagem, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Fechar", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Lista/SectionInfo/SectionInfo.swift // // SectionInfo.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class SectionInfo: NSObject { var itemsInSection: [CidadeModel] var sectionTitle: String? init(itemsInSection: [CidadeModel], sectionTitle: String) { self.itemsInSection = itemsInSection self.sectionTitle = sectionTitle } } <file_sep>/TesteCidades/TesteCidades/Util/Default/DefaultNavigatoinViewController.swift // // DefaultNavigatoinViewController.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class DefaultNavigatoinViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() self.setLayout() } // MARK: - Layout func setLayout(){ self.setNavbarLayout() } func setNavbarLayout(){ self.navigationBar.isTranslucent = false self.navigationBar.barTintColor = UIColor.defaultBlue self.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white] self.navigationBar.tintColor = UIColor.white } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Cidade/CidadePresenter.swift // // CidadePresenter.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class CidadePresenter: NSObject { private var cidadeView: CidadeView! func attachView(cidadeView: CidadeView){ self.cidadeView = cidadeView } // MARK: - Request func loadPontos(cidade: CidadeModel){ self.cidadeView.startLoading() PontosNetwork.pontosRoutine(cidade: cidade.nome, estado: cidade.estado) { (pontos) in if pontos == nil{ self.cidadeView.finishLoading() self.cidadeView.showAlert(msg: "Ocorreu um erro. Tente novamente mais tarde.") return } self.cidadeView.setPontos(pontos: self.formatPontos(pontos: pontos!)) self.cidadeView.finishLoading() } } // MARK: Process func formatPontos(pontos: Int) -> String{ let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter.string(from: NSNumber(integerLiteral: pontos)) ?? "0" } } <file_sep>/TesteCidades/TesteCidades/Network/NetworkManager.swift // // NetworkManager.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import Foundation import Alamofire protocol NetworkManager: class { //Vazio :) } extension NetworkManager { typealias Parameters = [String: Any] typealias Headers = [String: String] typealias Method = Alamofire.HTTPMethod /** Cria conexão padrão do Alamofire, seu retorno é um JSON. */ static func requestJson(method: Method, url: String, parameters: Parameters? = nil, headers: Headers? = nil, completion: @escaping (DataResponse<Any>) -> Void) { Alamofire.request(url , method: method , parameters: parameters , encoding: JSONEncoding.default , headers: headers) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .responseJSON(completionHandler: completion) } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Lista/ListaPresenter.swift // // ListaPresenter.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class ListaPresenter: NSObject { private var listaView: ListaView! func attachView(listaView: ListaView){ self.listaView = listaView } // MARK: - Request func loadCidadesWithFilter(cidade: String, estado: String){ self.listaView.startLoading() CidadesNetwork.cidadesRoutine { (cidades) in if cidades == nil{ self.listaView.finishLoading() self.listaView.showAlert(msg: "Ocorreu um erro. Tente novamente mais tarde.") return } self.filterCidades(cidades: cidades!, cidadeParam: cidade, estadoParam: estado) } } // MARK: - Process func filterCidades(cidades: [CidadeModel], cidadeParam: String, estadoParam: String){ /** Filtra as cidades de acordo com a cidade e estado passados Caso não haja parâmetros, exibe todos os resultados */ let filteredCidades: [CidadeModel] = cidades.filter({ (($0.nome.lowercased().contains(cidadeParam.lowercased())) || (cidadeParam == "") && ($0.estado.lowercased().contains(estadoParam.lowercased()) || (estadoParam == ""))) } ) self.listaView.setCidades(sections: self.aggregateCidades(cidades: filteredCidades)) self.listaView.finishLoading() } func aggregateCidades(cidades: [CidadeModel]) -> [SectionInfo]{ var sectionInfoArray: [SectionInfo] = [] /** Agrupa as cidades em sections de acordo com seu Estado */ for cidade in cidades{ let estado = cidade.estado if let section = sectionInfoArray.filter({ //Verifica se há alguma section com o estado atual $0.sectionTitle == estado }).first{ section.itemsInSection.append(cidade) } else{ //Caso não haja uma section com o nome do estado, cria uma nova let section = SectionInfo(itemsInSection: [cidade], sectionTitle: estado) sectionInfoArray.append(section) } } return sectionInfoArray } } <file_sep>/TesteCidades/TesteCidades/Network/PontosNetwork.swift // // PontosNetwork.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit class PontosNetwork: NetworkManager { class func pontosRoutine(cidade: String, estado: String, callback: @escaping(Int?) -> Void){ let body = ["Nome": cidade, "Estado": estado] print(REST.busca_pontos_url) requestJson(method: Method.post, url: REST.busca_pontos_url, parameters: body, headers: nil) { (response) in if (response.response?.statusCode ?? 0) != 200{ callback(nil) return } guard let pontos = response.result.value as? Int else{ callback(nil) return } callback(pontos) return } } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Lista/ListaViewProtocol.swift // // ListaViewProtocol.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit protocol ListaView: NSObjectProtocol{ func startLoading() func finishLoading() func setCidades(sections: [SectionInfo]) func showAlert(msg: String) } extension ListaTableViewController: ListaView{ func startLoading() { self.view.isUserInteractionEnabled = false self.view.bringSubview(toFront: self.activityView) self.activityView.center = self.tableView.center self.activityView.startAnimating() } func finishLoading() { self.view.isUserInteractionEnabled = true self.activityView.stopAnimating() } func setCidades(sections: [SectionInfo]) { self.sections = sections self.updateTableView() } func showAlert(msg: String) { self.navigationController?.showAlert(mensagem: msg) } } <file_sep>/TesteCidades/TesteCidades/Util/Constants/UIColorExtension.swift // // UIColorExtension.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit extension UIColor{ static var defaultBlue: UIColor{ get{ return UIColor(red: 0.196, green: 0.333, blue: 0.62, alpha: 1) } } } <file_sep>/TesteCidades/TesteCidades/Network/CidadesNetwork.swift // // CidadesNetwork.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit import Foundation import SwiftyJSON class CidadesNetwork : NetworkManager { class func cidadesRoutine(callback: @escaping([CidadeModel]?) -> Void){ print(REST.lista_url) requestJson(method: Method.get, url: REST.lista_url) { (response) in if (response.response?.statusCode ?? 0) != 200{ callback(nil) return } guard let cidadesJson = response.result.value as? [[String: Any]] else{ callback(nil) return } var listaCidades: [CidadeModel] = [] for cidadeJson in cidadesJson{ listaCidades.append(CidadeModelLoader.loadCidadeModel(json: cidadeJson)) } callback(listaCidades) return } } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Cidade/CidadeViewProtocol.swift // // CidadeViewProtocol.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit protocol CidadeView: NSObjectProtocol { func startLoading() func finishLoading() func setPontos(pontos: String) func showAlert(msg: String) } extension CidadeViewController: CidadeView { func startLoading() { self.view.isUserInteractionEnabled = false self.view.bringSubview(toFront: self.activityView) self.activityView.center = self.view.center self.activityView.startAnimating() } func finishLoading() { self.view.isUserInteractionEnabled = true self.activityView.stopAnimating() } func setPontos(pontos: String) { self.cidadeLabel.text = "A pontuação da Cidade \(self.cidade.nome) é \(pontos)" } func showAlert(msg: String) { self.navigationController?.showAlert(mensagem: msg) } } <file_sep>/TesteCidades/TesteCidades/Model/CidadeModel.swift // // CidadeModel.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import Foundation struct CidadeModel { var nome: String = "" var estado: String = "" } class CidadeModelLoader: NSObject { static func loadCidadeModel(json: [String: Any]) -> CidadeModel { var cidade = CidadeModel() cidade.nome = json["Nome"] as? String ?? "" cidade.estado = json["Estado"] as? String ?? "" return cidade } } <file_sep>/TesteCidades/TesteCidades/View Controller & Presenters/Home/HomeTextFieldDelegate.swift // // HomeTextFieldDelegate.swift // TesteCidades // // Created by <NAME> on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import UIKit extension HomeViewController: UITextFieldDelegate{ func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let nsText = textField.text! as NSString let newText = nsText.replacingCharacters(in: range, with: string) return newText.rangeOfCharacter(from: CharacterSet.letters.union(.whitespaces).inverted) == nil } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() let tag = textField.tag if tag != 11{ self.view.viewWithTag(tag + 1)?.becomeFirstResponder() } else{ self.performSegue(withIdentifier: "goToResultados", sender: self) } return true } }
3520500db62d08eb248f6649d2c6ca2106e0467e
[ "Swift" ]
19
Swift
Andre113/testeCidades
1caeca66c0c22f017a417b3a6dfd5ba42b8a1e02
479465adc02db4dc64d0810e89a5829df97a175c
refs/heads/master
<file_sep>// This script will compile the smart contracts, compile the ABI deploy them to the target web server, and write to company.JSON file for the // ABI and contract address var solc = require("solc"); // import the solidity compiler var Web3 = require("web3"); // import web3 var fs = require("fs"); //import the file system module var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); //******* COMPILE the contract var code = fs.readFileSync("../contracts/Company.sol").toString(); var compiledCode = solc.compile(code); //grab the bytecode from compiled contract - This is the code which will be deployed to the blockchain. var byteCode = compiledCode.contracts[":Company"].bytecode; //grab the contract interface, called the Application Binary Interface (ABI), which tells the user what methods are available in the contract. var abi = compiledCode.contracts[":Company"].interface; //parse the abi string into a JS object var abiDefinition = JSON.parse(abi); //******* DEPLOY the contract: //Create a contract object which is used to deploy and initiate contracts in the blockchain. var CompanyContract = web3.eth.contract(abiDefinition); var contractInstance; //Deploy the contract to the blockchain. The parameter is the info needed to actually deploy the contract: //data: This is the compiled bytecode that we deploy to the blockchain //from: The blockchain has to keep track of who deployed the contract. In this case, we are just picking the first account. //In the live blockchain, you can not just use any account. You have to own that account and unlock it before transacting. //You are asked for a passphrase while creating an account and that is what you use to prove your ownership of that account. Testrpc by default unlocks all the 10 accounts for convenience. //gas: It costs money to interact with the blockchain. This money goes to miners who do all the work to include your code in the blockchain. //You have to specify how much money you are willing to pay to get your code included in the blockchain and you do that by setting the value of ‘gas’. //The ether balance in your ‘from’ account will be used to buy gas. The price of gas is set by the network. //The amount of gas it takes to execute a transaction or deployment is calculated by the operations in the contract / function being executed. //function(e, contract): After the contract is deployed, this callback function will be called with either an error or our contract instance var deployedContract = CompanyContract.new( { data: byteCode, from: web3.eth.accounts[0], gas: 4700000 }, function(e, contract) { if (!e) { if (!contract.address) { console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...\n"); } else { console.log("Contract Address: " + contract.address); //get the instance of the contract at this address contractInstance = CompanyContract.at(contract.address); //write the contract address and abi to file for client side JS to use to interact with contract fs.writeFile("./company.json", JSON.stringify( { address: contract.address, abi: JSON.stringify(abiDefinition, null, 2) }, null, 2), "utf-8", function(err) { if (err) { console.log("ERROR: "); console.log(err); } else { console.log(`The file ./company.json was saved.`); } } ); } } else { console.log(e); } } ); <file_sep>//submitSurvey() - called when user selects to submit their survey on the web form window.submitSurvey = function() { var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); var surveyInstance; var companyInstance; //get the instances of our contract from their JSON files $.getJSON("./survey.json", function(contract) { surveyInstance = web3.eth.contract(JSON.parse(contract.abi)).at(contract.address); alert(surveyInstance.address); }) $.getJSON("./company.json", function(contract) { companyInstance = web3.eth.contract(JSON.parse(contract.abi)).at(contract.address); alert(companyInstance.address); }) //retrieve the header information for the MTC survey and write to Company contract companyName = $('input[name=companyName]').val(); mtcDate = $('input[name=mtcDate]').val(); alert(companyName); companyInstance.setCompanyData(companyName, mtcDate, companyInstance.address); name = companyInstance.getCompanyName(); alert(name); }; // submitSurvey() <file_sep>//after the script tags are loaded (web3 & jquery) run this function window.onload = function() { //initilize here }; //window.onload
9c8de6b8fe3ff1c14db9b6414946a0fc3734682f
[ "JavaScript" ]
3
JavaScript
pjjohnson/surveys
d9db76b7ad6ece8755ebe0197c4fb123d2e994ea
5e441c38056a49f4a87f000d61647350e49d86fb
refs/heads/master
<file_sep>import java.awt.*; import javax.swing.*; import javax.swing.event.*; import java.util.*; class ControlPanel extends JPanel{ private JButton areaButton; private JSlider slider; private JTextArea text; private AreaButtonHandler handler; public ControlPanel(){ // set layout setLayout(new GridLayout(3,1)); //place a button areaButton = new JButton("Calculate Area"); add(areaButton); //add button to handler handler= new AreaButtonHandler(); areaButton.addActionListener(handler); //add slider slider = new JSlider(JSlider.HORIZONTAL,-200,-20,-200); slider.addChangeListener(new TimerSlideHandler()); add(slider); //place a textfield text = new JTextArea(); add(text); } } <file_sep>class ExpressionToken{ public String s; public int precedence; public boolean isDigit; public ExpressionToken(String t,int p){ s = t; precedence = p; } } <file_sep>import java.util.*; import java.awt.*; class SweepLine{ // x and y bst's private BinarySearchTree xTree; private BinarySearchTree yTree; private ArrayList<Rectangle>inputRectangles; private ArrayList<Rectangle> animRectangles; private ArrayList<Double> animAreas; public SweepLine(){ xTree = new BinarySearchTree(); yTree = new BinarySearchTree(); inputRectangles = new ArrayList<Rectangle>(); animRectangles = new ArrayList<Rectangle>(); animAreas = new ArrayList<Double>(); } public SweepLine(ArrayList<Rectangle> r){ this(); inputRectangles = r; } public ArrayList<Rectangle>rectangles(){ return inputRectangles; } public ArrayList<Rectangle>animRectangles(){ return animRectangles; } public ArrayList<Double>animAreas(){ return animAreas; } public void fillYTree(){ for(int i =0;i <inputRectangles.size();i++){ // false = low // true = high Rectangle r = inputRectangles.get(i); TreeNode low = new TreeNode(r.y,i,false,r.x,r.x + r.width); TreeNode high = new TreeNode(r.y + r.height,i,true,r.x,r.x + r.width); yTree.insert(low); yTree.insert(high); } ////System.out.println("YTREE"); //yTree.print(yTree.root); } // performs iterative in order traversal to check nodes public double sweepXTree(int preY,int curY){ //System.out.println("ENTER sweepXTree"); int counter=1;int L=0; TreeNode prevX = null; TreeNode nextX = null; prevX = xTree.findMin(); while(prevX !=null){ //System.out.println("prevX : " + prevX.getPrimary() + " LOWHIGH: " + prevX.getLH()); nextX = successor(xTree,prevX); if(nextX !=null){ //System.out.println("nextX : " + nextX.getPrimary() + " LOWHIGH: " + nextX.getLH()); if(counter!=0){ L = L + (nextX.getPrimary() - prevX.getPrimary()); Rectangle r = new Rectangle(prevX.getPrimary(),preY,nextX.getPrimary()-prevX.getPrimary(),curY-preY); // System.out.println("CREATED RECTANGLE: " +r.x+" "+r.y+" "+r.width+" "+r.height); animRectangles.add(r); //System.out.println("L = " + L); } prevX = nextX; /* if(prevX.getLH() == false) counter++; else counter--; */ counter = (prevX.getLH() == false) ? counter+1:counter-1; //System.out.println("counter: " + counter); } else{ prevX = nextX; } } //System.out.println("EXIT sweepXTree"); //System.out.println("L = " + L); return L; } // given bst r and a node n, find next smalelst highest node to n private TreeNode successor(BinarySearchTree r, TreeNode n){ if(n.right() !=null) return r.findMin(n.right()); TreeNode succ = null; TreeNode root = r.root; while(root!=null){ if(n.getPrimary() < root.getPrimary()){ succ = root; root = root.left(); } else if(n.getPrimary() > root.getPrimary()){ root = root.right(); } else break; } return succ; } // returns the covered by the inputRectangles public double computeArea(){ //fill y tree fillYTree(); double area = 0; int curY=0;int preY=0; while(!yTree.empty(yTree.root)){ double L = 0; TreeNode n = new TreeNode(); n = yTree.findMin(); yTree.deleteMin(); curY = n.getPrimary(); //System.out.println("YMIN: " + n.getPrimary() + " LOWHIGH: " + n.getLH()); //System.out.println("PREY: " + preY + " CURY: " + curY); L = sweepXTree(preY,curY); if(curY-preY ==0) area = area + L; else area = area + L*(curY-preY); animAreas.add(area); //System.out.println("AREA: " + area); preY= curY; // create and insert two xTreeNodes if low value if(n.getLH() == false){ TreeNode xLow = new TreeNode(n.getLow(),n.getID(),false,n.getPrimary(),n.getPrimary() + inputRectangles.get(n.getID()).height); TreeNode xHigh = new TreeNode(n.getHigh(),n.getID(),true,n.getPrimary(),n.getPrimary() + inputRectangles.get(n.getID()).height); xTree.insert(xLow); xTree.insert(xHigh); //System.out.println("added two xnodes"); //System.out.println("lowx : " + xLow.getPrimary()); //System.out.println("highx : " + xHigh.getPrimary()); } // else remove two xTreeNodes else{ //System.out.println("removing " + n.getLow() + " " + n.getHigh()); xTree.remove(n.getLow()); xTree.remove(n.getHigh()); } } return area; } public static void main(String[] args){ SweepLine sl = new SweepLine(); // test rectangles from the doc Rectangle r0 = new Rectangle(120,100,58,58); Rectangle r1 = new Rectangle(160,140,30,32); Rectangle r2 = new Rectangle(180,164,55,24); /* * simple test caste Rectangle r0 = new Rectangle(0,0,4,4); Rectangle r1 = new Rectangle(2,2,1,1); Rectangle r2 = new Rectangle(1,1,5,5); */ // add rectangles to input array sl.inputRectangles.add(r0); sl.inputRectangles.add(r1); sl.inputRectangles.add(r2); // fill ytree sl.fillYTree(); sl.yTree.print(sl.yTree.root); //get area System.out.println(sl.computeArea()); } } <file_sep>class BinarySearchTree{ // root of tree node public TreeNode root; // creates a null BST public BinarySearchTree(){ root = null; } // create a BST with root n public BinarySearchTree(TreeNode n){ root = n; } // add n into root public void insert(TreeNode n){ if(!find(n.getPrimary())) root = insert(root,n); else System.out.println("DUPLICATE: " + n.getPrimary()); } // private method used to recursively add a node // returns new root with n inserted into it private TreeNode insert(TreeNode r,TreeNode n){ if(r ==null) return n; // go to the left if(r.getPrimary() < n.getPrimary()) r.setRight(insert(r.right(),n)); // go to the right else r.setLeft(insert(r.left(),n)); return r; } // in order print public void print(TreeNode r){ if(r == null){ return; } print(r.left()); System.out.println(r.getPrimary() + " "); print(r.right()); } // public method for finding a key in the tree. returns the node with key if it exists, // else returns a null node. public boolean find(int key){ return find(root,key); } private boolean find(TreeNode r,int key){ if(r == null) return false; else if(r.getPrimary() > key) return find(r.left(),key); else if(r.getPrimary() < key) return find(r.right(),key); else return true; } /* private TreeNode find(TreeNode r,int key){ while(r!=null){ // search right subtree if(r.getPrimary() < key) r = r.right(); // search left subtree else if (r.getPrimary() > key) r = r.left(); // else we found it else return r; } // didnt find it return r; } */ // finds min value key, delete it and return it for root r void deleteMin(){ root = deleteMin(root); } TreeNode findMin(){ return findMin(root); } TreeNode findMin(TreeNode r){ if(r == null) return r; while(r.left()!=null) r = r.left(); return r; } // recursive function that sets root with min node removed TreeNode deleteMin(TreeNode r){ if(r.left()!=null){ r.setLeft(deleteMin(r.left())); return r; } // if we are at the Min node, link to its right subtree, this sets // root as (root - minNode) else return r.right(); } // return true if r is null boolean empty(TreeNode r){ if(r == null) return true; return false; } // attemps to remove key from root public void remove(int key){ // only call remove if key is in root if(find(key)) root = remove(root,key); else System.out.println("ERROR, key must be in root"); } private TreeNode remove(TreeNode r,int key){ //search right if(r.getPrimary() < key) r.setRight(remove(r.right(),key)); //search left else if(r.getPrimary() > key) r.setLeft(remove(r.left(),key)); // we are at key //check for double child else if(r.left()!=null && r.right()!=null){ // find min val in right subtree r.setPrimary(findMin(r.right()).getPrimary()); r.setRight(deleteMin(r.right())); } // else if only a right child else if(r.left() == null) r = r.right(); // else only a left child else r = r.left(); return r; } public static void main (String[] a){ /* * Rectangles: * R0 (120,100) , (178,158) * R1 (160,140) , (190,172) * R2 (225,164) , (280,188) */ // YTREE with test Rectangles BinarySearchTree ytree = new BinarySearchTree(); // create ytree nodes TreeNode r0_low_y = new TreeNode(100,0,false,120,178); TreeNode r0_high_y = new TreeNode (158,0,true,120,178); TreeNode r1_low_y = new TreeNode(140,1,false,160,190); TreeNode r1_high_y = new TreeNode(172,1,true,160,190); TreeNode r2_low_y = new TreeNode(164,2,false,225,280); TreeNode r2_high_y = new TreeNode(280,2,true,225,280); //add the nodes ytree.insert(r0_low_y); ytree.insert(r0_high_y); ytree.insert(r1_low_y); ytree.insert(r1_high_y); ytree.insert(r2_low_y); ytree.insert(r2_high_y); //TreeNode t = new TreeNode(); //t = ytree.find(165); //if(t!=null) // System.out.println(t.getPrimary()); /* // test if min functions are working correctly //print in order ytree.print(ytree.root); System.out.print("MIN KEY: "+ ytree.findMin(ytree.root).getPrimary()); ytree.deleteMin(); System.out.println(); ytree.print(ytree.root); */ // test if delete is working ytree.print(ytree.root); System.out.println("DELETE 164, 100, 280"); ytree.remove(164); ytree.remove(100); ytree.remove(280); ytree.print(ytree.root); /* //initialize empty xtree BinarySearchTree xtree = new BinarySearchTree(); double area = 0; while(!ytree.isEmpty(ytree.root)){ double currentY=0;double prevY = 0; // find and delete minimum node TreeNode t = new TreeNode(); t = ytree.findMin(ytree.root); ytree.deleteMin(ytree.root); currentY = t.getPrimary(); */ } } <file_sep>import java.util.*; import java.io.*; import java.util.concurrent.*; class Board extends RecursiveAction implements Runnable{ //boolean array to represent game board private boolean[] brd; //the first move for the threaded solution public Move fm; //fork/join stuff public ArrayList<Board> tasks; private int magicNumber; //solution move set public ArrayList<Move> solution; private String filename; //constructor public Board(String f){ //init 2d array brd = new boolean[49]; solution= new ArrayList<Move>(); //set board brd = setBoard(); //init tasks tasks = new ArrayList<Board>(); filename =f; } //copy constructor public Board(Board b){ brd = new boolean[49]; solution= new ArrayList<Move>(); tasks = new ArrayList<Board>(); magicNumber = b.magicNumber; filename = b.filename; for(int i=0;i<49;i++) brd[i] = b.brd[i]; } boolean[] setBoard(){ boolean[] _brd = new boolean[49]; // read in from game.txt String line = new String(); try{ Scanner s = new Scanner(new File(filename)); line = s.nextLine(); }catch(FileNotFoundException e){ System.out.println("no game.txt"); return _brd; } String[] n = line.split(" "); magicNumber = n.length; for(String x:n) _brd[Integer.parseInt(x)] = true; return _brd; } void printBoard(){ for(int i =0;i <49;i++){ if(brd[i]) System.out.print("x "); else if (isPlayable(i)) System.out.print("_ "); else System.out.print(" "); if((i+1)%7==0) System.out.println(); } //System.out.println("\n"); } //returns true if not one of the 4 corner spots. boolean isPlayable(int i){ if(i==0 || i==1 || i==5 || i==6 || i==7 ||i==8 || i==12 || i==13 || i ==35 || i==36 || i==40 || i==41 || i ==42 || i==43 || i==47 || i==48) return false; return true; } Board move(Move m, Board b){ Board t = new Board(b); //flip the first and last t.brd[m.m[0]] = true; t.brd[m.m[1]] = false; t.brd[m.m[2]] = false; return t; } // returns a list of all possible moves on board x ArrayList<Move>nextMoves(Board x){ ArrayList<Move> moveList = new ArrayList<Move>(); for(int i =0;i<49;i++){ //if its a valid empty spot if(isPlayable(i) && x.brd[i] == false){ //check 2 left if( i%7 -2 >=0 && x.brd[i-1] &&x.brd[i-2]){ // System.out.println("(" + (i) + " " + (i-1) + " " +(i-2) +")"); Move m = new Move(i,i-1,i-2); moveList.add(m); } //check 2 right if( i%7+2<7 && x.brd[i+1] &&x.brd[i+2]){ // System.out.println("(" + i + " " + (i+1) + " " +( i+2) +")"); Move m = new Move(i,i+1,i+2); moveList.add(m); } //check 2 up if(i-14 >=0 && x.brd[i-7] && x.brd[i-14]){ // System.out.println("(" + i + " " + (i-7) + " " +( i-14) +")"); Move m = new Move(i,i-7,i-14); moveList.add(m); } //check 2 down if(i <35 && x.brd[i+7] && x.brd[i+14]){ // System.out.println("(" + i + " " + (i+7) + " " +( i+14) +")"); Move m = new Move(i,i+7,i+14); moveList.add(m); } } } return moveList; } ArrayList<Move>push(Move m, ArrayList<Move>mseq){ ArrayList<Move>temp =new ArrayList<Move>(mseq); temp.add(0,m); return temp; } boolean validMove(Move m,Board b){ if(b.brd[m.m[0]] == false && b.brd[m.m[1]] == true && b.brd[m.m[2]] == true) return true; return false; } boolean solve(Board x, ArrayList<Move> mseq){ if(solved(x)) return true; if(Thread.currentThread().isInterrupted()) return false; ArrayList<Move> next = nextMoves(x); for(Move m:next){ Board y = move(m,x); if(solve(y,mseq)){ //x.printBoard(); //m.printMove(); solution.add(m); mseq = push(m,mseq); return true; } } return false; } // returns true if x is solved boolean solved(Board x){ int n =0; for(int i =0;i<49;i++){ if(x.brd[i]) n++; if(n >1){ //System.out.println("not solved"); return false; } } return true; } //prints a list of moves void printMoves(ArrayList<Move> m){ for(Move x : m) x.printMove(); } void applySolution(Board b, ArrayList<Move> s){ System.out.println("START SOLUTION"); for(Move m :s ){ b = b.move(m,b); b.printBoard(); System.out.println("move finished"); } } int numPegs(){ int counter =0; for(int i=0;i<49;i++){ if(brd[i]) counter++; } return counter; } // overrided thread method public void run(){ try{ ArrayList<Move> moves = new ArrayList<Move>(); solve(this,moves); // if it finishes, interrupt all other threads Thread.sleep(1); // if this runnable found a solution if(this.solution.size() >1){ Thread.currentThread().getThreadGroup().interrupt(); Collections.reverse(this.solution); //applySolution(this,this.solution); solution.add(0,fm); printMoves(this.solution); } }catch(InterruptedException exception){ //System.out.println("got interrupted"); Thread.currentThread().interrupt(); } } // overrided recursiveAction method protected void compute(){ //get child tasks ArrayList<Move> childMoves = this.nextMoves(this); for(Move m: childMoves){ Board c = this.move(m,this); tasks.add(c); } // start subtasks invokeAll(tasks); solve(this,new ArrayList<Move>()); // print solution if found if(numPegs() ==magicNumber){ Collections.reverse(solution); printMoves(solution); // unsure if this does anything cancel(true); for(Board t : tasks) t.cancel(true); } } public static void main(String[] a){ /* Board b = new Board(); ArrayList<Move> moves = new ArrayList<Move>(); b.solve(b,moves); b.printMoves(b.solution); */ } } <file_sep>public class Move{ int[] m; Move(int i, int j, int k){ m = new int[3]; m[0]=i; m[1]=j; m[2]=k; } void printMove(){ System.out.println("(" + m[0] + " " + m[1] + " " +m[2] +")"); } }
da37dfeed051db9d381694ea851c858f5c4793cf
[ "Java" ]
6
Java
narmour/cs360
00dcbfa1f91f8f5071dbab337b9e8bad764560bb
41a49482f6e698c5f6bd607204cd80e7d3536dd9
refs/heads/master
<file_sep># Account-Manager-Discord-Bot This bot was made with intent to store some game accounts in a database and be able to retrieve it. Mostly it is used when playing with groups of people, as everyone creates different accounts - this bot allows to store this information into H2 database with JDBC and anyone with permissions can access all accounts list from discord client. With this bot, you won't need to constantly update your text files with new account information and then distribute that text file to all group members. Anyone with permissions can add/retrieve/remove accounts information. # References Bot is built with the help of [JDA](https://github.com/DV8FromTheWorld/JDA) [H2](http://www.h2database.com/html/cheatSheet.html) database with Server Mode and JDBC was used to store data in a local repository Additionally, [JDA Utilities](https://github.com/JDA-Applications/JDA-Utilities) were used # Commands - ```!add``` - adds account to database, example: ```!add mage1 login password``` If account already exists (checks profession, in this case mage1) -> the bot will ask if you want to update login/password. Can also be used to add permissions for users, example ```!add permissions discord_id``` - ```!acc``` - returns all accounts login/password information in DM, example ```!acc``` To retrieve a single account: ```!acc mage1``` - ```!remove``` - removes specific account (requires profession name), example: ```!remove mage1``` Can also remove permissions from a user, ```!remove permissions discord_id``` - ```!list``` - provides list of available accounts by profession name - ```!permissions``` - provides a list of users who can use bot functionality - ```!help``` - send DM with all commands available and their description (this command is made by default from JDA Utilities, Inherited Command class) # How to use In `Main.java` replace String `adminId` with your discord id. In file `TOKEN_HOLDER.txt`, insert your bot token. Also, H2 server should be set up according to your needs, in my case - the code uses H2 local test server, which can be left unmodified, but ideally, the bot could be hosted somewhere to have unlimited access to accounts information. In my case, of course, access to database is available as long as the project is running. <file_sep>package ddconvict.commands; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; import ddconvict.Account; import ddconvict.database.ReadFromDB; /** * Provides all accounts information or specific account information */ public class AccCommand extends Command { public AccCommand() { super.name = "acc"; super.aliases = new String[] {"accounts"}; super.help = "returns all accounts login/password information in PM -> !acc " + "\nCan also be used to retrieve single account -> !acc mage1"; } @Override protected void execute(CommandEvent event) { if (event.getAuthor().isBot()) { System.out.println("its bot!"); return; } String[] userTyped = event.getMessage().getContentRaw().split("\\s+"); if (new ReadFromDB().getPermissionList().contains(event.getAuthor().getId())) { if (!new ReadFromDB().getAccounts().isEmpty() && userTyped.length == 1 ) { event.replyInDm(new ReadFromDB().getAccounts().toString() .replace(",", "--------------" + "\n") .replace("[", "--------------" + "\n") .replace("]", "--------------" + "\n") .replace(" ", "") .trim()); } else if (!new ReadFromDB().getAccounts().isEmpty() && userTyped.length == 2 && new ReadFromDB().getAccounts().toString().contains(userTyped[1])) { for (Account acc : new ReadFromDB().getAccounts()) { if (acc.getProf().equalsIgnoreCase(userTyped[1])) { event.replyInDm(new ReadFromDB().getAccFromDB(userTyped[1]).toString()); } } } else if (userTyped.length > 1 && !new ReadFromDB().getAccounts().toString().contains(userTyped[1])) { event.reply("No account with profession: " + userTyped[1]); } else { event.reply("No accounts in database"); } } else { event.reply("You don't have permissions to use this bot"); } } } <file_sep>package ddconvict.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import ddconvict.Account; /** * Reads information about all tables */ public class ReadFromDB { private String prof, login, password, sql, command, permission; private ResultSet rs; private Statement stmt; public ReadFromDB() { Connection con; try { con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test","sa",""); this.stmt = con.createStatement(); } catch (SQLException e) { e.printStackTrace(); } } public ArrayList<Account> getAccounts() { ArrayList<Account> accounts = new ArrayList<>(); this.sql = "SELECT * FROM Registration"; try { this.rs = stmt.executeQuery(sql); while (this.rs.next()) { this.prof = rs.getNString("prof"); this.login = rs.getNString("login"); this.password = rs.getNString("<PASSWORD>"); accounts.add(new Account(this.prof, this.login, this.password)); } } catch (SQLException e) { e.printStackTrace(); } return accounts; } public Account getAccFromDB(String profke) { for (Account acc: this.getAccounts()) { if (acc.getProf().equals(profke)) { return acc; } } return null; } public ArrayList<String> getCommandList() { ArrayList<String> allCommands = new ArrayList<>(); this.sql = "SELECT * FROM Commands"; try { this.rs = stmt.executeQuery(sql); while (this.rs.next()) { this.command = rs.getNString("CommandList"); allCommands.add(this.command); } } catch (SQLException e) { e.printStackTrace(); } return allCommands; } public ArrayList<String> getPermissionList() { ArrayList<String> allPermissions = new ArrayList<>(); this.sql = "SELECT * FROM Permissions"; try { this.rs = stmt.executeQuery(sql); while (this.rs.next()) { this.permission = rs.getNString("PermissionList"); allPermissions.add(this.permission); } } catch (SQLException e) { e.printStackTrace(); } return allPermissions; } public ArrayList<String> getProfkes() { ArrayList<String> allProfkes = new ArrayList<>(); this.sql = "SELECT * FROM Commands"; try { this.rs = stmt.executeQuery(sql); while (this.rs.next()) { if (rs.getNString("CommandList").equals("add") || rs.getNString("CommandList").equals("acc") || rs.getNString("CommandList").equals("remove") || rs.getNString("CommandList").equals("list") || rs.getNString("CommandList").equals("permissions")) { continue; } else { this.command = rs.getNString("CommandList"); allProfkes.add(this.command); } } } catch (SQLException e) { e.printStackTrace(); } return allProfkes; } } <file_sep>package ddconvict; public class Account { private String prof, login, password; public Account(String prof, String login, String password) { this.prof = prof; this.login = login; this.password = password; } public String getProf() { return prof; } public void setProf(String prof) { this.prof = prof; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return this.prof + "\n" + this.login + "\n" + this.password + "\n"; } } <file_sep>package ddconvict.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; /** * Deletes specific table rows, or all rows depending on method */ public class DeleteFromDB { private Statement stmt; private String sql; public DeleteFromDB() { } public DeleteFromDB(String deleteUnit) { Connection con; try { con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test","sa",""); PreparedStatement prstmt = con.prepareStatement("DELETE FROM Registration " + "WHERE Prof = ?"); prstmt.setString(1, deleteUnit); prstmt.executeUpdate(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } public void DeleteAllAccounts() { Connection con; try { con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test","sa",""); this.stmt = con.createStatement(); this.sql = "DELETE FROM Registration"; this.stmt.executeUpdate(sql); con.close(); } catch (SQLException e) { e.printStackTrace(); } } public void DeleteCommandFromDB(String profke) { Connection con; try { con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test","sa",""); PreparedStatement prstmt = con.prepareStatement("DELETE FROM Commands " + "WHERE CommandList = ?"); prstmt.setString(1, profke); prstmt.executeUpdate(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } public void DeleteAllCommandsFromDB() { Connection con; try { con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test","sa",""); this.stmt = con.createStatement(); this.sql = "DELETE FROM Commands " + "WHERE CommandList NOT IN ('acc', 'add', 'remove', 'permissions', 'list')"; this.stmt.executeUpdate(sql); con.close(); } catch (SQLException e) { e.printStackTrace(); } } public void DeletePermission(String userId) { Connection con; try { con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test","sa",""); PreparedStatement prstmt = con.prepareStatement("DELETE FROM Permissions " + "WHERE PermissionList = ?"); prstmt.setString(1, userId); prstmt.executeUpdate(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } <file_sep>package ddconvict.commands; import java.util.ArrayList; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; import ddconvict.database.*; import net.dv8tion.jda.api.entities.Member; /** * Provides list of users who have permissions to use the bot */ public class PermissionsCommand extends Command{ public PermissionsCommand() { super.name = "permissions"; super.aliases = new String[] {"permission"}; super.help = "provides a list of users who can use bot functionality"; } @Override protected void execute(CommandEvent event) { if (event.getAuthor().isBot()) { System.out.println("its bot!"); return; } if (new ReadFromDB().getPermissionList().contains(event.getAuthor().getId())) { ArrayList<String> getNames = new ArrayList<>(); for (String id: new ReadFromDB().getPermissionList()) { getNames.add(convertToName(id, event)); } event.reply("People who can use bot: " + getNames.toString() .replace("[", "") .replace("]", "")); } else { event.reply("You don't have permissions to use this bot"); } } private String convertToName(String userIdString, CommandEvent event) { String name = ""; Guild guild = event.getGuild(); List<Member> users = guild.getMembers(); for (Member mem : users)) { if (mem.getId().equalsIgnoreCase(userIdString)) { name = mem.getEffectiveName(); } } return name; } } <file_sep>package ddconvict; import java.io.File; import java.io.IOException; import java.util.Scanner; import javax.security.auth.login.LoginException; import com.jagrosh.jdautilities.command.CommandClient; import com.jagrosh.jdautilities.command.CommandClientBuilder; import com.jagrosh.jdautilities.commons.waiter.EventWaiter; import ddconvict.commands.*; import ddconvict.database.CreateDBTable; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Activity; public class Boter { private String token; private EventWaiter waiter; public Boter() { /** * EventWaiter is needed only for 1 case(AddCommand class) * CreateDBTable makes 3 main database tables using H2 and JDBC * Tables are: Registration, Commands, Permissions * Commands table is created with default commands: add, remove, acc, list, permissions */ this.waiter = new EventWaiter(); new CreateDBTable(); /** * initialize JDA builder, you can use other methods to initialize it * but some methods I found were deprecated so I sticked with this one * create your own TOKEN_HOLDER.txt, place it in project directory and insert * your bot key into TOKEN_HOLDER.txt file */ JDA jda = null; try { Scanner scanner = new Scanner(new File("TOKEN_HOLDER.txt")); this.token = scanner.nextLine(); jda = JDABuilder.createDefault(this.token) .setActivity(Activity.playing("with Accounts")) .setChunkingFilter(ChunkingFilter.ALL) // enable member chunking for all guilds .setMemberCachePolicy(MemberCachePolicy.ALL) // ignored if chunking enabled .enableIntents(GatewayIntent.GUILD_MEMBERS) .build() .awaitReady(); } catch (InterruptedException | LoginException | IOException e) { e.printStackTrace(); } // just to check if builder returned null for some unexpected reason assert jda != null; /** * JDA provides utilities library for CommandClientBuilder * In this case it is used to merge separate commands into builder * as well as it provides helping methods for easier commands implementations */ CommandClientBuilder builder = new CommandClientBuilder(); builder.setPrefix("!"); // set up desired prefix for command builder.setOwnerId(Main.adminId); builder.addCommands(new AddCommand(waiter), new AccCommand(), new RemoveCommand(), new ListCommand(), new PermissionsCommand()); CommandClient client = builder.build(); jda.addEventListener(client); jda.addEventListener(waiter); } }
cb4e9bfe709234378a3a492f7d7575ddfbade749
[ "Markdown", "Java" ]
7
Markdown
Art0123/Account-Manager-Discord-Bot
b5e4dec89e1b558f62bd405e4f9180849e719d70
3b79ef098feec0d8253322e338fa853fc48bd6df
refs/heads/master
<repo_name>leonardobarrientosc/nozbe-projects-tasks-log<file_sep>/appz/src/BcTic/NozbeProjectsUtilsBundle/Entity/ApplicationRegister.php <?php namespace BcTic\NozbeProjectsUtilsBundle\Entity; class ApplicationRegister { private $email; private $password; private $redirectUrl; public function getEmail(){ return $this->email; } public function setEmail($email) { $this->email = $email; } public function getPassword(){ return $this->password; } public function setPassword($password) { $this->password = $password; } public function getRedirectUrl(){ return $this->redirectUrl; } public function setRedirectUrl($url) { $this->redirectUrl = $url; } } <file_sep>/appz/src/BcTic/NozbeProjectsUtilsBundle/Controller/DefaultController.php <?php namespace BcTic\NozbeProjectsUtilsBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use BcTic\NozbeProjectsUtilsBundle\Entity\ApplicationRegister; use BcTic\NozbeProjectsUtilsBundle\Form\ApplicationRegisterType; use BcTic\NozbeProjectsUtilsBundle\Form\ApplicationRegisterLoginType; use BcTic\NozbeProjectsUtilsBundle\Form\ApplicationRegisterRedirectUrlType; use Symfony\Component\HttpFoundation\Session\Session; class DefaultController extends Controller { /** * @Route("/", name="default_index") * @Template() */ public function indexAction() { return array(); } /** * @Route("/register-applicaction-with-nozbe", name="step_1") * @Template() */ public function step_1Action() { $entity = new ApplicationRegister(); $entity->setRedirectUrl('http://erp.bctic.net/oauth-return'); $form = $this->createCreateForm($entity); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * @Route("/getting-oauth-client-data", name="step_2") * @Template() */ public function step_2Action() { $entity = new ApplicationRegister(); $form = $this->createCreateFormStep2($entity); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * @Route("/change-the-app-data", name="step_3") * @Template() */ public function step_3Action() { $entity = new ApplicationRegister(); $entity->setRedirectUrl($this->get('session')->get('redirect_uri')); $form = $this->createCreateFormStep3($entity); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * @Route("/getting-the-oauth-access-token", name="step_4") * @Template() */ public function step_4Action() { return $this->redirect('https://api.nozbe.com:3000/login?client_id='.$this->get('session')->get('client_id')); } private function createCreateForm(ApplicationRegister $entity) { $form = $this->createForm(new ApplicationRegisterType(), $entity, array( 'action' => $this->generateUrl('step_1_submit'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Send')); return $form; } private function createCreateFormStep2(ApplicationRegister $entity) { $form = $this->createForm(new ApplicationRegisterLoginType(), $entity, array( 'action' => $this->generateUrl('step_2_submit'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Send')); return $form; } private function createCreateFormStep3(ApplicationRegister $entity) { $form = $this->createForm(new ApplicationRegisterRedirectUrlType(), $entity, array( 'action' => $this->generateUrl('step_3_submit'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Send')); return $form; } /** * * @Route("/getting-oauth-client-data-submit", name="step_1_submit") * @Method("POST") * @Template("BcTicNozbeProjectsUtilsBundle:Default:step_1.html.twig") */ public function step_1_submitAction(Request $request) { $entity = new ApplicationRegister(); $form = $this->createCreateFormStep2($entity); $form->handleRequest($request); if ($form->isValid()) { //HAGO LLAMADA $data = $this->callJson("https://api.nozbe.com:3000/oauth/secret/create", array(), array('email' => $entity->getEmail(), 'password' => $<PASSWORD>-><PASSWORD>(), 'redirect_uri' => $entity->getRedirectUrl())); if (isset($data['error'])) { $this->get('session')->getFlashBag()->add( 'error', 'Ha ocurrido un error: '.$data['error'] ); } } return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * * @Route("/register-applicaction-with-nozbe-submit", name="step_2_submit") * @Method("POST") * @Template("BcTicNozbeProjectsUtilsBundle:Default:step_2.html.twig") */ public function step_2_submitAction(Request $request) { $entity = new ApplicationRegister(); $form = $this->createCreateFormStep2($entity); $form->handleRequest($request); if ($form->isValid()) { //HAGO LLAMADA $data = $this->callJson("https://api.nozbe.com:3000/oauth/secret/data", array('email' => $entity->getEmail(), 'password' => $<PASSWORD>()), array()); if (isset($data['error'])) { $this->get('session')->getFlashBag()->add( 'error', 'Ha ocurrido un error: '.$data['error'] ); } else { $this->get('session')->getFlashBag()->add( 'notice', 'OK, CLIENT ID & CLIENT SECRET SAVED IN SESSION' ); //Guardo los datos: $this->get('session')->set('client_id', $data['client_id']); $this->get('session')->set('client_secret', $data['client_secret']); $this->get('session')->set('redirect_uri', $data['redirect_uri']); } } return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * * @Route("/change-the-app-data-submit", name="step_3_submit") * @Method("POST") * @Template("BcTicNozbeProjectsUtilsBundle:Default:step_3.html.twig") */ public function step_3_submitAction(Request $request) { $entity = new ApplicationRegister(); $form = $this->createCreateFormStep3($entity); $form->handleRequest($request); if ($form->isValid()) { //HAGO LLAMADA $data = $this->callJson("https://api.nozbe.com:3000/oauth/secret/data", array('client_id' => $this->get('session')->get('client_id'), 'secret_token' => $this->get('session')->get('client_secret')), array('redirect_uri' => $entity->getRedirectUrl()) ); if (isset($data['error'])) { $this->get('session')->getFlashBag()->add( 'error', 'Ha ocurrido un error: '.$data['error'] ); } else { $this->get('session')->getFlashBag()->add( 'notice', 'OK' ); //Guardo los datos: $this->get('session')->set('redirect_uri', $data['redirect_uri']); } } return array( 'entity' => $entity, 'form' => $form->createView(), ); } private function callJson($url,$getParams = array(), $postParams = array()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, (count($getParams) > 0 ) ? $url.'?'.http_build_query($getParams) : $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //POST? if (count($postParams) > 0) { curl_setopt($ch,CURLOPT_POST, count($postParams)); curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($postParams)); } $response = curl_exec($ch); $data = json_decode($response, true); return $data; } } <file_sep>/README.md # nozbe-projects-tasks-log HELLO WORLD! <file_sep>/appz/src/BcTic/NozbeProjectsUtilsBundle/BcTicNozbeProjectsUtilsBundle.php <?php namespace BcTic\NozbeProjectsUtilsBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class BcTicNozbeProjectsUtilsBundle extends Bundle { } <file_sep>/appz/src/BcTic/NozbeProjectsUtilsBundle/Command/NozbeProjectLogsAsNotesCommand.php <?php namespace BcTic\NozbeProjectsUtilsBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class NozbeProjectLogsAsNotesCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('nozbe:project-logs-as-notes') ->setDescription('CREATE A NOTE AS LOGS IN A PROJECT IN NOZBE') ->addArgument( 'api-oauth', InputArgument::REQUIRED, 'What is your Nozbe user mail (mandatory)?' ) ->addArgument( 'api-client-secret', InputArgument::REQUIRED, 'What is your Nozbe password (mandatory)?' ) ->addArgument( 'project-id', InputArgument::REQUIRED, 'What is your Project Id https://webapp.nozbe.com/api/projects/key-API_KEY (mandatory)?' ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $auth_log_url = 'https://api.nozbe.com:3000/oauth/secret/data'; $auth_log = $this->getJsonAsArray($auth_log_url, array('client_id' => $input->getArgument('api-client-id'),'client_secret' => $input->getArgument('api-client-secret'))); $tasks_log_url = 'https://webapp.nozbe.com/api/actions/what-project/id-'.$input->getArgument('project-id').'/showdone-1/key-'.$input->getArgument('api-key'); $tasks_log = $this->getJsonAsArray($tasks_log_url); $out = ''; $total = 0; if (!is_array($tasks_log)) continue; $i = 1; usort($tasks_log, function($a, $b) { return strcmp($a->done_time, $b->done_time); }); foreach ($tasks_log as $task) { if ($task->done == 0) continue; if ($task->time == 0) continue; //FOREACH I MUST CREATE A LINE: $out .= $i++.' - '.$task->done_time.' - '.$task->time.' min. '.chr(10).' '.$task->name.chr(10).chr(10); $total = $total + (int) $task->time; } $out .= chr(10).'TOTAL TIME: '.$total.' Minutes.'; $out .= chr(10).'API JSON CALL: '.$tasks_log_url; $this->publishNote($out,$input->getArgument('project-id'),$input,$output); } private function getJsonAsArray($url,$fields = array()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url.'?'.http_build_query($fields)); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //execute post $json = curl_exec($ch); $data = json_decode($json); return $data; } private function publishNote($content, $projectId,InputInterface $input, OutputInterface $output){ $content = rawurlencode($content); $url = 'https://webapp.nozbe.com/api/newnote/name-TASK_COMPLETED_LOG_'.date('Y-m-d-h:i').'/body-'.urlencode($content).'/project_id-'.$projectId.'/key-'.$input->getArgument('api-key'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); $data = json_decode($response); $output->writeln('Ok, YOU SHOULD NOW SEE A NEW NOTE IN PROJECT NOTES.'); } }
8fbb7690b7bb7f18a51cb5a86f9dd00215e3120a
[ "Markdown", "PHP" ]
5
PHP
leonardobarrientosc/nozbe-projects-tasks-log
8b3d165f11c966ee8b9f6999f8a90847fc0918f9
eb36d536b09b6723a5f07f3620b992df17995c72
refs/heads/master
<repo_name>igoramadas/bitecache<file_sep>/History.md # Changelog for Bitecache 1.3.1 ===== * Code refactoring. 1.3.0 ===== * NEW! Option "strict" can be set to false to avoid throwing errors with invalid collections. * Minor code refactoring. 1.2.2 ===== * Updated dependencies. 1.2.1 ===== * Updated dependencies. 1.2.0 ===== * Updated dependencies. 1.1.9 ===== * Updated dependencies. 1.1.8 ===== * Updated dependencies. 1.1.7 ===== * Updated dependencies. 1.1.6 ===== * Updated dependencies. 1.1.5 ===== * Updated dependencies. 1.1.4 ===== * Updated dependencies. 1.1.3 ===== * Updated dependencies. 1.1.2 ===== * Make sure Anyhow's logging is set up. * Updated dependencies. 1.1.1 ===== * Updated dependencies. 1.1.0 ===== * NEW! Method merge() to shallow merge data to existing cache. * Cache keys now also accept any data type. * Updated dependencies. 1.0.0 ===== * Initial release! <file_sep>/src/types.ts // Bitecache Types /** * A collection of cached items. */ export interface CacheCollection { /** Cached items. */ items: {} /** Default expires in (seconds). */ expiresIn: number /** Timer to expire old items. */ expireTimer: any /** Collection size (count). */ size: number /** Cache misses (count). */ misses: number } /** * A cached item. */ export interface CacheItem { /** Cached data. */ data: any /** Expire timestamp (epoch). */ expires: number } /** * Cache collection stats. */ export interface CacheStats { /** How many items cached. */ size: number /** Approx. memory used. */ memSize: number /** Total of cache misses. */ misses: number /** Expires in. */ expiresIn: number } <file_sep>/test/test.ts // TEST: BITECACHE import {describe, it} from "mocha" require("chai").should() describe("Bitecache Tests", function () { let bitecache = require("../src/index") it("Setup a collection with invalid expiresIn", function () { bitecache.setup("test", -5) }) it("Setup other collections", function () { bitecache.setup("test-another", 1) bitecache.setup("test-complex", 60) bitecache.setup("test-long-expire", 99999) }) it("Wait for expiration of items on test-another", function (done) { bitecache.set("test-another", "expire1", 1) bitecache.set("test-another", "expire2", 2) const check = () => { if (bitecache.totalSize == 0) { done() } else { done("Items on test-another did not expire") } } setTimeout(check, 3000) }) it("Setup same test collection again with expiresIn 1", function () { bitecache.setup("test", 1) }) it("Try getting invalid cache items, cache misses should be 3", function (done) { bitecache.get("test", "notexist1") bitecache.get("test", "notexist2") bitecache.get("test", "notexist3") const misses = bitecache.totalMisses if (misses == 3) { done() } else { done(`The total misses should be 3, but got ${misses}`) } }) it("Add an item to the cache", function () { bitecache.set("test", "a", "First", 1) }) it("Add an item to the cache with custom expiresIn 10", function () { bitecache.set("test", "b", "Second", 10) }) it("Get second added item", function (done) { const second = bitecache.get("test", "b") if (second == "Second") { done() } else { done("Did not return 'Second' for item 'b'") } }) it("First item should have expired by now", function (done) { const checkFirst = () => { const first = bitecache.get("test", "a") if (!first) { done() } else { done("Item 'a' should have expired") } } setTimeout(checkFirst, 1100) }) it("Fail to get expired item from long expiry collection", function (done) { const checkExpired = () => { const stillThere = bitecache.get("test-long-expire", "a") if (!stillThere) { done() } else { done("Item 'a' should have expired") } } bitecache.set("test-long-expire", "a", "still-here", 1) setTimeout(checkExpired, 1100) }) it("Add 10 itens to another collection", function () { for (let i = 0; i < 10; i++) { bitecache.set("test-another", i.toString(), i * 10) } }) it("Current size should be 11 (1 from test, 10 from test-another)", function (done) { const size = bitecache.totalSize if (size == 11) { done() } else { done(`Cache total size should be 11 but got ${size}`) } }) it("Delete item from cache", function (done) { if (bitecache.del("test", "b")) { done() } else { done("Deleting 'b' item should return true, but got false") } }) it("Deleting invalid item should return false, and current size 10", function (done) { const size = bitecache.totalSize if (bitecache.del("test", "b")) { done("Deleting 'b' item again should return false, but got true") } else if (size != 10) { done(`Cache total size should be now 10 but got ${size}`) } else { done() } }) it("Clear test-another, size should now be 0", function (done) { bitecache.clear("test-another") const size = bitecache.totalSize if (size == 0) { done() } else { done(`Total size should now be 0 but got ${size}`) } }) it("Get size used by cache", function (done) { const a = {a: "a"} const b = {b: "b"} bitecache.set("test-complex", "boolean", true) bitecache.set("test-complex", "string", "a") bitecache.set("test-complex", "number", 123) bitecache.set("test-complex", "date", new Date()) bitecache.set("test-complex", "array", ["1", 1, null]) bitecache.set("test-complex", "obj", { a: a, b: b, level0: { a: b } }) const memsize = bitecache.totalMemSize if (memsize > 150) { done() } else { done(`Total estimated memory size should be at least 150 bytes, but got ${memsize}`) } }) it("Merge data to existing cache item", function (done) { bitecache.set("test-complex", "to-merge", {a: "a", b: "a"}) bitecache.merge("test-complex", "to-merge", {b: "b"}) bitecache.set("test-complex", "to-merge-fail", 1) bitecache.merge("test-complex", "to-merge-fail", 2) if (bitecache.get("test-complex", "to-merge").b == "a") { done("Did not merge data") } else { done() } }) it("Get stats for cache", function () { bitecache.stats("test-complex") }) it("Throw error when calling methods on invalid collection", function (done) { try { bitecache.set("invalid") done("Calling set on invalid collection should throw an error") } catch (ex) {} try { bitecache.get("invalid") done("Calling get on invalid collection should throw an error") } catch (ex) {} try { bitecache.del("invalid") done("Calling del on invalid collection should throw an error") } catch (ex) {} try { bitecache.merge("invalid") done("Calling merge on invalid collection should throw an error") } catch (ex) {} try { bitecache.expire("invalid") done("Calling expire on invalid collection should throw an error") } catch (ex) {} try { bitecache.clear("invalid") done("Calling clear on invalid collection should throw an error") } catch (ex) {} try { bitecache.stats("invalid") done("Calling stats on invalid collection should throw an error") } catch (ex) {} try { bitecache.memSizeOf("invalid") done("Calling memSizeOf on invalid collection should throw an error") } catch (ex) {} done() }) it("Do not throw is strict is false", function (done) { bitecache.strict = false try { bitecache.set("invalid") } catch (ex) { return done("Calling set on invalid collection should not throw an error") } try { bitecache.get("invalid") } catch (ex) { return done("Calling set on invalid collection should not throw an error") } try { bitecache.del("invalid") } catch (ex) { return done("Calling del on invalid collection should not throw an error") } try { bitecache.merge("invalid") } catch (ex) { return done("Calling merge on invalid collection should not throw an error") } try { bitecache.expire("invalid") } catch (ex) { return done("Calling expire on invalid collection should not throw an error") } try { bitecache.clear("invalid") } catch (ex) { return done("Calling clear on invalid collection should not throw an error") } try { bitecache.stats("invalid") } catch (ex) { return done("Calling stats on invalid collection should not throw an error") } try { bitecache.memSizeOf("invalid") } catch (ex) { return done("Calling memSizeOf on invalid collection should not throw an error") } done() }) it("Setup a second instance which should have the same data", function (done) { let bitecache2 = require("../src/index") if (bitecache2.totalSize == 0) { done("Second instance should have the data from the first one") } else { done() } }) it("Clear all", function () { bitecache.clear() }) }) <file_sep>/src/index.ts // Bitecache import {CacheCollection, CacheItem, CacheStats} from "./types" import logger = require("anyhow") /** * Bitecache wrapper. */ class Bitecache { private constructor() {} private static _instance: Bitecache static get Instance() { return this._instance || (this._instance = new this()) } /** * Main holder of cached objects. */ private store: any = {} /** * Total cache size. */ get totalSize(): number { let result = 0 for (let collection in this.store) { result += this.store[collection].size } return result } /** * Total memory used by the cache. */ get totalMemSize(): number { let result = 0 for (let collection in this.store) { result += this.memSizeOf(collection) } return result } /** * Total cache misses. */ get totalMisses() { let result = 0 for (let collection in this.store) { result += this.store[collection].misses } return result } /** * If set to false, will not throw errors when trying to get * or set data from invalid cache collections. Default is true. */ strict: boolean = true // SETUP // -------------------------------------------------------------------------- /** * Setup a cache object with the specified name. * @param collection The collection name. * @param expiresIn Default expiration in seconds. */ setup = (collection: string, expiresIn: number): void => { if (expiresIn < 0.1) { expiresIn = 0.1 } // Make sure Anyhow was set up. if (!logger.isReady) { logger.setup() } // Replace current or create new collection? if (this.store[collection]) { clearInterval(this.store[collection].clearTimer) logger.info("Bitecache.setup", collection, `Expires in ${expiresIn}s`, "Collection already exists, will overwrite it") } else { logger.info("Bitecache.setup", collection, `Expires in ${expiresIn}s`) } // Cleanup helper. const cleanup = () => { this.expire(collection) } // Create and save the store collection. const store: CacheCollection = { items: {}, expiresIn: expiresIn, expireTimer: setInterval(cleanup, expiresIn * 1000), size: 0, misses: 0 } this.store[collection] = store } // METHODS // -------------------------------------------------------------------------- /** * Add an object to the specified cache collection. * @param collection Cache collection name. * @param key The object's unique key. * @param value The actual object. * @param expiresIn Optional if object should expire on a specific interval. */ set = (collection: string, key: string | number | Date, value: any, expiresIn?: number): void => { try { const store: CacheCollection = this.store[collection] if (!store) { if (this.strict) throw new Error(`Invalid collection: ${collection}`) else return } // Defaults to store's expireIn if the value is not valid. if (expiresIn < 0) { expiresIn = store.expiresIn } // Force key as string. key = key.toString() const now = new Date().getTime() const expires = expiresIn ? now + expiresIn * 1000 : now + store.expiresIn * 1000 const item: CacheItem = {data: value, expires: expires} store.items[key] = item store.size++ } catch (ex) { logger.error("Bitecache.set", collection, key, ex) throw ex } } /** * Get an object from the specified cache collection. * @param collection Cache collection name. * @param key The object's unique key. */ get = (collection: string, key: string | number | Date): any => { try { const store: CacheCollection = this.store[collection] if (!store) { if (this.strict) throw new Error(`Invalid collection: ${collection}`) else return } // Force key as string. key = key.toString() const now = new Date().getTime() const item = store.items[key] if (!item) { store.misses++ return null } if (item.expires <= now) { delete store.items[key] store.size-- return null } return item.data } catch (ex) { logger.error("Bitecache.get", collection, key, ex) throw ex } } /** * Remove an object from the specified cache collection. * @param collection Cache collection name. * @param key The object's unique key. */ del = (collection: string, key: string | number | Date): boolean => { try { const store: CacheCollection = this.store[collection] if (!store) { if (this.strict) throw new Error(`Invalid collection: ${collection}`) else return } // Force key as string. key = key.toString() if (!(key in store.items)) { store.misses++ return false } delete store.items[key] store.size-- return true } catch (ex) { logger.error("Bitecache.del", collection, key, ex) throw ex } } /** * Merge (shallow copy) data to an existing object on the specified cache collection. * @param collection Cache collection name. * @param key The object's unique key. * @param dataToMerge The data to be merged. */ merge = (collection: string, key: string | number | Date, dataToMerge: any): void => { try { const store: CacheCollection = this.store[collection] if (!store) { if (this.strict) throw new Error(`Invalid collection: ${collection}`) else return } // Force key as string. key = key.toString() // Get existing object. if (store.items[key] && typeof store.items[key].data == "object") { Object.assign(store.items[key].data, dataToMerge) } } catch (ex) { logger.error("Bitecache.merge", collection, key, ex) throw ex } } /** * Remove old items from the specified cache collection. * @param collection Cache collection name. */ expire = (collection: string): void => { try { const store: CacheCollection = this.store[collection] if (!store) { if (this.strict) throw new Error(`Invalid collection: ${collection}`) else return } const storeItems = Object.entries(store.items) const now = new Date().getTime() let key: string let item: any for ([key, item] of storeItems) { if (item.expires <= now) { delete store.items[key] store.size-- } } } catch (ex) { logger.error("Bitecache.expire", collection, ex) throw ex } } /** * Clear the cache. * @param collection Optional collection, if not specified will clear all collections. */ clear = (collection?: string): void => { try { if (collection) { const store: CacheCollection = this.store[collection] if (!store) { if (this.strict) throw new Error(`Invalid collection: ${collection}`) else return } store.items = {} store.size = 0 store.misses = 0 } else { for (let c in this.store) { this.store[c].items = {} this.store[c].size = 0 this.store[c].misses = 0 } } } catch (ex) { logger.error("Bitecache.clear", collection, ex) throw ex } } /** * Get individual stats for the specified cache collection. * @param collection Optional cache collection name. */ stats = (collection?: string): CacheStats => { try { const store: CacheCollection = this.store[collection] if (!store) { if (this.strict) throw new Error(`Invalid collection: ${collection}`) else return } return { size: store.size, memSize: this.memSizeOf(collection), misses: store.misses, expiresIn: store.expiresIn } } catch (ex) { logger.error("Bitecache.stats", collection, ex) throw ex } } // HELPERS // -------------------------------------------------------------------------- /** * Calculate memory usage for the specified collection. * */ memSizeOf = (collection: string): number => { try { const store: CacheCollection = this.store[collection] if (!store) { if (this.strict) throw new Error(`Invalid collection: ${collection}`) else return } const objectList = [] let stack = [store.items] let bytes = 0 // Iterate items to calculate memory size. while (stack.length) { let value = stack.pop() if (typeof value === "boolean") { bytes += 4 } else if (typeof value === "string") { bytes += value.length * 2 } else if (typeof value === "number") { bytes += 8 } else if (typeof value === "object" && objectList.indexOf(value) === -1) { objectList.push(value) if (Object.prototype.toString.call(value) != "[object Array]") { for (let key in value) { bytes += 2 * key.length } } for (let key in value) { stack.push(value[key]) } } } return bytes } catch (ex) { logger.error("Bitecache.expire", collection, ex) throw ex } } } // Exports... export = Bitecache.Instance <file_sep>/README.md # Bitecache [![Version](https://img.shields.io/npm/v/bitecache.svg)](https://npmjs.com/package/bitecache) [![Coverage Status](https://coveralls.io/repos/github/igoramadas/bitecache/badge.svg?branch=master)](https://coveralls.io/github/igoramadas/bitecache?branch=master) [![Build Status](https://github.com/igoramadas/bitecache/actions/workflows/build.yml/badge.svg)](https://github.com/igoramadas/bitecache/actions) A tiny, in-memory cache manager that won't bite you :-) ## Basic usage ```javascript const cache = require("bitecache") // Create a "users" cache collection with 20 seconds expiration, // and a "products" with expiration in 10 minutes. cache.setup("users", 20) cache.setup("products", 600) // Add a new user with cache key "jdoe". const user = {name: "John", surname: "Doe"} cache.set("users", "jdoe" user) // Get <NAME> from cache. const cachedUser = cache.get("users", "jdoe") // You can also merge data to existing cached objects. cache.merge("users", "jdoe", {surname: "New Doe"}) // A user that does not exist, will return null. const invalidUser = cache.get("users", "invalid") // Remove user from cache. cache.del("users", "jdoe") // Individual cache items can also have their own expiresIn, here we add // a product that expires in 30 seconds instead of the 10 mminutes default. cache.set("products", "myproduct", {title: "My Product"}, 30) // Log cache's total size, estimation of memory size, and cache misses. console.log("Total size", cache.totalSize) console.log("Total memory size", cache.totalMemSize) console.log("Total misses", cache.totalMisses) // Log individual cache collection stats. console.dir(cache.stats("users")) // Clear the users cache or all cache collections. cache.clear("users") cache.clear() // By default, hitting an invalid collection will throw an exception. try { const invalidCollection = cache.get("oops", "some-id") } catch (ex) { console.error(ex) } // You can disable the strict mode and it won't throw an exception, // but return undefined instead. cache.strict = false const invalidAgain = cache.get("oops", "some-id") cachet.set("oops", "another invalid") ```
d0ded6f208012ea0cf38255a0f3443cbfa0c1769
[ "Markdown", "TypeScript" ]
5
Markdown
igoramadas/bitecache
3abe7700cfa87b12c37ee073db77994c0f87fa97
b8fd7e5cdec0eda1406d7ba3aee21cb23ddd89fb
refs/heads/master
<repo_name>Yuditskiy-o/2GIS-test-task<file_sep>/README.md [![Build status](https://ci.appveyor.com/api/projects/status/0m44407llao3uunf/branch/master?svg=true)](https://ci.appveyor.com/project/Yuditskiy-o/2gis-test-task/branch/master) # Тестовое задание для 2GIS - [Тестовое задание](https://github.com/Yuditskiy-o/2GIS-test-task/blob/master/documents/%D0%A2%D0%B5%D1%81%D1%82%D0%BE%D0%B2%D0%BE%D0%B5%20%D0%B7%D0%B0%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5%202GIS.pdf) - [Файл с тест-кейсами и баг-репортами](https://docs.google.com/spreadsheets/d/1Hkiwq4ov_yGq9G4GKByQ2gmBmxgY96EOVRtiAREby8E/edit#gid=0) ## Отчет Allure по итогам тестирования: ![image](https://user-images.githubusercontent.com/64474359/116820714-8e924600-aba0-11eb-9e39-080ca72793c2.png) <file_sep>/build.gradle plugins { id 'java' id "io.freefair.lombok" version "6.0.0-m2" id 'io.qameta.allure' version '2.8.1' } allure { autoconfigure = true version = '2.13.6' // Latest Allure Version useJUnit5 { version = '2.13.6' // Latest Allure Version } } repositories { mavenCentral() } compileJava.options.encoding = "UTF-8" compileTestJava.options.encoding = "UTF-8" dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' testImplementation 'io.rest-assured:rest-assured:4.3.3' testImplementation 'io.rest-assured:json-path:4.3.3' implementation group: 'io.rest-assured', name: 'json-schema-validator', version: '3.0.0' } test { useJUnitPlatform() }<file_sep>/settings.gradle rootProject.name = '2GIS-test-task' <file_sep>/src/test/java/ru/gis/test/QueryQTest.java package ru.gis.test; import io.restassured.builder.RequestSpecBuilder; import io.restassured.filter.log.LogDetail; import io.restassured.http.ContentType; import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.basePath; import static io.restassured.RestAssured.given; import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; import static org.hamcrest.Matchers.hasItems; public class QueryQTest { private final RequestSpecification requestSpec = new RequestSpecBuilder() .setBaseUri("https://regions-test.2gis.com") .setBasePath("/1.0/regions") .setUrlEncodingEnabled(false) .setAccept(ContentType.JSON) .setContentType(ContentType.JSON) .log(LogDetail.ALL) .build(); @Nested class QBelow3Tests { @Test void shouldCheckIfGetErrorWithOnlyQ() { given() .spec(requestSpec) .queryParam("q") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("q/error_schema_with_q_below_3.json")); } @Test void shouldCheckIfGetErrorWithQAndSign() { given() .spec(requestSpec) .queryParam("q=") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("q/error_schema_with_q_below_3.json")); } @Test void shouldCheckIfGetErrorWithQAnd1Symbol() { given() .spec(requestSpec) .queryParam("q=а") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("q/error_schema_with_q_below_3.json")); } @Test void shouldCheckIfGetErrorWithQAnd2Symbols() { given() .spec(requestSpec) .queryParam("q=ак") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("q/error_schema_with_q_below_3.json")); } } @Nested class SuccessfulAndUnsuccessfulSearchForQSign3 { @Test void shouldCheckIfSearchWorksWith3CorrectSymbols() { given() .spec(requestSpec) .queryParam("q=акт") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items.name", hasItems("Актау", "Актобе")); } @Test void shouldCheckIfGetErrorWhereQIs3IncorrectSymbols() { given() .spec(requestSpec) .queryParam("q=пол") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("error_schema_with_no_results_were_found.json")); } } @Nested class SuccessfulAndUnsuccessfulSearchForFullNames { @Test void shouldCheckIfSearchWorksWithCorrectFullName() { given() .spec(requestSpec) .queryParam("q=Новосибирск") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items.name", hasItems("Новосибирск")); } @Test void shouldCheckIfGetErrorWhereQIsIncorrectFullName() { given() .spec(requestSpec) .queryParam("q=Ставрополь") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("error_schema_with_no_results_were_found.json")); } @Test void shouldCheckIfGetErrorWhereQIsFullNameWith2Symbols() { given() .spec(requestSpec) .queryParam("q=Ош") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("q/error_schema_with_q_below_3.json")); } } @Nested class QWith30andMoreSymbols { @Test void shouldCheckIfGetErrorWhereQIs30Symbols() { given() .spec(requestSpec) .queryParam("q=Новосибирсккккккккккккккккккк") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("error_schema_with_no_results_were_found.json")); } @Test void shouldCheckIfGetErrorWhereQIs31Symbols() { given() .spec(requestSpec) .queryParam("q=Новосибирскккккккккккккккккккф") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("q/error_schema_with_q_more_30.json")); } @Test void shouldCheckIfGetErrorWhereQIs50Symbols() { given() .spec(requestSpec) .queryParam("q=Новосибирскккккккккккккккккккфыыыыыыыыыыффффффффф") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body(matchesJsonSchemaInClasspath("q/error_schema_with_q_more_30.json")); } } @Nested class LowercaseAndUppercaseChecks { @Test void shouldCheckIfSearchWorksWithCorrectFullNameInUpperCase() { given() .spec(requestSpec) .queryParam("q=НОВОСИБИРСК") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items.name", hasItems("Новосибирск")); } @Test void shouldCheckIfSearchWorksWithCorrectFullNameInLowerCase() { given() .spec(requestSpec) .queryParam("q=новосибирск") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items.name", hasItems("Новосибирск")); } } @Nested class SearchWithQAndOtherQuery { @Test void shouldCheckIfSearchWorksWithQIs3SymbolsAndOtherQuery() { given() .spec(requestSpec) .queryParam("q=рск") .queryParam("сountry_code=ru") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items.name", hasItems("Красноярск", "Магнитогорск", "Новосибирск", "Орск", "Усть-Каменогорск")); } @Test void shouldCheckIfSearchWorksWithCorrectFullNameInLowerCase() { given() .spec(requestSpec) .queryParam("q=рск") .queryParam("page=2") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items.name", hasItems("Красноярск", "Магнитогорск", "Новосибирск", "Орск", "Усть-Каменогорск")); } } } <file_sep>/src/test/java/ru/gis/test/QueryPageSizeTest.java package ru.gis.test; import io.restassured.builder.RequestSpecBuilder; import io.restassured.filter.log.LogDetail; import io.restassured.http.ContentType; import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.basePath; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.hasSize; public class QueryPageSizeTest { private final RequestSpecification requestSpec = new RequestSpecBuilder() .setBaseUri("https://regions-test.2gis.com") .setBasePath("/1.0/regions") .setUrlEncodingEnabled(false) .setAccept(ContentType.JSON) .setContentType(ContentType.JSON) .log(LogDetail.ALL) .build(); @Nested class PageSizeWithNoArgs { @Test void shouldCheckIfGetErrorWhenOnlyPageSize() { given() .spec(requestSpec) .queryParam("page_size") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("error.message", equalTo("Параметр 'page_size' должен быть целым числом")); } @Test void shouldCheckIfGetErrorWhenPageSizeAndSign() { given() .spec(requestSpec) .queryParam("page_size=") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("error.message", equalTo("Параметр 'page_size' должен быть целым числом")); } } @Nested class PageSizeWithIncorrectArgs { @Test void shouldCheckIfGetErrorWhenPageSizeSignMinus1() { given() .spec(requestSpec) .queryParam("page_size=-1") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15")); } @Test void shouldCheckIfGetErrorWhenPageSizeSign0() { given() .spec(requestSpec) .queryParam("page_size=0") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15")); } @Test void shouldCheckIfGetErrorWhenPageSizeSignFloat() { given() .spec(requestSpec) .queryParam("page_size=1.1") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15")); } @Test void shouldCheckIfGetErrorWhenPageSizeSignLetters() { given() .spec(requestSpec) .queryParam("page_size=акт") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15")); } @Test void shouldCheckIfGetErrorWhenPageSizeSignSpecialCharacters() { given() .spec(requestSpec) .queryParam("page_size=$$$$") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15")); } } @Nested class PageSizeWithSizeFilterAndDefaultCountTest { @Test void shouldCheckIfSearchWorksWithExact5Cities() { given() .spec(requestSpec) .queryParam("page_size=5") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items", hasSize(5)); } @Test void shouldCheckIfSearchWorksWithExact10Cities() { given() .spec(requestSpec) .queryParam("page_size=10") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items", hasSize(10)); } @Test void shouldCheckIfSearchWorksWithExact15Cities() { given() .spec(requestSpec) .queryParam("page_size=15") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items", hasSize(15)); } @Test void shouldCheckIfGetErrorWhenPageSizeMoreWhen15() { given() .spec(requestSpec) .queryParam("page_size=20") // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15")); } @Test void shouldCheckIfDefaultCountOfRegionsIs15() { given() .spec(requestSpec) // Выполняемые действия .when() .get(basePath) // Проверки .then().assertThat().statusCode(200) .and().body("items", hasSize(15)); } } }
031442dca1761a79cd60c7d3a5ab1951ec0c2698
[ "Markdown", "Java", "Gradle" ]
5
Markdown
Yuditskiy-o/2GIS-test-task
9e1346f30223f3c934b6eae2f2121336c8fb8012
86603c3dbe33126a0ee794c415f3f0010caf815b
refs/heads/master
<repo_name>codingpains/acts_as_seekable_example<file_sep>/app/models/soccer_player.rb class SoccerPlayer < ActiveRecord::Base belongs_to :team validates_presence_of :age validates_presence_of :level validates_presence_of :name acts_as_seekable :paginate => true #Write all the named scopes you need for the filter paramater. #Write a named scope called search with a lambda, #this is important for your search field to work #By status named_scope :active, :conditions => { :active => true } named_scope :inactive, :conditions => { :active => false } #By level named_scope :amateur, :conditions => { :level => 'Amateur' } named_scope :semipro, :conditions => { :level => 'Semipro' } named_scope :pro, :conditions => { :level => 'Pro' } #By age named_scope :child, :conditions => { :age => 5..14 } named_scope :old, :conditions => { :age => 31..99 } named_scope :young, :conditions => { :age => 15..30 } named_scope :search, lambda { |value| { :conditions => "soccer_players.name LIKE '%#{value}%'" }} def description "#{name} [#{team_name}]" end def team_name team ? team.name : "No team" end end <file_sep>/app/helpers/application_helper.rb # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def title(string) content_for(:title, string) string end end <file_sep>/app/controllers/soccer_players_controller.rb class SoccerPlayersController < ApplicationController def index @soccer_players = SoccerPlayer.seek(params) end def new @soccer_player = SoccerPlayer.new end def edit @soccer_player = SoccerPlayer.find(params[:id]) end def create @soccer_player = SoccerPlayer.new(params[:soccer_player]) if @soccer_player.save flash[:notice] = 'Soccer player was successfully created.' redirect_to(soccer_players_path) else render :new end end def update @soccer_player = SoccerPlayer.find(params[:id]) if @soccer_player.update_attributes(params[:soccer_player]) flash[:notice] = 'Soccer player was successfully updated.' redirect_to(soccer_players_path) else render :edit end end def destroy @soccer_player = SoccerPlayer.find(params[:id]) @soccer_player.destroy flash[:notice] = "Soccer player #{@soccer_player.name} deleted" end end <file_sep>/app/models/team.rb class Team < ActiveRecord::Base has_many :soccer_players validates_presence_of :name validates_presence_of :championships before_destroy :kick_out_players accepts_nested_attributes_for :soccer_players, :allow_destroy => true acts_as_seekable # Example with no pagination #By Championships named_scope :noob, :conditions => {:championships => 0..2} named_scope :ruler, :conditions => {:championships => 3..20} #By level named_scope :amateur, :conditions => { :level => 'Amateur' } named_scope :semipro, :conditions => { :level => 'Semipro' } named_scope :pro, :conditions => { :level => 'Pro' } named_scope :search, lambda {|value|{ :conditions => "teams.name LIKE '%#{value}%' OR teams.city LIKE '%#{value}%'"}} private def kick_out_players soccer_players.each { |player| player.team = nil player.save(false) } end end <file_sep>/app/helpers/soccer_players_helper.rb module SoccerPlayersHelper def soccer_player_status(active) if active content_tag(:span, "Active", :class => 'active') else content_tag(:span, "Retired", :class => 'inactive') end end def soccer_players_filter select_tag(:filter, grouped_options_for_select(grouped_soccer_player_filter_options)) end def soccer_players_order select_tag(:order, options_for_select(soccer_player_order_options)) end def soccer_players_per_page select_tag(:per_page, options_for_select(per_page_options)) end private def soccer_player_order_options [['Name ascendent', 'name ASC'], ['Name descendent', 'name DESC'], ['Age ascendent', 'age ASC'], ['Age descendent', 'age DESC']] end def grouped_soccer_player_filter_options [ ['All',[['All soccer players','all_records']]], ['By Age',[['Children','child' ], ['Youth','young'],['Veteran','old']]], ['By level', [['Amateur','amateur'],['Semipro','semipro'],['Pro','pro']]], ['By status',[['Active','active'],['Retired','inactive']]] ] end def per_page_options (1..10) end end <file_sep>/test/unit/helpers/soccer_players_helper_test.rb require 'test_helper' class SoccerPlayersHelperTest < ActionView::TestCase end <file_sep>/app/helpers/teams_helper.rb module TeamsHelper def teams_filter select_tag(:filter, grouped_options_for_select(grouped_team_filter_options)) end def teams_order select_tag(:order, options_for_select(team_order_options)) end private def team_order_options [['Name ascendent', 'name ASC'], ['Name descendent', 'name DESC'], ['Championships ascendent', 'championships ASC'], ['Championships descendent', 'championships DESC'], ['City ascendent', 'city ASC'], ['City descendent', 'city DESC'], ['State ascendent', 'state ASC'], ['State descendent', 'state DESC'] ] end def grouped_team_filter_options [ ['All',[['All teams','all_records']]], ['By Championships',[['Rulers','ruler' ], ['Noobs','noob']]], ['By level', [['Amateur','amateur'],['Semipro','semipro'],['Pro','pro']]], ] end end <file_sep>/app/controllers/teams_controller.rb class TeamsController < ApplicationController def index @teams = Team.seek(params) end def show @team = Team.find_by_id(params[:id]) end def new @team = Team.new end def edit @team = Team.find(params[:id]) end def create @team = Team.new(params[:team]) if @team.save flash[:notice] = 'Team was successfully created.' redirect_to(teams_path) else render :new end end def update @team = Team.find(params[:id]) if @team.update_attributes(params[:team]) flash[:notice] = 'Team was successfully updated.' redirect_to(teams_path) else render :edit end end def destroy @team = Team.find(params[:id]) @team.destroy flash[:notice] = "Team #{@team.name} deleted" respond_to do |format| format.html {redirect_to(teams_path)} format.js end end end <file_sep>/app/helpers/form_helper.rb module FormHelper def required "<span class=\"required\">*</span>" end def delete_fields_link(fields, tag = "tr") out = '' unless fields.object.new_record? out << fields.hidden_field(:_delete) out << link_to_function("remove", "this.up('#{tag}').hide(); hidden_input = this.previous('input[type=hidden]'); hidden_input.value = '1';") else out << link_to_function("remove", "this.up('#{tag}').remove()") end out end def add_link_for(children_name, form_builder) children_name = children_name.to_sym unless children_name.class.equal?(Symbol) child = eval("form_builder.object.#{children_name.to_s}.build") link_to_function "add #{children_name.to_s.singularize.gsub(/_/,' ')}" do |page| form_builder.fields_for children_name, child, :child_index => 'NEW_RECORD' do |f| html = render(:partial => child.class.table_name.singularize, :locals => { :form => f }) page << "$('#{children_name.to_s}').insert({ bottom: '#{escape_javascript(html)}'.replace(/NEW_RECORD/g, new Date().getTime()) });" end end end end <file_sep>/test/functional/soccer_players_controller_test.rb require 'test_helper' class SoccerPlayersControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success assert_not_nil assigns(:soccer_players) end test "should get new" do get :new assert_response :success end test "should create soccer_player" do assert_difference('SoccerPlayer.count') do post :create, :soccer_player => { } end assert_redirected_to soccer_player_path(assigns(:soccer_player)) end test "should show soccer_player" do get :show, :id => soccer_players(:one).to_param assert_response :success end test "should get edit" do get :edit, :id => soccer_players(:one).to_param assert_response :success end test "should update soccer_player" do put :update, :id => soccer_players(:one).to_param, :soccer_player => { } assert_redirected_to soccer_player_path(assigns(:soccer_player)) end test "should destroy soccer_player" do assert_difference('SoccerPlayer.count', -1) do delete :destroy, :id => soccer_players(:one).to_param end assert_redirected_to soccer_players_path end end <file_sep>/db/migrate/20090429183521_create_soccer_players.rb class CreateSoccerPlayers < ActiveRecord::Migration def self.up create_table :soccer_players do |t| t.string :name t.integer :age t.boolean :active t.string :level t.integer :team_id t.timestamps end end def self.down drop_table :soccer_players end end
4c3f08455d39c5200b2edad128b23b99727777c9
[ "Ruby" ]
11
Ruby
codingpains/acts_as_seekable_example
a445674682a8101b5dcf6ab44498dcbbfe587101
0f1229041e8133affb4643c17a7fd3d500a61ad1
refs/heads/master
<file_sep>// Copyright (C) 2019 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "utility.h" #include <android-base/logging.h> #include <android-base/strings.h> namespace android { namespace snapshot { void AutoDevice::Release() { name_.clear(); } AutoDeviceList::~AutoDeviceList() { // Destroy devices in the reverse order because newer devices may have dependencies // on older devices. for (auto it = devices_.rbegin(); it != devices_.rend(); ++it) { it->reset(); } } void AutoDeviceList::Release() { for (auto&& p : devices_) { p->Release(); } } AutoUnmapDevice::~AutoUnmapDevice() { if (name_.empty()) return; if (!dm_->DeleteDeviceIfExists(name_)) { LOG(ERROR) << "Failed to auto unmap device " << name_; } } AutoUnmapImage::~AutoUnmapImage() { if (name_.empty()) return; if (!images_->UnmapImageIfExists(name_)) { LOG(ERROR) << "Failed to auto unmap cow image " << name_; } } } // namespace snapshot } // namespace android
4315a7ad8c25310379a9d95ae97e0d22c76c858c
[ "C++" ]
1
C++
tiger-cave/platform_system_core
537e4af23512389438b86f31ee81eb522111f944
fce101b9af038004bf13bf71099642e511b27a05
refs/heads/master
<repo_name>angelo98-dev/Read_Text<file_sep>/README.txt Hello je m'appel Angelo ! Description du programme: Programme consistant à lire un fichier et afficher son contenu dans le terminal ou la console. Apres avoir lancé le programme, indiquez le chemin du fichier à lire. exemple : /home/PycharmProjects/texte_a_lire.txt <file_sep>/read_text.py ################################### # Program's name Read file # # Author(s) : @ngelo ELijah, 2019 # # Profession # ################################### #!/usr/local/bin/python3.7 # -*-coding:utf-8 *- ################################### # External functions importation #import os ################################### # Local functions definition from functions_bank import* ################################### # Main programme's body again = 1 while again: chemin = input("Indiquer le chemin du fichier :") try: with open(chemin, 'r') as fichier: contenu = fichier.read() print(contenu) except FileNotFoundError as e: print("Le fichier n'existe pas !") except IsADirectoryError as e: print("Vous n'avez pas indiqué un fichier !") again = question("Lire un autre fichier ? (yes, no) : ") #os.system("pause") #for windows user <file_sep>/functions_bank.py ################################### # Functions_Banks # # Author(s) : @ngelo ELijah, 2019 # # Profession # ################################### def question(annonce='Yes or No ?, please : '): """function to ask the user a Yes or No question""" reponse = input(annonce) if(reponse in ('y','Y','Yes','YES','YeS','yES','yeS','YEs','yEs')): return 1 if(reponse in ('n','N','No','NO','nO')): return 0
1a2a4d6106d7b06a5ef3be50cbc3dc79e54fa08e
[ "Python", "Text" ]
3
Text
angelo98-dev/Read_Text
deb0b8134d66405e81035eab683b56835ba84f49
79a299347bb598aca60d1c94b2852827bc5f20a1
refs/heads/main
<repo_name>Gaurang-WEB-MAKER-OP/c-1115<file_sep>/main.js noseX = 0; noseY = 0; function preload() { clown_nose = lodImage("'https://i.postimg.cc/7ZBcjDqp/clownnose.png") } function setup() { canvas = createCanvas(300, 300); canvas.center(); veido = createCapture(VEDIO); VEDIO.SIZE(300, 300); VEDIO.HIDE(); poseNET = ml5.poseNET(video, modelLoded); poseNet.on('poseNet is intialized') }
f2b15ae6945425279774aa6fb0e10c68ad30b84f
[ "JavaScript" ]
1
JavaScript
Gaurang-WEB-MAKER-OP/c-1115
5a93565b09745f51c8a76fbfca8742ef8174dcf0
2b09ca30236e51d889a259020c749e3955b7d7d6
refs/heads/master
<file_sep>#! python3 #phoneAndEmial.py - Wyszukuje numery tel i adresy e-mail w tekście skopiowanym do schowka """Przykłądowy tekst (415)-555-4242 ext 44 zawierający numery 422 111 4545 telefonów <EMAIL> oraz adresy mail <EMAIL>. Wystraczy skopiować.""" import re import pyperclip clipboard = str(pyperclip.paste()) find_num = re.compile(r"""( (\d{3}|\(\d{3}\))? #numer kierunkowy (\s|-|\.)? #separator (\d{3}) #pierwsze 3 cyfry (\s|-|\.)? #separator (\d{4}) #ostatnie cyfry (\s*(ext|x|ext.)\s*(\d{2,5}))? #numer wewnętrzny )""", re.VERBOSE) find_email = re.compile(r"""( ([a-zA-Z0-9._-])+ #nazwa użytkownika @ #małpa ([a-zA-Z0-9._-])+ #nazwa domeny (\.[a-zA-Z]{2,4})+ #końcówka )""", re.VERBOSE) clip_out = [] for groups in find_num.findall(clipboard): phone_num = "-".join([groups[1], groups[3], groups[5]]) if groups[8]!= "": phone_num += " x" + groups[8] clip_out.append(phone_num) for groups in find_email.findall(clipboard): clip_out.append(groups[0]) if len(clip_out) > 0: print("Skopiowano do schowka: ") print("\n".join(clip_out)) pyperclip.copy("\n".join(clip_out)) else: print("Nie znaleziono numerów tel. i adresów e-mail") <file_sep>#! python3 # -*- coding: utf-8 -*- # madLibs.py - finds word NOUN, VERB, ADVERB and ADJECTIVE in text and change they to inputted import re example_text = open("./madLibs.txt") read_text = example_text.read() print(read_text) print("\n") find_word = re.compile(r"NOUN|VERB|ADJECTIVE|ADVERB") results_list = find_word.findall(read_text) # Addition new key word and change it in text new_word = {} num_noun = 0 num_verb = 0 num_adv = 0 num_adj = 0 for i in range(len(results_list)): if results_list[i] == "NOUN": new_word["noun{0}".format(num_noun)] = input("Podaj rzeczownik: \n") read_text = read_text.replace(results_list[i], new_word["noun{0}".format(num_noun)], 1) num_noun += 1 elif results_list[i] == "VERB": new_word["verb{0}".format(num_verb)] = input("Podaj czasownik: \n") read_text = read_text.replace(results_list[i], new_word["verb{0}".format(num_verb)], 1) num_verb += 1 elif results_list[i] == "ADVERB": new_word["adverb{0}".format(num_adv)] = input("Podaj przysłówek: \n") read_text = read_text.replace(results_list[i], new_word["adverb{0}".format(num_adv)], 1) num_adv += 1 elif results_list[i] == "ADJECTIVE": new_word["adjective{0}".format(num_adj)] = input("Podaj przymiotnik: \n") read_text = read_text.replace(results_list[i], new_word["adjective{0}".format(num_adj)], 1) num_adj += 1 print(read_text) print("\n") example_text.close() # Save new text in new file edited = open("editedMadLibs.txt", "w") edited.write(read_text) edited.close() <file_sep>#! python3 #strongPassword.py - Sprawdza "siłę" hasła: min 8 znaków, małe i duże litery, min 1 cyfra import re print("Wprowadź hasło: ") your_password = input() def strong_password(password): if len(password) < 8: print("Hasło musi zawierać min. 8 znaków") digit_pass = re.compile(r"[0-9]+") mo1 = digit_pass.search(password) if mo1 == None: print("Hasło musi zawierać min. jedną cyfrę") else: print(mo1.group()) upper_pass = re.compile(r"[A-Z]+") mo2 = upper_pass.search(password) if mo2 == None: print("Hasło musi zawierać min. jedną wielką literę") else: print(mo2.group()) strong_password(your_password)<file_sep>#! python3 # randomQuizGenerator.py - tworzy quiz z losowo ułożonymi pytaniami i odpowiedziami import random # Dane quizu. Klucze to nazwy stanów, wartości to ich stolice. capitals = {"Alabama":"Montgomery", "Alaska":"Juneau", "Arizona":"Phoenix", "Arkansas":"Little Rock", "Kalifornia":"Sacramento", "Kolorado":"Denver", "Connecticut":"Hartford", "Delaware":"Dover", "Floryda":"Tallahasse", "Georgia":"Atlanta", "Hawaje":"Honolulu", "Idaho":"Boise", "Illnois":"Springfield", "Indiana":"Indianapolis", "Iowa":"Des Moines", "Kansas":"Topeka", "Kentucky":"Frankfort", "Luizjana":"Baton Rouge", "Maine":"Augusta", "Maryland":"Annapolis", "Massachusetts":"Boston", "Michigan":"Lansing", "Minnesota":"Saint Paul", "Mississippi":"Jackson", "Missouri":"Jefferson City", "Montana":"Helena", "Nebraska":"Lincoln", "Nevada":"Carson City", "New Hampshire":"Concord", "New Jersey":"Trenton", "Nowy Meksyk":"Santa Fe", "Nowy Jork":"Albany", "Karolina Północna":"Raleigh", "Dakota Północna":"Bismarck", "Ohio":"Columbus", "Oklahoma":"Oklahoma City", "Oregon":"Salem", "Pensylwania":"Harrisburg", "Rhode Island":"Providence", "Karolina Południowa":"Columbia", "Dakota Południowa":"Pierre", "Tennessee":"Nashville", "Teksas":"Austin", "Utah":"Salt Lake City", "Vermont":"Montpelier", "Wirginia":"Richmond", "Waszyngton":"Olympia", "Wirginia Zachodnia":"Charleston", "Wisconsin":"Madison", "Wyoming":"Cheyenne"} # Wygenerowanie 35 plików quizu for quiz_num in range(3): # Utworzenie plików quizu i odpowiedzi na pytania quiz_file = open("capitalsquiz%s.txt" % (quiz_num + 1), "w") answer_key_file = open("capitalsquiz_answers%s.txt" % (quiz_num + 1), "w") # Zapis nagłówka quizu quiz_file.write("Imię i nazwisko:\n\nData:\n\nKlasa:\n\n") quiz_file.write((" "*20) + "Quiz stolic stanów (Quiz %s)" % (quiz_num + 1)) quiz_file.write("\n\n") # Losowe ustalenie kolejności pytań states = list(capitals.keys()) random.shuffle(states) #TODO: Iteracja przez 50 stanów i utworzenie pytania dotyczącego każdego z nich for question_num in range(50): #Przygotowanie prawidłowych i nieprawidłowych odpowiedzi correct_answer = capitals[states[question_num]]1 wrong_answer = list(capitals.values()) del wrong_answer[wrong_answer.index(correct_answer)] wrong_answer = random.sample(wrong_answer, 3) answer_options = wrong_answer + [correct_answer] random.shuffle(answer_options) #Zapis pytania i odpowiedzi w pliku quizu quiz_file.write("%s. Co jest stolicą stanu %s?\n" % (question_num + 1, states[question_num])) for i in range(4): quiz_file.write(" %s. %s\n" % ("ABCD"[i], answer_options[i])) quiz_file.write("\n") # Zapis odpowiedzi w pliku. answer_key_file.write("%s. %s\n" % (question_num + 1, "ABCD"[answer_options.index(correct_answer)])) quiz_file.close() answer_key_file.close() <file_sep>#! python3 # mcb.pyw - save and load text in clipboard # use py.exe mcb.pyw save <key word> - save clipboard with key word # py.exe mcv.pyw <key word> - load key word to clipboard # py.exe mcb.pyw list - load all key word to clipboard # py.exe mcb.pyw delete - clear all key word # py.exe mcb.pyw delete <key word> - remove key word from base import shelve, pyperclip, sys mcbShelf = shelve.open("mcb") if len(sys.argv) == 3 and sys.argv[1].lower() == "save": mcbShelf[sys.argv[2]] = pyperclip.paste() elif len(sys.argv) == 3 and sys.argv[1].lower() == "delete": del mcbShelf[sys.argv[2]] elif len(sys.argv) == 2: if sys.argv[1].lower() == "list": pyperclip.copy(str(list(mcbShelf.keys()))) elif sys.argv[1].lower() == "delete": mcbShelf.clear() elif sys.argv[1] in mcbShelf: pyperclip.copy(mcbShelf[sys.argv[1]]) mcbShelf.close()
40ea0a58c27c2de83dc15e57946230a7b40f0a4f
[ "Python" ]
5
Python
dharaszczuk/Practice-Projects
60eedf4977c299df40e0971611691af5f58c53f0
a1b2f59976f9cee485fd70e051ebeb23072d1249
refs/heads/master
<file_sep>package com.example.vaibhav.project1; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class Welcome extends AppCompatActivity { Spinner category; Button go; boolean cat; TextView wu; int timelimit=60; String[] c={"Select your category","Aptitude","Science","Current Affairs"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome_xml); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); category=(Spinner)findViewById(R.id.category); go=(Button)findViewById(R.id.cont); wu=(TextView)findViewById(R.id.welcomeuser); Bundle b=getIntent().getExtras(); wu.setText("WELCOME "+b.getString("username")); MainActivity.currentuser=b.getString("username"); loadCategory(); category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position > 0) { cat=true; Toast.makeText(parent.getContext(), "You selected: " + c[position], Toast.LENGTH_LONG).show(); } else cat = false; if (cat) go.setEnabled(true); else go.setEnabled(false); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); go.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cont(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement switch(id) { case R.id.myprofile: Toast.makeText(getApplication(),"My Profile",Toast.LENGTH_SHORT).show(); myProfile(); break; case R.id.signout: Toast.makeText(getApplication(),"Sign Out",Toast.LENGTH_SHORT).show(); signout(); break; case R.id.about: Toast.makeText(getApplication(),"About",Toast.LENGTH_SHORT).show(); Intent i=new Intent(Welcome.this,AboutActivity.class); startActivity(i); break; case R.id.contact: Toast.makeText(getApplication(),"Contact Us",Toast.LENGTH_SHORT).show(); contact(); break; case R.id.exit: Toast.makeText(getApplication(),"Exit",Toast.LENGTH_SHORT).show(); exit(); break; } return super.onOptionsItemSelected(item); } public void myProfile() { Intent i=new Intent(Welcome.this,ProfileActivity.class); startActivity(i); } public void signout() { AlertDialog.Builder b=new AlertDialog.Builder(this); b.setMessage("") .setCancelable(false) .setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent j=new Intent(Welcome.this,MainActivity.class); MainActivity.currentuser=""; startActivity(j); finish(); } }); AlertDialog a= b.create(); a.setTitle("Are you sure you want to sign out?"); a.show(); } public void exit() { AlertDialog.Builder b=new AlertDialog.Builder(this); b.setMessage("Do you want to exit?") .setCancelable(false) .setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); AlertDialog a= b.create(); a.setTitle("Confirm exit"); a.show(); } public void contact() { AlertDialog.Builder b=new AlertDialog.Builder(this); b.setMessage("here we can give our number/email or\nopen an activity providing our details.") .setCancelable(true) .setNegativeButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog a= b.create(); a.setTitle("Contact Us"); a.show(); } public void onBackPressed() { exit(); } public void loadCategory() { ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, c); // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner category.setAdapter(dataAdapter); } public void cont() { AlertDialog.Builder b=new AlertDialog.Builder(this); b.setMessage("Once started, you'll have only "+timelimit+" seconds to complete your quiz.") .setCancelable(false) .setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(), "Can't connect right now.", Toast.LENGTH_LONG).show(); } }); AlertDialog a= b.create(); a.setTitle("Start the quiz?"); a.show(); } } <file_sep>package com.example.vaibhav.project1; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; public class DatabaseHandler extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "LoginUser"; private static final String TABLE_NAME = "user"; private static final String NAME = "Name"; private static final String USERNAME = "Username"; private static final String PASS = "<PASSWORD>"; private static final String ACTIVE = "Active"; private static final String TOTAL_QUIZ = "Total Quiz"; private static final String TOTAL_SCORE = "Total Score"; private static final String AVG_SCORE = "Average Score"; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Creating Tables @Override public void onCreate(SQLiteDatabase db) { // Category table create query String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME +"(" +NAME + " TEXT, " +USERNAME + " TEXT PRIMARY KEY, " +PASS + " TEXT, " +ACTIVE +" TEXT, " +TOTAL_QUIZ +" NUMBER, " +TOTAL_SCORE +" NUMBER, " +AVG_SCORE +" NUMBER)"; Log.d("Table creating : ",CREATE_ITEM_TABLE); db.execSQL(CREATE_ITEM_TABLE); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // Create tables again onCreate(db); } public int register(String nm,String unm,String pwd) { Log.d("REGISTERING ",unm); SQLiteDatabase db = this.getWritableDatabase(); String query="SELECT * FROM "+TABLE_NAME+" WHERE "+USERNAME+"='"+unm+"'"; Cursor c=db.rawQuery(query,null); try { if (c.moveToFirst()) { c.close(); db.close(); return 0; } }catch(SQLException e) { return 2; } ContentValues values = new ContentValues(); values.put(NAME, nm); values.put(USERNAME,unm); values.put(PASS, pwd); values.put(ACTIVE, "N"); values.put(TOTAL_QUIZ, 0); values.put(TOTAL_SCORE, 0); values.put(AVG_SCORE, 0); db.insert(TABLE_NAME,null,values); db.close(); Log.d("REGISTERED SUCCESSFULLY",unm); UserDetails.TABLE_NAME=unm; return 1; } public boolean verify(String unm, String p) { Log.d("VERIFYING ",unm); SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM " + TABLE_NAME + " WHERE "+USERNAME+"='" + unm + "' AND "+PASS+"='" + p + "'"; Cursor c = db.rawQuery(query, null); try { if (c.moveToFirst()) { //db.execSQL("UPDATE "+TABLE_NAME+" SET "+ACTIVE+" = 'Y' WHERE "+USERNAME+" = "+unm); ContentValues values = new ContentValues(); values.put(ACTIVE, "Y"); db.update(TABLE_NAME,values," USERNAME = ?",new String[]{unm}); c.close(); db.close(); Log.d("VERIFIED ",unm); return true; } } catch (SQLException e) { return false; } return false; } public String activeUser() { SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM " + TABLE_NAME + " WHERE "+ACTIVE+"='Y'"; Cursor c = db.rawQuery(query, null); try { if (c.moveToFirst()) { c.close(); db.close(); Log.d("Active user : ",c.getString(2)); return c.getString(2); } else return ""; } catch (SQLException e) { return ""; } } }
17070303da82da910ad3dcda5eb1e50ae5fc46b9
[ "Java" ]
2
Java
vaibhavkedia968/Project1
5f8286d7237f6800be8b13b2b9f35a357e9c4ec5
a87f4c532022c1101072e82c77ecfe0a38c54d7b
refs/heads/master
<repo_name>jlxy-117/117admin<file_sep>/maintain.php <?php require_once './function.php'; header( 'Access-Control-Allow-Origin:*' ); // 获取信息信息列表 $json = do_get_request("http://localhost:9092/cityLines"); $list = json_decode($json, true); ?> <!DOCTYPE html> <html> <head> <title>路线维护</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="back-stage management."> <link rel="stylesheet" href="css/main1.css"> <link rel="stylesheet" href="css/maintain.css"> <script type="text/javascript" src="plugin/easyui/jquery.min.js"></script> <script type="text/javascript" src="js/getCity.js"></script><!--确定城市--> </head> <body class="html"> <div id="wrapper"> <div id="maincontent"> <!-- 选择城市,添加路线等--> <table style=" font-size:17px; text-align:right;width:100%;" border="0"> <tr> <td id="td1"style="width: 40%;"></td> <!-- 选择城市额二级联动--> <td id="td1"style="width: 35%;"><FORM METHOD=POST ACTION="" name="form2"> <SELECT id = "select"NAME="province" onChange="getCity()"> <OPTION VALUE="0">江苏</OPTION> </SELECT> <SELECT id = "select" NAME="city"> <OPTION VALUE="0">南京&nbsp;&nbsp;</OPTION> </SELECT> </FORM> </td> </tr> </table> <!-- 表格数据部分--> <table id = "oTable"style=" text-align:center; font-size:14px;width: 100%;" border="0"> <thead> <tr bgColor=#f3ffd7> <td style="width: 10%;">路线编号</td> <td style="width: 10%;">路线名</td> <td style="width: 8%;">全程(km)</td> <td style="width: 27%;">途经</td> <td style="width: 8%;">站点数</td> <td>编辑站点</td> </tr> </thead> <tbody> <?php $line_no = 0; foreach ($list as $item) { $line_no++; echo ' <tr> <td>' . $item['id'] . '</td> <td>' . $item['line_name'] . '</td> <td>' . $item['distance'] . '</td> <td>' . $item['start_to_end'] . '</td> <td>' . $item['station_number'] . '</td> <td> <a href="#" style="color:red" onclick="station_edit(' . $line_no. ')">查看</a> </td> </tr>'; } ?> </tbody> </table> <script> function station_edit(no) { window.location.href = "line"+no+".php"; } </script> </div> </div> </body> </html> <file_sep>/home.php <?php header( 'Access-Control-Allow-Origin:*' ); require_once './function.php'; $res = do_get_request("http://localhost:9091/CheckAdminLogin"); ?> <html> <head> <title>后台管理</title> <meta charset="utf-8"> </head> <!-- 第一次上下划分! --> <frameset rows="70px,*"border=7 bordercolor=#f5f5f9> <frame name="top" src="top.php" noresize scrolling="none"> <!-- 第二次划分! --> <frameset cols="18%,*"border=12> <frame name="menu" src="menu.php" noresize scrolling="none"> <frame name="main" src="main.php"> </frameset> </frameset> </html><file_sep>/js/getCity.js //定义了城市的二维数组,里面的顺序跟省份的顺序是相同的。通过selectedIndex获得省份的下标值来得到相应的城市数组 var city=[ ["南京","苏州","南通","常州"], ["北京","天津","上海","重庆"], ["福州","福安","龙岩","南平"], ["广州","潮阳","潮州","澄海"], ["兰州","白银","定西","敦煌"] ]; function getCity(){ //获得省份下拉框的对象 var sltProvince=document.form2.province; //获得城市下拉框的对象 var sltCity=document.form2.city; //得到对应省份的城市数组 var provinceCity=city[sltProvince.selectedIndex - 1]; //清空城市下拉框,仅留提示选项 // sltCity.length=1; //将城市数组中的值填充到城市下拉框中 for(var i=0;i<provinceCity.length;i++){ sltCity[i+1]=new Option(provinceCity[i],provinceCity[i]); } }<file_sep>/login.php <?php header('Access-Control-Allow-Origin:*'); require_once './function.php'; ?> <html> <head> <title>欢迎登陆</title> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="css/structure.css" > <script type="text/javascript" src="js/jquery.min.js" ></script> </head> <body> <div id="login"> <h2>欢迎登陆</h2> <form id="login_form" method="post"> <fieldset> <p><label for="usename">用户名</label></p> <p><input type="text" id="username" name="username" onBlur="if(this.value=='')$('#error').html('请输入用户名')" onFocus="this.value='';$('#error').html('')"/></p> <p><label for="password">密码</label></p> <p><input type="password" id="password" name="password" onBlur="if(this.value=='')$('#error').html('请输入密码');" onFocus="this.value=''"/></p> <p><input id="sub_btn" type="button" value="登陆" /><label id="error"></label></p> </fieldset> </form> </div> <script type="text/javascript"> $(function(){ $("#username")[0].focus(); $("#sub_btn").click(function(){ var username = $("#username").val(); var password = $("#password").val(); if (""==(username)||""==(password)) { return false; } else { $.post( "http://localhost:9091/Adminlogin", { _method:"get", id:username, password:<PASSWORD> }, function (data) { if(String(data)=="fail") alert("用户名或密码错误"); else window.location.href = "http://localhost:8088/Admin/home.php"; }, "text"); } return true; }); }); </script> </body> </html><file_sep>/js/checkDelete.js function $(objId) { //objId为table的ID return document.getElementById(objId); } function del_tbl(tableId, ckeckName) { //tblN为table的ID var ck = document.getElementsByName(ckeckName); //CKN为checkbox的name var tab = $(tableId); var rowIndex; for (var i = 0; i < ck.length; i++) { if (ck[i].checked) { rowIndex = ck[i].parentNode.parentNode.sectionRowIndex; tab.deleteRow(rowIndex); i = -1; } } } //全选触发的函数 function checkAll(form) { //length-2是因为复选框中有一个全选,还有一个反选 for (var i = 0; i < form.elements.length - 2; i++) { form.elements[i].checked = true; } } //反选触发的函数 function checkReverse(form) { //length-2是因为复选框中有一个全选,还有一个反选 for (var i = 0; i < form.elements.length - 2; i++) { form.elements[i].checked = (form.elements[i].checked == true) ? false : true; //三元运算 //或者form.elements[i].checked == true ? form.elements[i].checked = false : form.elements[i].checked = true; } }<file_sep>/js/deletCurrentRow.js function deleteCurrentRow(obj) { var tr = obj.parentNode.parentNode; var tbody = tr.parentNode; tbody.removeChild(tr); //只剩行首时删除表格 // if (tbody.rows.length == 1) { // tbody.parentNode.removeChild(tbody); // } }<file_sep>/js/addSite.js function addRow(){ var oTable = document.getElementById("list"); var tBodies = oTable.tBodies; var tbody = tBodies[0]; var tr = tbody.insertRow(tbody.rows.length); var td_1 = tr.insertCell(0); td_1.innerHTML = "<div contenteditable='true'></div>"; var td_2 = tr.insertCell(1); td_2.innerHTML = "<div contenteditable='true'>编号</div>"; var td_3 = tr.insertCell(2); td_3.innerHTML = "<div contenteditable='true'>站名</div>"; var td_4 = tr.insertCell(3); td_4.innerHTML = "<div contenteditable='true'>下一站距离(km)</div>"; var td_5 = tr.insertCell(4); td_5.innerHTML = "<div contenteditable='true'>首发正</div>"; var td_6 = tr.insertCell(5); td_6.innerHTML = "<div contenteditable='true'>首发反</div>"; var td_7 = tr.insertCell(6); td_7.innerHTML = "<div contenteditable='true'>末发正</div>"; var td_8 = tr.insertCell(7); td_8.innerHTML = "<div contenteditable='true'>末发反</div>"; var td_9 = tr.insertCell(8); td_9.innerHTML = "<div>删除</div>"; }<file_sep>/discount.php <?php header("Access-Control-Allow-Origin:*"); ?> <!DOCTYPE html> <html> <head> <title>折扣设置</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="back-stage management."> <link rel="stylesheet" href="css/main1.css"> <link rel="stylesheet" href="css/discount.css"> <script type="text/javascript" src="js/jquery.min.js" ></script> <script> function stuDiscount() { var discount = $("#stu_discount").val() $.post( "http://localhost:9092/discountStu", { _method:"post", city_id:"025", discount:discount }, function (data) { alert("修改成功"); window.location.reload(); }, "text") } function oldDiscount() { var discount = $("#old_discount").val() $.post( "http://localhost:9092/discountElder", { _method:"post", city_id:"025", discount:discount }, function (data) { alert("修改成功"); window.location.reload(); }, "text") } function nolDiscount() { var discount = $("#nol_discount").val() $.post( "http://localhost:9092/discountUser", { _method:"post", city_id:"025", discount:discount }, function (data) { alert("修改成功"); window.location.reload(); }, "text") } </script> </head> <body class="html"> <div id="wrapper"> <div id="maincontent"> <!--表格外的框架--> <table id="table" > <tr> <td id ="user">学生</td> <td id ="user">老人</td> <td id ="user">普通用户</td> </tr> <tr> <td id="td2"> <div id="container"> <!-- 学生折扣设置--> <table id="list" style=" font-size:14px;width: 100%;" border="0"> <form name="myform" method="post"> <tr id="tr"> <td style="width:15%;"><input id = "search" type="button" name="submit" value="+" class="left" onclick="addRow();" /></td> <td style="width: 60%; font-weight: bold;"> 折扣设置 </td> <td style=" font-weight: bold;"></td> </tr> <tr id="tr"> <td ></td> <td > <div contenteditable="true"><input id="stu_discount" type="text" value="0.5"/></div> </td> <td ><a href="#" onclick='stuDiscount()'>确认</a></td> </tr> </form> </table> </div> </td> <!-- 老人折扣设置--> <td id="td2"><div id="container"> <table id="list2" style=" font-size:14px;width: 100%;" border="0"> <form name="myform" method="post"> <tr id="tr"> <td style="width:15%;"><input id = "search" type="button" name="submit" value="+" class="left" onclick="addRow2();" /></td> <td style="width: 60%; font-weight: bold;"> 折扣设置 </td> <td style=" font-weight: bold;"></td> </tr> <tr id="tr"> <td ></td> <td > <div contenteditable="true"><input id="old_discount" type="text" value="0.5"/></div> </td> <td ><a href="#" onclick='oldDiscount()'>确认</a></td> </tr> </form> </table> </div></td> <!-- 普通用户--> <td id="td2"><div id="container"> <table id="list3" style=" font-size:14px;width: 100%;" border="0"> <form name="myform" method="post"> <tr id="tr"> <td style="width:15%;"><input id = "search" type="button" name="submit" value="+" class="left" onclick="addRow3();" /></td> <td style="width: 60%; font-weight: bold;"> 折扣设置 </td> <td style=" font-weight: bold;"></td> </tr> <tr id="tr"> <td ></td> <td > <div contenteditable="true"><input id = "nol_discount" type="text" value="1.0"/></div> </td> <td ><a href="#" onclick='nolDiscount()'>确认</a></td> </tr> </form> </table> </div></td> </tr> </table> </div> </div> </body> </html> <file_sep>/main.php <?php ?> <html> <head> <title>后台管理系统</title> <meta charset="utf-8"> </head> <body> <div style="font-size: 50px;text-align: center;margin-top:20%">您好,欢迎使用后台管理系统</div> </body> </html> <file_sep>/js/deleteUser.js function user_remove(phone_number) { $.post( "http://localhost:9092/DeleteUser/"+phone_number, { _method:"delete", phone_number:phone_number }, function () { window.location.reload(); }, "text"); }<file_sep>/top.php <?php header("Access-Control-Allow-Origin:*"); ?> <html> <head> <title>top顶部页面</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="plugin/easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="plugin/easyui/themes/icon.css"> <script type="text/javascript" src="plugin/easyui/jquery.min.js"></script> <script type="text/javascript" src="plugin/easyui/jquery.easyui.min.js"></script> <style> #logo { margin: 0 0 0 12px; padding: 0; border: 0; width: 200px; height: 70px; text-align: center; color: #ffffff; margin-left:4%; font: 45px Verdana, Arial, Helvetica, sans-serif; background-color: #9acf73; } .info{ position:static; width:260px; float:right; margin-top:30px; font: 15px sans-serif; color:#ffffff; } .info a{ font-size:15px; color:#666; text-decoration:none; font-weight:bold; } .info a span{ display:inline-block; width:60px; height:26px; line-height:26px; background:url("img/shutdown.png") no-repeat; padding-left:26px; } .info a:hover{ color:seagreen; } .time{ float:right; width:200px; margin-top:45px; font-size:14px; font-weight:bold; color:#666; } </style> </head> <body style="background: #9acf73;overflow: hidden;"> <div class="info"> <span>管理界面</span> <a href="javascript:;"><span>退出</span></a> </div> <span id="logo">LOGO</span> </body> </html><file_sep>/register.php <!--<?php header( 'Access-Control-Allow-Origin:*' ); require_once './function.php'; ?>--> <!DOCTYPE html> <html> <head> <title>优惠办理</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="back-stage management."> <link rel="stylesheet" href="css/main1.css"> <link rel="stylesheet" href="css/register.css"> <script type="text/javascript" src="js/jquery.min.js" ></script> <script> $(function(){ $("#sub_btn").click(function(){ var type = $("input[name='type']:checked").val(); var phone = $("#phone").val(); var password = $("#<PASSWORD>").val(); var repassword = $("#rePassword").val(); var cash = $("#recharge").val(); var name = $("#name").val(); if(""==phone){ alert("手机号不能为空"); return; } else if(phone.length>11) { alert("请输入正确的手机号"); return; } else if(""==password){ alert("密码不能为空"); return; } else if(""==name){ alert("名称不能为空"); return; } else if(password != repassword){ alert("确认密码与密码不符") return; } $.post( "http://localhost:9092/addSpUser", { _method:"post", phone:phone, password:<PASSWORD>, name:name, type:type, cash:cash }, function (data) { if(String(data)=="Existed") alert("用户名已存在"); else{ alert("注册成功"); window.location.href="http://localhost:8088/Admin/register.php" } }, "text"); }); }); </script> </head> <body class="html"> <div id="wrapper"> <div id="maincontent"> <!--表格外的框架--> <table style=" text-align:left; font-size:17px;width:100%; text-align:right;" border="0"> <br> <tr> <td id="td1">手机号</td> <td id="td2"><input class="input" id="phone" type="text" /></td> <td id="td3"></td> </tr> <tr> <td id="td1">身份证号</td> <td id="td2"><input class="input" name="ID" type="text" /></td> <td id="td3"></td> </tr> <tr> <td id="td1">密码</td> <td id="td2"><input class="input" id="password" type="text" /></td> <td id="td3"></td> </tr> <tr> <td id="td1">确认密码</td> <td id="td2"><input class="input" id="rePassword" type="text" /> </td> </tr> <tr> <td id="td1">名称</td> <td id="td2"><input class="input" id="name" type="text" /> </td> </tr> <tr> <td id="td1">充值</td> <td id="td2"><input class="input" value="0" id="recharge" type="text" /> </td> </tr> <tr> <td id="td1">类型</td> <td id="td2"> <input type="radio" name="type" value="student" checked>学生 <input type="radio" name="type" value="old">老人 <input type="radio" name="type" value="free">免票 </td> </tr> <tr> <td id="td1"></td> <td id="td2" style="text-align:center;"><input class="zhuce" type="button" id="sub_btn" value="注 册" class="left" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> </tr> </table> </div> </div> </body> </html> <file_sep>/menu.php <!--<?php header( 'Access-Control-Allow-Origin:*' ); require_once './function.php'; ?>--> <html> <head> <title>menu.html菜单页面</title> <meta charset="utf-8"> <style> #menu { height: 50px; width: 100%; margin-bottom: 10px; background-color:#528c3b; text-align: center; } .m1font { color: #ffffff; font: 25px sans-serif; } </style> </head> <body style="background: #9acf73;overflow: hidden;"> <!-- 声明菜单项 target转向!! --> <a href="adUser.php" target="main"style="text-decoration: none;"> <div id="menu"> <span class="m1font"> <hr> 用户管理 </span> </div> </a> <a href="maintain.php"target="main"style="text-decoration: none;"> <div id="menu"> <span class="m1font"> <hr> 路线维护 </span> </div> </a> <a href="register.php"target="main"style="text-decoration: none;"> <div id="menu"> <span class="m1font"> <hr> 优惠办理 </span> </div> </a> <a href="discount.php"target="main"style="text-decoration: none;"> <div id="menu"> <span class="m1font"> <hr> 折扣设置 </span> </div> </a> </body> </html><file_sep>/line3.php <?php header( 'Access-Control-Allow-Origin:*' ); require_once './function.php'; // 获取信息信息列表 $json = do_get_request("http://localhost:9092/stations?city=025&line=03"); $list = json_decode($json, true); ?> <!DOCTYPE html> <html> <head> <title>一号线</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="back-stage management."> <link rel="stylesheet" href="css/main1.css"> <link rel="stylesheet" href="css/maintain.css"> </head> <body class="html"> <div id="wrapper"> <div id="maincontent"> <!-- 选择城市,添加路线等--> <table style=" font-size:17px; text-align:right;width: 100%;" border="0"> <tr> <td id="td1" style="width:35%;"> </td> <!-- 选择城市额二级联动--> <td id="td1" style="width: 30%;"> <FORM METHOD=POST ACTION="" name="form2"> <SELECT id="select" NAME="province" onChange="getCity()"> <OPTION VALUE="0">江苏</OPTION> </SELECT> <SELECT id="select" NAME="city"> <OPTION VALUE="0">南京&nbsp;&nbsp;</OPTION> </SELECT> </FORM> </td> <!-- 返回--> <td style="width: 10%;"> <a href="maintain.php"> <input id="search" type="button" name="btn1" value="返回"> </a> </td> </tr> </table> <!-- 表格数据部分--> <form name="myform" method="post"> <table id="list" style=" text-align:center; font-size:14px;width: 100%;" border="0"> <thead> <tr bgColor=#f3ffd7> <td style="width: 12%;">编号</td> <td style="width: 20%;">站名</td> <td style="width:12%;">首发时间正</td> <td style="width:12%;">首发时间反</td> <td style="width:12%;">末发时间正</td> <td style="width:12%;">末发时间反</td> </tr> </thead> <tbody> <?php foreach ($list as $item) { echo ' <tr> <td>' . $item['id'] . '</td> <td>' . $item['station_name'] . '</td> <td>' . $item['station_begin'] . '</td> <td>' . $item['station_last'] . '</td> <td>' . $item['reverse_station_begin'] . '</td> <td>' . $item['reverse_station_last'] . '</td> </tr>'; } ?> </tbody> </table> <div syle="position:fixed;"> </div> </form> </div> <div> </div> </div> </body> </html>
5b229269c38a0fef38fcefea3ace1eb28758edbe
[ "JavaScript", "PHP" ]
14
PHP
jlxy-117/117admin
ea0a4b70961597c9b67c0dcfd90e2118b3cecc16
01abcc3ac05c713ba966549b34a7500aa2b4ba45
refs/heads/master
<repo_name>Tehtehteh/codewars<file_sep>/client.py import socket import threading def sendmsg(s): while 1: data = input() s.send(bytes(data, encoding='utf-8')) def updates(s): while 1: dataBack = s.recv(1024) if dataBack: print('%s:' % (dataBack,)) def main(): s = socket.socket() s.connect(('127.0.0.1', 8888)) while 1: <<<<<<< HEAD data = input() s.sendall(bytes(data, encoding='utf-8')) ======= threading._start_new_thread(sendmsg, (s,)) >>>>>>> f7ba475ad225548053724d793b766a9fae668c3c threading._start_new_thread(updates, (s,)) if __name__=='__main__': main()<file_sep>/square.py from math import sqrt def find_square(num,y=1): if num // y == y or y == num : return y else: find_square(num,y+1) print(find_square(16))<file_sep>/arraydiff.py def array_diff(a, b): for x in b: try: while a.index(x)>=0: a.remove(x) except: pass return a print(array_diff([1,2], [1]))<file_sep>/qeq.py ver1 = '2.3-8' ver2 = '2.21-7' ver3 = '12.1-0' def cmpV(ver1, ver2): f1 = ver1.split('.') f2 = ver2.split('.') f11 = f1[1].split('-') f22 = f2[1].split('-') print(f1,f2,f11,f22) if int(f1[0]) > int(f2[0]): return True elif int(f1[0]) > int(f2[0]): return False else: g = list(zip(f11, f22)) if g[0][0] > g[0][1]: return True elif g[0][0] < g[0][1]: return False else: if g[1][0] > g[1][1]: return True elif g[1][0] < g[1][1]: return False print(cmpV(ver2,ver1)) #g = list(zip(ver1.split('.')[1].split('-'), ver2.split('.')[1].split('-'))) #print(g) #print(g[0][0] > g[0][1]) <file_sep>/server.py import socket import threading host, port = '', 8888 socketList = [] def sockupdt(client, address): def update(socketList, add): while True: for conn in socketList: req = conn.recv(1024) conn.sendall(req) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(10) print('Serving on %s %s' % (host, port)) while True: cc, ca = s.accept() socketList.append(cc) threading._start_new_thread(update, (socketList, ca)) #cc.close() # import logging # from tornado.ioloop import IOLoop # from tornado import gen # from tornado.iostream import StreamClosedError # from tornado.tcpserver import TCPServer # from tornado.options import options, define # define("port", default=8888, help="TCP port to listen on") # logger = logging.getLogger(__name__) # # # class EchoServer(TCPServer): # @gen.coroutine # def handle_stream(self, stream, address): # while True: # try: # data = yield stream.read_until(b"\n") # logger.info("Received bytes: %s", data, ' from address ', address[0]) # if not data.endswith(b"\n"): # data = data + b"\n" # yield stream.write(data) # except StreamClosedError: # logger.warning("Lost client at host %s", address[0]) # break # except Exception as e: # print(e) # # # if __name__ == "__main__": # options.parse_command_line() # server = EchoServer() # server.listen(options.port) # logger.info("Listening on TCP port %d", options.port) # IOLoop.current().start()<file_sep>/echoserver.py import tornado.netutil import tornado.tcpserver import tornado.ioloop class EchoServer(tornado.tcpserver.TCPServer): def handle_stream(self, stream, address): self.read_chunk_size() <file_sep>/xos.py def getRows(m): for x in m: if ''.join(y for y in x) == 'XXX': yield 'x' elif ''.join(y for y in x) == 'OOO': yield 'o' else: yield 'd' def getColumns(m): for x in zip(*m): if ''.join(y for y in x) == 'XXX': yield 'x' elif ''.join(y for y in x) == 'OOO': yield 'o' else: yield 'd' def getDig(m): if ''.join(m[i][i] for i in range(3)) == 'XXX' or ''.join(m[i][i-3+i] for i in range(3)) == 'XXX': yield 'x' elif ''.join(m[i][i] for i in range(3)) == 'OOO'or ''.join(m[i][i-3+i] for i in range(3)) == 'OOO': yield 'o' else: yield 'd' m = [ "X.O", "XX.", "XOO"] def main(m): g = [] for x in m: (*a,) = x g.extend([a]) ans = [] ans.extend(x for x in getRows(g)) ans.extend(x for x in getColumns(g)) ans.extend(x for x in getDig(g)) return next(filter(lambda x: x!='d', ans)) if list(filter(lambda x: x!='d', ans)) else 'd' print(main(m))<file_sep>/app.py import tornado.web import tornado.ioloop class MainHandler(tornado.web.RequestHandler): def get(self): items = ['qeq', 'da', 'deb'] self.render('qeq.html', title='Hello world', items=items, error=tornado.web.HTTPError(302)) def post(self): print(self.get_arguments(name='age')) self.write('Nice arguments, bitch.') app = tornado.web.Application([ (r'/', MainHandler), ]) class ContactHandler(tornado.web.RequestHandler): def post(self): print(self.get_arguments()) self.write('Nice arguments, bitch.') app.listen(8888) tornado.ioloop.IOLoop.instance().start() <file_sep>/tower.py def tower_builder(n_floors): res = [] for i in range(n_floors, 0, -1): floor = ' ' * (i//2) + '*' * (n_floors-i+1) + ' ' * (i//2) print(floor) res.append(floor) return res print(tower_builder(3))<file_sep>/iqtest.py def iq_test(numbers): Odd = list(filter(lambda x: x%2==0, map(int, numbers.split()))) Even = list(filter(lambda x: x%2==1, map(int, numbers.split()))) if len(Odd)>len(Even): return list(map(int, numbers.split())).index(Even[0])+1 else: return list(map(int, numbers.split())).index(Odd[0])+1 print(iq_test("1 2 2"))<file_sep>/Desc_order.py def Descending_Order(num): g = [] retN = '' for x in str(num): g.append(x) if len(g) == 1: return int(g[0]) for x in reversed(g): retN += x return int(retN) <file_sep>/Lambdas.py spoken = lambda greeting: greeting[0].upper() + greeting[1:] + '.'#? shouted = lambda greeting: greeting.upper() + '!'#? whispered = lambda greeting: greeting.lower() + '.'#? # greet = lambda style, msg: style(msg) #? print(greet(spoken,'Hello')) class mylist(list): def __init__(self, *args): super().__init__(*args) def __call__(self, *args, **kwargs): return 'qeq' f = mylist([1,2,3]) print(help(super))<file_sep>/accum.py def accum(s): s1 = '' for i,x in enumerate(s): s1 = s1 + x.upper()*1+ (x.lower()*i) s1+='-' return s1[:-1] print(accum('ZpglnRxqenU')) <file_sep>/rever_str.py def reverse(str): if not str: return '' else: return reverse(str[1:])+str[0:1] print(reverse('qeqoos')) print('sooqa'[1:] + 'sooqa'[0:1])<file_sep>/polind.py MIN = 100 MAX=1000 lstr = str def is_pol(num): if lstr(num)==lstr(num)[::-1]: return True else: return False def pol(): mx = 0 for i in range(MAX-1, MIN, -1): for j in range(MAX-1, i-1, -1): ml = i*j if ml>mx and is_pol(ml): mx = ml return mx print(pol())<file_sep>/isPrime.py from math import sqrt, ceil def is_prime(num): for i in range(2,ceil(sqrt(num))): if num % i == 0: print(i) return False return True print(is_prime(19))<file_sep>/largeDig.py def solution(digits): nums = list(map(int, NumR(digits))) print(max(nums)) return 0 def NumR(digits): if len(digits)==5: yield digits return yield digits[:5] yield from NumR(digits[1:]) solution('176531330624919225119674426574742355349194934969835')<file_sep>/dupencode.py from collections import Counter def duplicate_encode(word): g = Counter(word.lower()) res = '' for x in word.lower(): if g.get(x) > 1: res = res + ')' else: res = res + '(' return res print(duplicate_encode('Success')) # # Test.assert_equals(duplicate_encode("din"),"(((") # Test.assert_equals(duplicate_encode("recede"),"()()()") # Test.assert_equals(duplicate_encode("Success"),")())())","should ignore case") # Test.assert_equals(duplicate_encode("(( @"),"))((")<file_sep>/scrumble.py from collections import Counter def scramble(s1,s2): return set(Counter(s2)).issubset(set(Counter(s1))) # Test.assert_equals(scramble('rkqodlw','world'),True) # Test.assert_equals(scramble('cedewaraaossoqqyt','codewars'),True) # Test.assert_equals(scramble('katas','steak'),False) # Test.assert_equals(scramble('scriptjava','javascript'),True) # Test.assert_equals(scramble('scriptingjava','javascript'),True)<file_sep>/node.py class Node(object): def __init__(self, data=None, next=None): self.data = data self.next = next def push(self, data): self.next = Node(data, None) def build_one_two_three(): f = Node(None) f.push(1) f.push(2) f.push(3) return f print(build_one_two_three().next) <file_sep>/cmo.py import sys def main(): verbose = False try: user = sys.argv[1] try: verbose = True if sys.argv[2] else False except IndexError: pass except IndexError: user = 'root' print(user, verbose) main() <file_sep>/toCC.py def to_camel_case(text): pass <file_sep>/revWords.py def reverse_words(str): return ''.join(x[::-1] for x in str.split(' ')) data3 = [0,0,1,1,0,1,1,0,0,0,1,0,1,0,0,1] def getBytes(str): print(reverse_words('This is an example!'))<file_sep>/my-serv.py import socket import threading def update(s, data, clients): while True: for client in clients: s.sendall(data) client.close() def main(): host, port = ('', 8888) clients = set() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(10) print('Serving @ ', host, port) #s.setblocking(0) while True: con, client = s.accept() clients.add(client) data = s.recv(1024) print('Received data {} from {}'.format(data, client)) threading._start_new_thread(update, (s, data, clients)) main()<file_sep>/assign.py def main(): prices = { 'Canada': { 'Alberta': lambda x: x * 2, 'Ontario': lambda x: x * 3, 'Default': lambda x: x * 4 }, 'Usa': lambda x: x } choice = input('Your country?\n').title() if choice not in prices: print('Wrong destination country.') return else: price = int(input('Value?\n')) if choice == 'Canada': state = input('Which state?\n') print('Total price is ', prices[choice][state](price)) else: print('Total price is ', prices[choice](price)) if __name__ == '__main__': main() <file_sep>/longest_consec.py def longest_consec(strarr, k): if k <= 0 or not strarr: return '' m = [x for x in createL(strarr, k)] print(m) return yieldMaxStr(m) def createL(strarr, k): res = '' if k > len(strarr): return else: for i in range(k): res += strarr[i] yield res yield from createL(strarr[1:], k) def yieldMaxStr(strarr): max = 0 maxi = 0 for i,x in enumerate(strarr): if len(x) > max: max = len(x) maxi = i if maxi > len(strarr) or max==0: return '' return strarr[maxi] input() m = [x for x in createL(["zone", "abigail", "theta", "form", "libe", "zas"], 2)] print(longest_consec(["zone", "abigail", "theta", "form", "libe", "zas"], -2))<file_sep>/sol.py """ solution('abc') # should return ['ab', 'c_'] solution('abcdef') # should return ['ab', 'cd', 'ef'] """ def ys(s): if len(s) == 0: return '' elif len(s) == 2 or len(s) == 1: yield s + '_'*(2-len(s)) return yield s[:2] yield from ys(s[2:]) def solution(s): return list(ys(s)) print(solution('abcde'))
3e30b049117ee4ef8a8c0903f46b117962c3f794
[ "Python" ]
27
Python
Tehtehteh/codewars
d915f10076400388c606be6508a6559707cf7c60
ad3640cf264a47630b3fdca0e9911715b1d577c8
refs/heads/master
<file_sep>'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Project metadata pkg: grunt.file.readJSON('package.json'), ghPagesDir: '../nerdshow@gh-pages', ghRuntimeDir: '<%= ghPagesDir %>/rt/<%= pkg.version %>', jshint: { all: [ 'Gruntfile.js', // client 'lib/server/htdocs/s5/ui/common/s5.js', 'lib/server/htdocs/rc/remote.js', // server 'lib/server.js', 'lib/generator/*.js' ], options: { jshintrc: '.jshintrc' } }, run: { "generate-examples-about": { args: [ 'bin/nerdshow-generate', 'examples/about/presentation.json' ] }, "generate-gh-pages-about": { args: [ 'bin/nerdshow-generate', 'examples/about/presentation.json', '--nerdshow-folder', 'rt/<%= pkg.version %>', '--no-socketio-enabled', '--no-zoom-enabled' ] } }, copy: { "gh-pages": { files: [ { // runtime expand: true, cwd: 'lib/server/htdocs', src: ['**'], dest: '<%= ghRuntimeDir %>/' }, { // examples expand: true, cwd: 'examples/about', src: ['**', '!*.md', '!20-*.html'], dest: '<%= ghPagesDir %>/' } ] } }, clean: { "gh-pages-runtime": { options: { force: true }, src: ['<%= ghRuntimeDir %>'] } } }); // Load npm plugins to provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-run'); // Default tasks to be run. grunt.registerTask('default', ['jshint']); grunt.registerTask('gh-pages', [ 'clean:gh-pages-runtime', 'run:generate-gh-pages-about', 'copy:gh-pages', 'run:generate-examples-about' ]); };
a201a1a928216b7d03a1d13c32cb1d9c960baa53
[ "JavaScript" ]
1
JavaScript
Biranchi-narayan/nerdshow
92a6a37b341a49b00ca55f515d7599e9d838f1e8
8c3fbb1025525482bc148de98c4c5c8d98a72a42
refs/heads/master
<repo_name>icyflame/create-together-rails<file_sep>/README.md # Create Together [![Build Status](https://travis-ci.org/icyflame/create-together-rails.svg?branch=master)](https://travis-ci.org/icyflame/create-together-rails) ### Caters to the control freak inside you A custom blogging framework. Post moderation are first rate citizens in this project. Built to be used by the Students' Alumni Cell, IIT Kharagpur. Code is licensed under MIT. Copyright 2015 <NAME>. <file_sep>/app/controllers/administrators_controller.rb class AdministratorsController < ApplicationController def index @administrators = Administrator.all end def show @administrator = Administrator.find(params[:id]) end def verify_token # render plain: params.inspect if params[:verificationstring] == current_administrator.verification_string @administrator = current_administrator @administrator.update(verified: true) flash[:alert] = "You have been validated as an administrator." else flash[:alert] = "You entered the wrong verfication token." end redirect_to posts_path end def verify end def moderate_content if administrator_signed_in? if current_administrator.verified temp = Post.find(params[:post]) temp.moderated = !temp.moderated temp.save redirect_to temp end end end end <file_sep>/app/controllers/posts_controller.rb class PostsController < ApplicationController def index if params[:contributor_id] @posts = Post.all.order(created_at: :desc).where("contributor_id = ?", params[:contributor_id]) else @posts = Post.all.order(created_at: :desc) end end def create @contributor = Contributor.find(params[:contributor_id]) if @post = @contributor.posts.create(post_params) redirect_to post_path(@post) else render 'new' end # @post = Post.new(post_params) # render plain: params[:post].inspect end def new if contributor_signed_in? @contributor = current_contributor else flash[:alert] = "You need to be signed in as a contributor to add new posts." redirect_to new_contributor_session_path end end def edit end def show @post = Post.find(params[:id]) @contributor = Contributor.find(@post.contributor_id) # if params[:contributor_id] # render plain: "Contributor ID is defined." # else # render plain: "Contributor ID is not defined" # end end def update end def destroy end private def post_params params.require(:post).permit(:title, :content, :tags) end end <file_sep>/app/models/post.rb class Post < ActiveRecord::Base belongs_to :contributor validates :title, presence: true, length: { minimum: 5 } validates :content, presence: true, length: { minimum: 20 } end <file_sep>/test/models/administrator_test.rb require 'test_helper' class AdministratorTest < ActiveSupport::TestCase # test "Sample AdministratorTest" do # admin = Administrator.new # assert_not admin.save, "Save administrator without the name" # end # test "the truth" do # assert true # end end <file_sep>/app/controllers/contributors_controller.rb class ContributorsController < ApplicationController def index @contributors = Contributor.all end def show @contributor = Contributor.find(params[:id]) end end <file_sep>/test/controllers/contributors_controller_test.rb require 'test_helper' class ContributorsControllerTest < ActionController::TestCase # test "should get index" do # get :index # assert_response :success # end # test "should get create" do # contributor = contributors(:one) # # get :create, {:contributor => {:name => contributor.name, :email => contributor.email }} # get :create, {:contributor => contributor.attributes} # assert_response :success # end # test "should get new" do # get :new # assert_response :success # end # test "should get edit" do # get :edit # assert_response :success # end # test "should get show" do # contributor = contributors(:one) # get :show, {:id => contributor.id} # assert_response :success # end # test "should get update" do # get :update # assert_response :success # end # test "should get destroy" do # get :destroy # assert_response :success # end end
bf312c99c4060d3422dbe065ac6560b1182b21b5
[ "Markdown", "Ruby" ]
7
Markdown
icyflame/create-together-rails
5d8ade05f1557fb4004b72364ce2f38cb50c34b2
92cc0ab7e3cadb62d106d775ecab5555e31136f2
refs/heads/master
<repo_name>louisquach/supermemory<file_sep>/src/components/mainContent/LearnContent/Learn_content.jsx import React from 'react' import './learn_content.scss' import Card from '../../Card/card'; import Number from '../../Number/number'; import {connect} from 'react-redux' const LearnContent = ({num,key,display}) => { console.log(num); return ( <div className="learn__container" style={{display: `${display}`}}> <div className='learn__container-num'> { num != null ? num.map( n => <Card num={n} key={key}/>) : null } </div> <Number/> </div> ) } const mapStateToProps = state => ({ num: state.number[0].num, key: state.number[0].id, display: state.display.learn }) export default connect(mapStateToProps)(LearnContent);<file_sep>/src/components/Card/FronFace/CardFront.jsx import React from 'react' import './CardFront.scss' const FrontCard = ({num}) => { return ( <div className='frontCard__container'> <h1 className='frontCard_detail'>{num}</h1> </div> ) } export default FrontCard;<file_sep>/src/components/Number/number.jsx import React from 'react' import './number.scss' import {connect} from 'react-redux' import {Learn1, Learn2, Learn3, Learn4, Learn5, Learn6,Learn7,Learn8,Learn9,Learn10} from '../../redux/learnNumber/learnReducer' const Number = ({learn1,learn2,learn3,learn4,learn5,learn6,learn7,learn8,learn9,learn10}) => { return ( <div className="number__container"> <div onClick={learn1} className="number__num"><span className='number'>1</span></div> <div onClick={learn2} className="number__num"><span className='number'>2</span></div> <div onClick={learn3} className="number__num"><span className='number'>3</span></div> <div onClick={learn4} className="number__num"><span className='number'>4</span></div> <div onClick={learn5} className="number__num"><span className='number'>5</span></div> <div onClick={learn6} className="number__num"><span className='number'>6</span></div> <div onClick={learn7} className="number__num"><span className='number'>7</span></div> <div onClick={learn8} className="number__num"><span className='number'>8</span></div> <div onClick={learn9} className="number__num"><span className='number'>9</span></div> <div onClick={learn10} className="number__num"><span className='number'>10</span></div> </div> ) } const mapDispatchToProps = dispatch => ({ learn1: () => dispatch(Learn1()), learn2: () => dispatch(Learn2()), learn3: () => dispatch(Learn3()), learn4: () => dispatch(Learn4()), learn5: () => dispatch(Learn5()), learn6: () => dispatch(Learn6()), learn7: () => dispatch(Learn7()), learn8: () => dispatch(Learn8()), learn9: () => dispatch(Learn9()), learn10: () => dispatch(Learn10()), }) export default connect(null,mapDispatchToProps)(Number);<file_sep>/src/components/Signin-signup/signIn_signUp_component.jsx import React from 'react'; import Input from "../Input/input"; import './signIn_signUp_component.scss' import Button from '../button/sign_btn'; import { googleSignIn, auth, createUserProfile} from '../../firebase/firebaseConfig'; export const SignInForm = () => { const [signIn, setSignIn] = React.useState({ displayName: '', email: '' }) const handleChange = (event) => { const {name, value} = event.target; setSignIn(prev => ({...prev,[name]:value})) } const handleSubmit = async event => { event.preventDefault(); const {email, password} = signIn; try { await auth.signInWithEmailAndPassword(email, password); setSignIn({ displayName: '', email: '' }) } catch (error) {console.log(error); alert("There is a problem with sign in, please try again!")} } return ( <div className="signIn"> <h1 className="signIn__form">Sign In</h1> <h4 className="signin__form-h4">Already have account?</h4> <form className="signInForm" onSubmit={handleSubmit}> <Input name="email" type="email" placeholder="Your email" onChange={handleChange}/> <Input name="password" type="<PASSWORD>" placeholder="<PASSWORD>" onChange={handleChange}/> <div className="form__btn"> <Button name="Sign In" type='submit'/> <Button name="Google Sign In" onClick={googleSignIn} type="button"/> </div> </form> </div> ) } export const SignUpForm = () => { const [newUser, setNewUser] = React.useState({ displayName: '', email: '', password:'', confirmPassword:'' }) const handleSubmit = async event => { event.preventDefault(); const {displayName, email, password, confirmPassword} = newUser; if (password !== confirmPassword) { alert("Password does not match, please try again!"); return;} try { const {user} = await auth.createUserWithEmailAndPassword(email,password); await createUserProfile(user, {displayName}); setNewUser({ displayName: '', email: '', password: '', confirmPassword: '' }); } catch(err) {console.log(err);} } const handleChange = (event) => { const {value, name} = event.target; setNewUser(pre => ({...pre,[name]: value})); } return ( <div className="signUp"> <h1 className="signUp__form">Sign Up</h1> <h4 className="signin__form-h4">Don't have account?</h4> <form className="signUpForm" onSubmit={handleSubmit}> <Input name="displayName" type="text" onChange={handleChange} placeholder="Your full name"/> <Input name="email" type="email" placeholder="Your email" onChange={handleChange}/> <Input name="password" type="<PASSWORD>" placeholder="<PASSWORD>" onChange={handleChange}/> <Input name="confirmPassword" type="<PASSWORD>" placeholder="<PASSWORD>" onChange={handleChange}/> <div className="form__btn"> <Button name="Sign Up" type="submit"/> </div> </form> </div> ) }<file_sep>/src/App.js import React from 'react'; import SignInSignUp from './pages/signin_signup-page/SignInSignUp_page'; import {Switch, Route, Redirect} from 'react-router-dom'; import HomePage from './pages/homepage/homepage'; import { auth, createUserProfile } from './firebase/firebaseConfig'; import { catchUser } from './redux/user/userReducer'; import {connect} from 'react-redux'; function App(props) { const [detectUser, setDetectUser] = React.useState(null); const {catchUser, checkUser} = props React.useEffect( () => { setDetectUser( () => {auth.onAuthStateChanged( async userAuth => { if (userAuth) { const userRef = await createUserProfile(userAuth); userRef.onSnapshot( snapshot => { catchUser({ id: snapshot.id, ...snapshot.data() }) }) } catchUser(userAuth); }); }); setDetectUser(); },[]) return ( <div> <Switch> <Route exact path='/' component={HomePage}/> <Route exact path="/signin" render={ () => checkUser ? <Redirect to='/'/> : <SignInSignUp/>}/> </Switch> </div> ); } const dispatchStateToProps = dispatch => ({ catchUser: user => dispatch(catchUser(user)) }) const mapStateToProps = state => ({ checkUser: state.user.currentUser }) export default connect(mapStateToProps,dispatchStateToProps)(App); <file_sep>/src/redux/user/userReducer.js export const catchUser = user => ({ type: 'CATCH_A_USER', payload: user }); const INITIAL_USER = { currentUser: null } const userReducer = (state = INITIAL_USER, catchUser) => { switch (catchUser.type) { case 'CATCH_A_USER': return ({...state, currentUser: catchUser.payload }); default: return state; } } export default userReducer;<file_sep>/src/redux/rootReducer.js import {combineReducers} from 'redux' import {ToggleReducer} from './toggle/toggleReducer' import userReducer from './user/userReducer'; import learnReducer from './learnNumber/learnReducer'; import DisplayReducer from './displayScreen/screenReducer'; const rootReducer = combineReducers({ hidden: ToggleReducer, user : userReducer, number: learnReducer, display: DisplayReducer }); export default rootReducer; <file_sep>/src/redux/displayScreen/screenReducer.js const INITIAL_STATE = { learn: 'none', test: 'none', blog: 'none' } export const DisplayLearn = action => ({ type: "LEARN" }) export const DisplayTest = action => ({ type: "TEST" }) export const DisplayBlog = action => ({ type: "BLOG" }) const DisplayReducer = (state = INITIAL_STATE, action) => { switch (action.type) { case 'LEARN': return {learn: 'flex', test:'none', blog:'none'}; case 'TEST': return {learn: 'none', test:'flex', blog:'none'}; case 'BLOG': return {learn: 'none', test:'none', blog:'flex'}; default: return state; } } export default DisplayReducer;<file_sep>/src/components/mainContent/TestContent/test.jsx import React from 'react' import './test.scss' import {connect} from 'react-redux' import {TestCard} from '../../Card/BackFace/CardBack' const TestContent = ({display}) => { const [ranNum,setRanNum] = React.useState({display: 'none', num:[{num:null},{num:null},{num:null},{num:null},{num:null}], correctAnswer:''}) const [result,setResult] = React.useState({result:null}) const [title,setTitle] = React.useState({title:''}) const [startProps, setStartProps] = React.useState({ animate:'turnaround ease-in-out 1s infinite', top:'10rem', display: {startBtn: 'flex',startAgain:'none'}}); function setRandomnumber() { const num1 = Math.floor(Math.random()*100) + 1; const num2 = Math.floor(Math.random()*100) + 1; const num3 = Math.floor(Math.random()*100) + 1; const num4 = Math.floor(Math.random()*100) + 1; const num5 = Math.floor(Math.random()*100) + 1; const correctAnswer = String(num1) + String(num2) +String(num3)+String(num4)+String(num5) console.log(correctAnswer); setRanNum({display:'flex',num:[{id:1,num:num1},{id:2,num:num2},{id:3,num:num3},{id:4,num:num4},{id:5,num:num5}],correctAnswer: correctAnswer}); } function handleStartButton() { setStartProps({animate:'none',top:'auto',display:{startBtn:'none',startAgain:'flex'}}); setRandomnumber() } const handleChange = (e) => { const answer = e.target.value; setResult({result: answer}); } const handleSubmit = e => { e.preventDefault() console.log(result); var title = '' if (String(result.result) == String(ranNum.correctAnswer)) { title = "Answer is correct!"; } else { title = "Answer is wrong!"; } setTitle({title: title}) } return ( <div className='test__container' style={{display: `${display}`}}> <div className='test__container-card'> { ranNum ? ranNum.num.map( n => <div className='test__container-backCard' style={{display: `${ranNum.display}`}}> <TestCard num={n.num} key={n.id} style={{display:`${ranNum.display}`}}/> </div> ): null } </div> <div className='test__container-form'> <div className='test__container-start' style={{animation: startProps.animate, top: startProps.top,display:startProps.display.startBtn}}> <button className='test__form-btn start' onClick={handleStartButton}>Start</button> </div> <h2 className='test__result' style={ title.title === "Answer is correct!" ? {color: 'green'}: {color: 'red'}}>{title.title}</h2> <button onClick={setRandomnumber} className='test__form-btn' style={{display:startProps.display.startAgain}}>Play</button> <div className='test__form'> <input className='test__form-input' name='result' onChange={handleChange}/> <button className='test__form-btn' onClick={handleSubmit}>Submit</button> </div> </div> </div> ) } const mapStateToProps = state => ({ display: state.display.test }) export default connect(mapStateToProps)(TestContent);<file_sep>/src/components/Input/input.jsx import React from 'react'; import "./input.scss" const Input = (props) => { const {name, placeholder, onChange, type,...otherprops} = props; return ( <div className="input__container"> <label>{placeholder}</label> <input onChange={onChange} type={type} className='input__container-input' name={name} {...otherprops} placeholder={placeholder} required/> </div> ) } export default Input;<file_sep>/src/redux/toggle/toggleReducer.js const INITIAL_STATE = { hidden: false } const toggleAction = () => ({type: "TOGGLE_CHANGE"}); export const ToggleReducer = (state = INITIAL_STATE, toggleAction) => { switch (toggleAction.type) { case "TOGGLE_CHANGE": return ({...state, hidden: !state.hidden}) default: return state; } } export default toggleAction;<file_sep>/src/components/footer/footer.jsx import React from 'react'; import './footer.scss' const Footer = () => { return ( <div className='footer_container'> <h5 className='footer_container-content'> <span className='copyright'>&copy;</span> 2020 <span className='footer-name'><NAME></span>. All right reserved. </h5> </div> ) } export default Footer;<file_sep>/src/pages/homepage/homepage.jsx import React from 'react' import './homepage.scss' import NavBar from '../../components/navbar/navbar' import Footer from '../../components/footer/footer' import SideBar from '../../components/SideBar/sidebar' import MainContent from '../../components/mainContent/mainContent' const HomePage = () => { return ( <div className='homepage__container'> <NavBar/> <SideBar/> <MainContent/> <Footer/> </div> ) } export default HomePage;<file_sep>/src/components/SideBar/sidebar.jsx import React from 'react' import './signbar.scss' import SideBarItem from './sidebarItems/sidebarItem'; import { DisplayLearn, DisplayTest, DisplayBlog } from '../../redux/displayScreen/screenReducer' import {connect} from 'react-redux' import { Learn0 } from '../../redux/learnNumber/learnReducer'; const SideBar = ({learn,test,blog,changeScreen}) => { return ( <div className="sidebar__container"> <SideBarItem onClick={learn} name="learn"/> <SideBarItem onClick={test} name="test"/> <SideBarItem onClick={blog} name="blog"/> </div> ) } const mapDispatchToProps = dispatch => { return () => ({ learn: () => dispatch(DisplayLearn()), test: () => dispatch(DisplayTest()), blog: () => dispatch(DisplayBlog()) }) } export default connect(null, mapDispatchToProps)(SideBar);<file_sep>/src/pages/signin_signup-page/SignInSignUp_page.jsx import React from 'react'; import "./SignInSignUp_page.scss" import {SignInForm, SignUpForm} from '../../components/Signin-signup/signIn_signUp_component' const SignInSignUp = () => { return ( <div className="sign_container"> <SignInForm/> <SignUpForm/> </div> ) } export default SignInSignUp;<file_sep>/src/firebase/firebaseConfig.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseConfig = { apiKey: "<KEY>", authDomain: "memory-training-d882f.firebaseapp.com", databaseURL: "https://memory-training-d882f.firebaseio.com", projectId: "memory-training-d882f", storageBucket: "memory-training-d882f.appspot.com", messagingSenderId: "918290049455", appId: "1:918290049455:web:64197bea9143b5023ae75a", measurementId: "G-ME5QRZ6R6W" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); console.log(firebase.app().name); export const auth = firebase.auth() export const firestore = firebase.firestore() const provider = new firebase.auth.GoogleAuthProvider(); provider.setCustomParameters({ promt: 'select_account'}); export const createUserProfile = async (userAuth) => { if (!userAuth) return; const userProfile = firestore.doc(`users/${userAuth.uid}`); const snapshot = userProfile.get(); console.log(snapshot); if (!(await snapshot).exists) { const {displayName, email} = userAuth; const createAt = new Date(); try { await userProfile.set({ displayName, email, createAt }) } catch(err) {console.log('There is an error', err.message);} } return userProfile; }; export const googleSignIn = () => auth.signInWithPopup(provider); export const googleSignOut = () => auth.signOut().then( () => console.log("user has signed out!")).catch( err => console.log(err)) export default firebase; <file_sep>/src/components/Card/BackFace/CardBack.jsx import React from 'react' import './CardBack.scss' const BackCard = ({num}) => { return ( <div className='backCard__container'> <img className="card_image" src={process.env.PUBLIC_URL + `/images/${num}.jpg`} alt="number item"/> </div> ) } export const TestCard = ({num,key,display}) => { return ( <div className='backCard__container-test' key={key} style={{display: `${display}`}}> <img className="card_image" src={process.env.PUBLIC_URL + `/images/${num}.jpg`} alt="number item"/> </div> ) } export default BackCard; <file_sep>/src/components/navbar/navbar_hidden/hiddenNav.jsx import React from 'react' import './hiddenNav.scss' import { googleSignOut } from '../../../firebase/firebaseConfig'; import {Link} from 'react-router-dom' import {connect} from 'react-redux' import toggleAction from '../../../redux/toggle/toggleReducer'; const ToggleNav = ({hidden, dispatchToggle, currentUser}) => { const handleSignOut = () => { googleSignOut(); dispatchToggle(); } return ( <div className='navbar_detail' style={hidden ? {width: "auto"}: null}> { currentUser ? <div className='navbar_detail-signOut' onClick={handleSignOut}><h4>Sign Out</h4></div> :<div className='navbar_detail-signIn' onClick={dispatchToggle}><Link to="/signin"><h4>Sign In</h4></Link></div> } </div> ) } const dispatchStateTopProps = dispatch => ({ dispatchToggle: () => dispatch(toggleAction()) }) const mapStateToProps = state => ({ currentUser: state.user.currentUser }) export default connect(mapStateToProps, dispatchStateTopProps)(ToggleNav);<file_sep>/src/components/button/sign_btn.jsx import React from 'react' import './sign_btn.scss' const Button = ({name, type, onClick}) => { return ( <div className="sign__btn"> <button onClick={onClick} className='sign__btn-button' type={type}>{name}</button> </div> ) } export default Button;
78a9b2eda0419a85eb64e41e2b5d308f121c10bc
[ "JavaScript" ]
19
JavaScript
louisquach/supermemory
7c66aab797ae665828c07ba96d701a0a1c9ebccb
cf718d4eb2b7f4309fc147acc48cbbc66773fe4f
refs/heads/master
<repo_name>aktug/react-visjs-graph2d<file_sep>/example/src/VisGraph2dContainer.js import React, { Component } from "react" import moment from "moment" //import VisGraph2d from "react-visjs-graph2d" import VisGraph2d from "./build" const example_one = { options: { height: "380px", }, items: [ { x: moment(), y: 30, group: 0 }, { x: moment().add(1, "days"), y: 10, group: 0 }, { x: moment(), y: 15, group: 1 }, { x: moment().add(1, "days"), y: 30, group: 1 }, { x: moment().add(2, "days"), y: 10, group: 1 }, { x: moment().add(3, "days"), y: 15, group: 1 }, ], customTimes: { customTime1: moment().add(-1, "days"), customTime2: moment().add(4, "days"), }, groups: [ { id: 1, content: "Group0", options: { drawPoints: { style: "circle", }, shaded: { orientation: "bottom", }, }, }, { id: 0, content: "Group1", options: { style: "bar", }, }, ], } const example_two = { options: { height: "380px", }, items: [ { x: moment().add(-5, "days"), y: 13, group: 0 }, { x: moment().add(-4, "days"), y: 12, group: 0 }, { x: moment().add(-3, "days"), y: 11, group: 0 }, { x: moment().add(-2, "days"), y: 10, group: 0 }, { x: moment().add(-1, "days"), y: 9, group: 0 }, { x: moment(), y: 8, group: 0 }, { x: moment().add(1, "days"), y: 9, group: 0 }, { x: moment().add(2, "days"), y: 10, group: 0 }, { x: moment().add(3, "days"), y: 11, group: 0 }, { x: moment().add(4, "days"), y: 12, group: 0 }, { x: moment().add(5, "days"), y: 13, group: 0 }, ], customTimes: { customTime1: moment().add(-6, "days"), customTime2: moment().add(6, "days"), }, groups: [ { id: 0, content: "Group1", options: { style: "bar", }, }, ], } class VisGraph2dContainer extends Component { log = e => console.log(e) render() { return ( <> <VisGraph2d {...example_one} onClick={e => this.log(e)} /> <VisGraph2d {...example_two} onRangechange={e => this.log(e)} onContextmenu={e => this.log(e)} /> </> ) } } export default VisGraph2dContainer <file_sep>/README.md # React Vis.js Graph2d #### React component for the vis.js graph2d module [Vis.js Graph2d Docs](http://visjs.org/docs/graph2d/) ### Installation ```bash yarn add react-visjs-graph2d ``` ![screenshot](https://github.com/aktug/react-visjs-graph2d/blob/master/public/ss.png?raw=true) <file_sep>/src/index.js import vis from "vis/dist/vis-timeline-graph2d.min" import "vis/dist/vis-timeline-graph2d.min.css" import React, { Component } from "react" import PropTypes from "prop-types" import difference from "lodash/difference" import intersection from "lodash/intersection" import each from "lodash/each" import assign from "lodash/assign" import noop from "lodash/noop" import keys from "lodash/keys" const ucFirst = str => str.charAt(0).toUpperCase() + str.slice(1) const events = [ "currenttimetick", "click", "contextmenu", "doubleclick", "changed", "rangechange", "rangechanged", "timechange", "timechanged", ] const eventPropTypes = {} const eventDefaultProps = {} each(events, event => { eventPropTypes[event] = PropTypes.func eventDefaultProps[`on${ucFirst(event)}`] = noop }) export default class VisGraph2d extends Component { constructor(props) { super(props) this.state = { customTimes: [], } } componentDidMount() { const { container } = this.refs this.$el = new vis.Graph2d(container, undefined, this.props.options) this.$el.on("rangechange", () => this.$el.redraw()) events.forEach(event => this.$el.on(event, this.props[`on${ucFirst(event)}`])) this.init() } componentDidUpdate() { this.init() } shouldComponentUpdate(nextProps) { const { items, groups, options, customTimes } = this.props const itemsChange = items !== nextProps.items const groupsChange = groups !== nextProps.groups const optionsChange = options !== nextProps.options const customTimesChange = customTimes !== nextProps.customTimes return itemsChange || groupsChange || optionsChange || customTimesChange } init() { const { items, groups, options, customTimes, currentTime } = this.props let timelineOptions = options this.$el.setOptions(timelineOptions) if (groups.length > 0) { const groupsDataset = new vis.DataSet() groupsDataset.add(groups) this.$el.setGroups(groupsDataset) } this.$el.setItems(items) if (currentTime) { this.$el.setCurrentTime(currentTime) } const customTimeKeysPrev = keys(this.state.customTimes) const customTimeKeysNew = keys(customTimes) const customTimeKeysToAdd = difference( customTimeKeysNew, customTimeKeysPrev ) const customTimeKeysToRemove = difference( customTimeKeysPrev, customTimeKeysNew ) const customTimeKeysToUpdate = intersection( customTimeKeysPrev, customTimeKeysNew ) each(customTimeKeysToRemove, id => this.$el.removeCustomTime(id)) each(customTimeKeysToAdd, id => this.$el.addCustomTime(customTimes[id], id)) each(customTimeKeysToUpdate, id => this.$el.setCustomTime(customTimes[id], id)) this.setState({ customTimes }) } render() { return <div ref="container" /> } componentWillUnmount() { this.$el.destroy() } } VisGraph2d.propTypes = assign( { items: PropTypes.array, groups: PropTypes.array, options: PropTypes.object, customTimes: PropTypes.shape({ datetime: PropTypes.instanceOf(Date), id: PropTypes.string, }), currentTime: PropTypes.oneOfType([ PropTypes.string, PropTypes.instanceOf(Date), PropTypes.number, ]), }, eventPropTypes ) VisGraph2d.defaultProps = assign( { options: {}, items: [], groups: [], customTimes: {}, }, eventDefaultProps )
1c5ba83e1f3b595a3653ab03fc220436236b674b
[ "JavaScript", "Markdown" ]
3
JavaScript
aktug/react-visjs-graph2d
e9c5a26296191f62db783c206e4a974e7a586491
a2377924c4246e33f8a611bf707e8da02eedc37d
refs/heads/master
<file_sep><!DOCTYPE html> <?php $json = file_get_contents('proj.json'); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> <NAME>'s site </title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="jquery-3.1.1.min.js"></script> <script src="velocity.min.js"></script> <style> @font-face { font-family: 'Kraftstoff'; src: url("Kraftstoff-Regular.otf"); } * { color: white; font-size: 22px; font-family: 'Kraftstoff' !important; } #infotitletext { font-size: 32px; } body { margin: 0; border: 0; padding: 0; background-color: rgb(43, 42, 40); } .popup { position: fixed; } canvas { position: absolute; width: 100%; height: 100%; } .popuptext { position: absolute; top: 0px; left: 0px; } #pretext { top:0px; left:0px; height: 20%; } .text { position: absolute; top: 0%; left:6%; width: 94%; height: 100%; overflow-y: scroll; overflow-x: hidden; } .head { width: 100%; height: 20%; left:0px; top: 0px; } .info { width: 80%; height: 75%; bottom: 0px; left: 0px; } .close { height: 19%; bottom: 0px; right: 0px; } .head{ top:-20%; } .info{ bottom:-75%; left:-80%; } .close{ bottom:-19%; right:-100%; } img#gitlogo { position: absolute; } a#gitredirect { position: absolute; top: 55px; right: 130px; display: none; } img#viewmore { position: absolute; bottom: 15%; right: 10%; width: 60%; display: none; } #title{ position: absolute; left:1%; top: 3%; font-size: 50px ; } #clock { position: absolute; font-size: 50px; top: 42%; right: 15%; } .icon { position: absolute; width: 53px; height: 53px; stroke-width: 0; stroke: white; fill: white; bottom: 10px; right: 10px; } #infotitle { position: absolute; top: 17%; left: 5%; height: 30%; overflow-y: hidden; } .infotext { position: absolute; left: 5%; width: 100%; height: 100%; } #infoRedirect { position: absolute; left: 5%; bottom: 3%; width: 80%; } .infoarea { position: absolute; width: 80%; height: 37%; top: 46%; overflow-y: auto; overflow-x: hidden; } div#stopbg { position: absolute; width: 100%; height: 100%; top: 0px; left: 0px; display: none; } @media (max-width : 750px) { img#viewmore{ display: none; } #title{ position: absolute; left:1%; top: 3%; font-size: 45px ; } #clock { position: absolute; font-size: 45px; top: 42%; right: 15%; } </style> </head> <body> <div class="text"> <div id="pretext"></div> <p> <font id="infofont"> </font></p><p><font id="infofont">Sono <NAME>, un ragazzo a cui piace programmare.</font></p><font id="infofont"> <p>Non tendo spesso a pubblicare i miei progetti, ma da qualche tempo a questa parte ho deciso di iniziare a farlo, <br>tra i progetti pubblicati ci sono codici scolastici e altri creati indipendentemente. </p><p> Tutti i questi sono caricati su GitHub, ma elencati in modo più dettagliato su questo sito</p><br><br> Ecco la lista: <span id="pagetext"></span> <br> Mi potete trovare su github al seguente indirizzo:<br> <a href="https://github.com/domenicopopolizio"><font color="white">https://github.com/domenicopopolizio</font></a><br> <br>E su SoloLearn* al link:<br> <a href="https://www.sololearn.com/Profile/829585"><font color="white">https://www.sololearn.com/Profile/829585</font> </a><br> <br> <br> <br> <p> *I progetti pubblicati su SoloLearn <i>non</i> sono presenti in questo sito, eccetto quelli presenti anche su GitHub.<br>Per vederli visitare il <a href="https://www.sololearn.com/Profile/829585"><font color="white">mio profilo su SoloLearn</font></a>. </p><p> <br> P.S. I miei progetti non finiscono qui, questi sono solo alcuni, <br> ovvero quelli che per un motivo o per l'altro ho voluto pubblicare ;) </p> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> </font> <p></p> </div> <img src="viewmore.png" id="viewmore"> <div class="head popup" style="top: 0px;"> <canvas class="headcanvas" id="headcanvas" width="1024" height="117.796875"> </canvas> <div class="headtext popuptext" id="title"> Domenico Popolizio's Site </div> <div id="clock"></div> </div> <div id="stopbg"></div> <div class="info popup" style="bottom: -353.4px; left: -730.837px;"> <canvas class="canvas" id="infocanvas" width="819.1875" height="441.75"> </canvas> <div id="infotitle"><font ><p>Risolutore di fisica</p></font></div> <div class="infotext popuptext" id="infotext"> </div> <div id="infoRedirect"><a href="https://domenicopopolizio.github.io/fisicautomatica/">Clicca qui per vedere la pagina!</a></div> <a href="https://github.com/domenicopopolizio/domenicopopolizio.github.io" id="git"><img src="gitlogo.png" id="gitlogo" style="position: absolute; top: 22.175px; right: 22.175px; width: 60px;"></a> <a href="https://github.com/domenicopopolizio/domenicopopolizio.github.io" id="gitredirect"> Guarda su github</a> </div> <div class="close popup" style="bottom: -19%; right: -111.906%; width: 111.906px;"> <canvas id="closecanvas" width="111.90625" height="111.90625"> </canvas> <div id="closeicon"> <svg> <symbol id="icon-close" viewBox="0 0 22 28"> <title> close </title> <path d="M20.281 20.656c0 0.391-0.156 0.781-0.438 1.062l-2.125 2.125c-0.281 0.281-0.672 0.438-1.062 0.438s-0.781-0.156-1.062-0.438l-4.594-4.594-4.594 4.594c-0.281 0.281-0.672 0.438-1.062 0.438s-0.781-0.156-1.062-0.438l-2.125-2.125c-0.281-0.281-0.438-0.672-0.438-1.062s0.156-0.781 0.438-1.062l4.594-4.594-4.594-4.594c-0.281-0.281-0.438-0.672-0.438-1.062s0.156-0.781 0.438-1.062l2.125-2.125c0.281-0.281 0.672-0.438 1.062-0.438s0.781 0.156 1.062 0.438l4.594 4.594 4.594-4.594c0.281-0.281 0.672-0.438 1.062-0.438s0.781 0.156 1.062 0.438l2.125 2.125c0.281 0.281 0.438 0.672 0.438 1.062s-0.156 0.781-0.438 1.062l-4.594 4.594 4.594 4.594c0.281 0.281 0.438 0.672 0.438 1.062z"></path> </symbol> </svg> <svg class="icon icon-close"><use xlink:href="#icon-close"></use></svg> </div> </div> <script> var projects = <?php echo $json; ?>; function compile_list(key) { t = "<li><p>Progetti "+key+":</p><ol>"; for (var i = 0; i < projects[key].length; i++) { t+='<li><p onclick=\"info(projects[\''+key+'\']['+i+']);\"><u>'+projects[key][i].name+'</u></p></li>'; } t += "</ol></li><br>"; return t; } function write_page() { keys = Object.keys(projects); text = '<ul>' for (var i = 0; i < keys.length; i++) { text += compile_list(keys[i]); } text += '</ul>' $("#pagetext").append(text); } function open_info() { $(".info").velocity({ 'bottom':"0px", 'left':"0px", }); $(".close").velocity({ 'bottom':'0px', 'right':'0px', }); $("div#stopbg").css({ 'display':'block', }); } function close_info() { $(".close").velocity({ 'bottom':'-19%', 'right':'-'+$(".close").height()+'%' }); $(".info").velocity( { 'bottom':-(($(window).height()/100)*60)+"px", 'left':-($('.info').width()-($('.info').height()-(($(window).height()/100)*60)))+"px", }, function() { $("#infotext").html(''); $('a#git').attr('href', 'https://github.com/domenicopopolizio/domenicopopolizio.github.io'); } ); $("div#stopbg").css({ 'display':'none', }); } function info(obj) { title = ''; text = ''; textRedirect = ''; title += '<font><p id="infotitletext">'+obj.name+'</p></font>'; text += '<font class="infoarea"><p>'+obj.info+'</p></font>'; text += '<br>'; if (obj.pagina != obj.github) { textRedirect = '<a href="'+obj.pagina+'"><font color="white"><p>Clicca qui per vedere la pagina!<p></font></a>' } else { textRedirect = '<a href="'+obj.pagina+'"><font color="white"><p>Clicca qui per vedere il codice!<p></font></a>' } $('a#git').attr('href', obj.github); $('#infotitle').html(title); $("#infotext").html(text); $('#infoRedirect').html(textRedirect); open_info(); } function updateClock() { d = new Date(); o = d.getHours()+''; if (o.length == 1) { o = '0'+o; } else if (o.length == 0) { o += '00'; } m = d.getMinutes()+''; if (m.length == 1) { m = '0'+m; } else if (o.length == 0) { m += '00'; } ora = o+':'+m; $('#clock').html(ora); requestAnimationFrame(updateClock); } $( function () { write_page(); requestAnimationFrame(updateClock); $(".head").css({ 'top':'-20%', }); $(".info").css({ 'bottom':'-75%', 'left':"-80%", }); $(".close").css({ 'bottom':'-19%', 'right':'-'+$(".close").height()+'%' }); $(".head").velocity({ 'top':'0px', }); $(".info").velocity({ 'bottom':-(($(window).height()/100)*60)+"px", 'left':-($('.info').width()-($('.info').height()-(($(window).height()/100)*60)))+"px", }); /*$(".info").velocity({ 'bottom':'0px', 'left':"0px", }); $(".close").velocity({ 'bottom':'0px', 'right':'0px', });*/ //$(".info").click(open_info); $(".close").click(close_info); var generalFillStyle = 'rgb(0,162,232)';// 'rgb(252, 207, 14)'; var firstAdjust = true; var generalShadow = '#222222'; function adjust() { var w = $(window).width(); var h = $(window).height(); var pw = w/100; var ph = h/100; $(".close").css({"width":$(".close").height()+"px"}); $('#headcanvas').attr("width",$(".head").width()); $('#headcanvas').attr("height",$(".head").height()); var headDOM = document.getElementById('headcanvas'); var head = headDOM.getContext('2d'); pwh = headDOM.width/100; //percenteage width headdom phh = (headDOM.height-8)/100; //percentage height headdom //head.clearRect(0, 0, headDOM.width, headDOM.height); head.fillStyle = generalFillStyle; head.beginPath(); head.moveTo(0, 0); head.lineTo(pwh*0, phh*70); head.lineTo(pwh*85, phh*100-4); head.lineTo(pwh*100, phh*50); head.lineTo(pwh*100, phh*0); head.closePath(); head.shadowColor = generalShadow; head.shadowBlur = 12; head.shadowOffsetX = 0; head.shadowOffsetY = 4; head.fill(); $('#infocanvas').attr("width",$(".info").width()); $('#infocanvas').attr("height",$(".info").height()); var infoDOM = document.getElementById('infocanvas'); var info = infoDOM.getContext('2d'); pwi = infoDOM.width/100; //percenteage width infodom phi = infoDOM.height/100; //percentage height infodom //head.clearRect(0, 0, headDOM.width, headDOM.height); info.fillStyle = generalFillStyle; info.beginPath(); info.moveTo(pwi*0, phi*100); info.lineTo(pwi*0, phi*10); info.lineTo(pwi*100-12, phi*0+12); info.lineTo(pwi*87, phi*100); info.closePath(); info.shadowColor = generalShadow; info.shadowBlur = 12; info.shadowOffsetX = 4; info.shadowOffsetY = -4; info.fill(); $('#closecanvas').attr("width",$(".close").width()); $('#closecanvas').attr("height",$(".close").height()); var closeDOM = document.getElementById('closecanvas'); var close = closeDOM.getContext('2d'); pwc = closeDOM.width/100; //percenteage width closedom phc = closeDOM.height/100; //percentage height closedom //head.clearRect(0, 0, headDOM.width, headDOM.height); close.fillStyle = generalFillStyle; close.beginPath(); close.moveTo(pwc*100, phc*100); close.lineTo(pwc*22, phc*100); close.lineTo(pwc*39, phc*0); close.lineTo(pwc*100, phc*20); close.closePath(); close.shadowColor = generalShadow; close.shadowBlur = 12; close.shadowOffsetX = -4; close.shadowOffsetY = -4; close.fill(); if (!firstAdjust) { $(".close").css( { 'bottom':'-19%', 'right':'-'+$(".close").height()+'%' } ); $(".info").css( { 'bottom':-(($(window).height()/100)*60)+"px", 'left':-($('.info').width()-($('.info').height()-(($(window).height()/100)*60)))+"px", } ); } firstAdjust = false; $('#gitlogo').css( { 'position':'absolute', 'top': (($('.info').width()-($('.info').width()-($('.info').height()-(($(window).height()/100)*60))))-64)/2+10+'px', 'right': (($('.info').width()-($('.info').width()-($('.info').height()-(($(window).height()/100)*60))))-64)/2+12+'px', 'width' :'60px', }); } $(window).resize( function() { adjust(); } ); adjust(); } ); </script> </body></html><file_sep>'use strict'; //costanti const stecWidth = 17.5; const stecHeight = 300; const onSideMargin = 0.125*window.innerWidth; //variabili globali let presi = 0; //rappresenta il numero di stecchini presi dal giocatore let stecchini; let margin; let endAnim = true; //funzioni const randrange = ( min, max ) => Math.floor(Math.random()*max)%(max-min) + min function testoTurno(player) { let testo = ""; switch(player) { case 'p': testo = "È il tuo turno!"; break; case 'c': testo = "È il turno del computer!"; break; } return testo; } function prendiStec(player, stec) { } function rmEventStecchini() { /*https://stackoverflow.com/questions/9251837/how-to-remove-all-listeners-in-an-element*/ let stecchini = document.querySelectorAll(".stecchino"); stecchini.forEach( stecchino => { var newStecchino = stecchino.cloneNode(true); stecchino.parentNode.replaceChild(newStecchino, stecchino); } ); } async function displayBanner() { return new Promise( (resolve, reject) => { let bannerContent = document.querySelector("#banner"); bannerContent.style.left = "0"; bannerContent.style.right = ""; Velocity( bannerContent, { width: "100%" }, { delay: 600, duration: 300, complete: newbanner => { bannerContent.style.left = ""; bannerContent.style.right = "0"; Velocity( bannerContent, { width:"0%" }, { delay: 1500, duration: 300, complete: newbanner => { resolve(); } } ); } } ) } ); } async function computerPrendi(n, i = 0, resolvePrec = () => {}) { return new Promise ( (resolve, reject) => { if( !(i < n) ) { resolve("i<n"); } else { let stecchini = document.querySelectorAll(".stecchino.tavolo"); let inMano = document.querySelectorAll(`.stecchino.computer`).length | 0; let stecchino = stecchini[randrange(0, stecchini.length)]; stecchino.classList.remove("tavolo"); stecchino.classList.add("computer"); Velocity( stecchino, { left : ( (inMano+1) * margin + inMano*stecWidth) + "px", top : `-${stecHeight/2}px`, marginTop: "0px" }, { complete: newStecchino => { computerPrendi(n, ++i).then( resolve ); } } ); } } ); } async function turnoComputer(daPrendere) { document.querySelector("#banner-content").innerHTML = testoTurno('c'); await displayBanner(); document.querySelector("#end").style.display = "none"; return new Promise( async (resolve, reject) => { computerPrendi(daPrendere).then(resolve); } ); } async function turnoPlayer() { presi = 0; document.querySelector("#banner-content").innerHTML = testoTurno('p'); await displayBanner(); document.querySelector("#end").style.display = "flex"; return new Promise( (resolve, reject) => { document.querySelectorAll('.stecchino.tavolo').forEach( (stecchino) => { stecchino.addEventListener( "click", function selStecEv(event) { if(endAnim) { endAnim = false; let stecchino = event.target; let inMano = document.querySelectorAll(`.stecchino.giocatore`).length | 0; presi++ Velocity( stecchino, { left : ( (inMano+1) * margin + inMano*stecWidth) + "px", marginTop: "0px", top: (window.innerHeight-stecHeight/2)+"px" }, { complete: newStecchino => { stecchino.classList.remove("tavolo"); stecchino.classList.add("giocatore"); stecchino.removeEventListener("click", selStecEv); if(presi == 3) { resolve("3Stecchini"); rmEventStecchini(); } endAnim = true; } } ); } } ); } ); document.querySelector("#end").addEventListener( "click", function selStecEv(event) { if(presi > 0 && presi < 3) { resolve("schiacciato bottone"); rmEventStecchini(); } } ); } ); } function turno(player) { switch(player) { case 'p': turnoPlayer(); break; case 'c': turnoComputer(); break; } } function resize(event = 0) { margin = (window.innerWidth - onSideMargin*2 - stecchini.length*stecWidth) / 12; for(let i = 0; i < stecchini.length; i++) { stecchini[i].style.left = ( (i+1) * margin + i*stecWidth + onSideMargin) + "px"; } } async function inizia() { await turnoComputer(2); do { await turnoPlayer(); await turnoComputer(4-presi); } while(document.querySelectorAll(".stecchino.tavolo").length > 1); document.querySelector("#banner-content").innerHTML = "HAI PERSO!"; await displayBanner(); } //main document.addEventListener( "DOMContentLoaded", () => { stecchini = document.querySelectorAll(".stecchino.tavolo"); resize(); window.addEventListener( "resize", resize ); /*setTimeout( inizia, 2000 );*/ let background = new Image(); background.addEventListener("load", inizia); background.src="background.png"; } ) <file_sep>Questo sito aiuta chiunque ne abbia bisogno a fare semplici calcoli per le prove fatte nei laboratori di fisica. <file_sep>**11 stecchini, gioco** Un gioco contro il computer in cui ci sono 11 stecchini, perde chi prende l'ultimo stecchino. E' una pwa, quindi installabile e funzionante offline. <file_sep><?php error_reporting(0); if (isset($_POST["psw"])) { $real_psw = $_POST["psw"]; $psw = hash( "sha512", $_POST["psw"]); } else { $psw = "error"; $real_psw = "error"; } $correct_psw = "601d88357328e7f884605f639a061d79e12e61cabbeea3bae4a57cb8aa664ef1dec7d0299b506748d326c456c61ce801c5326e4937ad8598dd534d877d0134ce"; if ($psw==$correct_psw) { $file="proj.json"; if (isset($_POST["type_to_delete"]) and isset($_POST["n_to_delete"]) ){ if ($_POST["n_to_delete"] == "") { $type = $_POST["type_to_delete"]; $json = file_get_contents($file); $arr = json_decode($json, true); if (array_key_exists ( $type , $arr )) { unset($arr[$type]); $new_json= json_encode($arr); file_put_contents($file, $new_json); } } else if ( $_POST["type_to_delete"] != "" and $_POST["n_to_delete"] != "") { $type = $_POST["type_to_delete"]; $n = ((int) $_POST["n_to_delete"])-1; if ($n >= 0) { $json = file_get_contents($file); $arr = json_decode($json, true); if (array_key_exists ( $type , $arr )) { if (count($arr[$type])>$n) { array_splice( $arr[$type] , $n, 1 ); if( count($arr[$type])==0 ) { unset($arr[$type]); } $new_json= json_encode($arr); file_put_contents($file, $new_json); } } } } } else if(isset($_POST["name"])) { $type=$_POST["type"]??"Altri progetti"; if($type == "") { $type = "Altri progetti"; } $name=$_POST["name"]??""; $info=$_POST["info"]??""; $page=$_POST["page"]??""; $github=$_POST["github"]??""; $json = file_get_contents($file); $arr = json_decode($json, true); $arr[$type][(string)(count($arr[$type])??0)] = array( "name"=>$name, "info"=>$info, "pagina"=>$page, "github"=>$github, ); $new_json= json_encode($arr); if (!($name=="" and $info=="" and $page=="" and $github=="")) { file_put_contents($file, $new_json); } } } ?> <!DOCTYPE html> <html> <head> <title>Admin Area</title> </head> <body> <?php if ($psw == "error"): ?> <form method="post"> Password:<br> <input name="psw" type="Password"/> <br><br> <input type="submit" value="Log in"/> <br><br> </form> <?php elseif ($psw != $correct_psw): ?> <form method="post"> Password:<br> <input name="psw" type="Password"/> <br><br> <input type="submit" value="Log in"/> <br><br> <font color="red">Wrong password!</font> </form> <?php elseif($psw == $correct_psw): ?> <form method="post"> <input style="display: none" name="psw" value="<?php echo $real_psw ?>"/> Project type(ex. html, C, etc):<br> <input style="width: 490px" name="type"> <br><br> Name:<br> <input style="width: 490px" name="name"> <br><br> Info:<br> <textarea style="width: 490px; height:190px;" name="info"></textarea> <br><br> Page:<br> <input style="width: 490px" name="page"> <br><br> Code url (ex. github url):<br> <input style="width: 490px" name="github"> <br><br><br> <input type="submit" value="<NAME>"> </form> <br><br><br><br><br><br> <form method="post"> <input style="display: none" name="psw" value="<?php echo $real_psw ?>"/> <font color="red">Delete</font><br> Project type(ex. html, C, etc):<br> <input style="width: 490px" name="type_to_delete"> <br><br> Number(1 is the first):<br> <input style="width: 490px" name="n_to_delete"> <br><br> <input type="submit" value="ELIMINA"> </form> <?php endif ?> <br> <br> <br> <br> </body> </html> <file_sep>///////////////////////////////COSTANTI PER CACHE////////////////////////////// const cacheName = '11STECCHINI'; const defaultToCache = [ '/11stecchini/', 'index.html', 'background.png', 'index.css', 'index.html', 'index.js', 'logo.png', 'manifest.json', 'materialicon.woff2', 'Roboto-Light.ttf', 'stecchino.png', 'velocity.min.js' ] ///////////////////////////////FUNZIONI/////////////////////////////// const sendToCache = async toCache => { caches.open(cacheName) .then ( cache => cache.addAll(toCache) ) } const serverFetch = request => fetch(request).then( response => response ); const cacheFetch = request => caches.open(cacheName) .then( cache => cache.match(request) .then( response => response || serverFetch(request) ) .catch( error => serverFetch(request) ) ) ///////////////////////////////EVENTI///////////////////////////////// self.addEventListener( 'install', event => { let cacheWhitelist = []; event.waitUntil( sendToCache(defaultToCache) ); } ); self.addEventListener( 'activate', event => {} ); self.addEventListener( 'message', event => { let message = event.data; console.log('Ricevuto messaggio recitante: "'+message+'";'); } ); self.addEventListener( 'fetch', event => event.respondWith( cacheFetch(event.request) ) ); ///////////////////////////////FINE///////////////////////////////////<file_sep>let slide = 0; let slides; const animate = s => slides[s].classList.add("animate"); const leave = s => slides[s].classList.remove("animate"); const tasto = ev => { let d = 0; switch (ev.key) { case "ArrowRight": case "ArrowDown": d = +1; break; case "ArrowLeft": case "ArrowUp": d = -1; break; } if (slide + d < 0 || slide + d >= slides.length) return; leave(slide); slide += d; animate(slide); window.scrollTo({ top: slide * window.innerHeight, behavior: "smooth" }); }; document.addEventListener( 'DOMContentLoaded', () => { const arrows = ["ArrowUp", "ArrowDown", "ArrowRight", "ArrowLeft"]; slides = document.querySelectorAll("section"); document.addEventListener('keyup', tasto); document.addEventListener('keydown', ev => arrows.includes(ev.key) ? ev.preventDefault() : 0); document.addEventListener('wheel', ev => ev.preventDefault()); setTimeout( () => animate(slide), 1000 ); } ); <file_sep># domenicopopolizio.github.io My personal website. ------------------------------------------------------------------------------------------------------ As you can see, the index.html file, contains a redirect to the link where the hompage is hosted (https://domenicopopolizio.000webhostapp.com/), so if you want to read the code of this page you must read the index.php file. ------------------------------------------------------------------------------------------------------- This website include both html and php pages: -All the html file are only hosted on github pages (https://domenicopopolizio.github.io); -All the php file, instead, are hosted on 000webhostapp on the link above ( the same of the index.php page), but all the codes are in this repository! ------------------------------------------------------------------------------------------------------- On the homepage of the site I also link to other project and/or repostory, separated from this one, but all the codes are public on github, and if, in any future project, they are not, I will insert a notice on the website. ------------------------------------------------------------------------------------------------------- p.s. I'm italian, so sorry if my english is not perfect, it isn't my language, however I do my best :) (That's also why in my code the most of the comment/sentences aren't in english, but in italian). <file_sep># simple-carousel It works only with webkit (otherwise it will work but a scrollbar will appear under each carousel) It's not a library, just a code for me that I'll reuse in future, but it could be useful for anyone if they understand how does it work. It's commented by the way, it's not too difficult to understand, I hope. [demo](https://domenicopopolizio.github.io/simple-carousel) <file_sep>// carousel class class Carousel { // it needs the element that should became the carousel itself constructor(elem) { // the element is saved this.element = elem; // list of elements inside the carousel this.content = [...elem.children]; // each one should have an event to select it for (let el of this.content) { el.addEventListener("click", this.select); } // the first one should be selected, so here the event is triggered on the first // element of the current carousel this.select({ target: this.content[0] }); } // current carousel select(ev) { // it works on ev.target and not on this.element because when an event is called, "this" refers to // the caller, not to the current istance of the object // it scrolls the parent of the clicked element (it scrolls the carousel) // in such a way to center the clicked element on the carousel // smoothly ev.target.parentNode.scrollTo({ top: 0, left: ev.target.offsetLeft - ev.target.parentNode.clientWidth / 2 + ev.target.clientWidth / 2, behavior: "smooth" }); // the current selected element of the carousel is not more the current selected element // (It iterate through all the .current element, but it should be just one element) ev.target.parentNode.querySelectorAll(".current").forEach(curr => { curr.classList.remove("current"); }); //and the new current element is the one the user have clicked on ev.target.classList.add("current"); } } // just for the example document.addEventListener("DOMContentLoaded", () => { // let els be the group of div that should became a carousel let els = document.querySelectorAll(".sc-container"); // for each of this div for (let el of els) { // a carousel istance is created new Carousel(el); } });
d5566f10a722b8f822063c437a58e6cf3b362140
[ "JavaScript", "Markdown", "PHP" ]
10
PHP
domenicopopolizio/domenicopopolizio.github.io
1a979e52a471bdbdcbf00a96b770ec8262958298
26606bef061469409f2f3db5f3f7f783b35734fd
refs/heads/master
<file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.objects.TiledMapTileMapObject; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by <NAME> on 2/20/2017. */ public class Wall extends Entity{ int lifeTime; Animation<TextureRegion> animation; float stateTime; boolean needsDeset; boolean removeState; int SETX, SETY; public Wall(float x, float y, Animation<TextureRegion> animation, int lifeTime) { // lifeTime enters as wait time super(x, y); this.animation = animation; removeState = false; stateTime = 0f; this.lifeTime = lifeTime + (int)Gdx.graphics.getDeltaTime(); collisionLayer = (TiledMapTileLayer) Play.getMap().getLayers().get(1); this.sprite = new Sprite(spriteTextures.basic64); removeState = setCollisionLayer(x, y, "blocked"); SETX = (int)(x/ collisionLayer.getTileWidth()); SETY = (int) (y/collisionLayer.getTileHeight()) ; /// Needs to look better with cursor. This looks like a wall and acts correctly. x = SETX * collisionLayer.getTileWidth()-32; y = SETY * collisionLayer.getTileHeight()-32; sprite.setPosition(x, y); } public boolean getCollision(int x1, int y1, int x2, int y2, int x3, int y3){ return COLIDE(x1,y1) && COLIDE(x2,y2) && COLIDE(x3,y3); } private boolean COLIDE(int x1, int y1){ return (SETX+1 == x1 || x1 == (SETX -1) || SETX == x1)&& (y1 == (SETY -1) || SETY == y1); } public int getSETX(){ return SETX; } public int getSETY(){ return SETY; } @Override public void draw(Batch batch) { stateTime += Gdx.graphics.getDeltaTime(); batch.draw((TextureRegion) animation.getKeyFrame(stateTime, true), sprite.getX(), sprite.getY()); if(stateTime > lifeTime){ wallDespawn(); } } public boolean getRemoveState(){return removeState;} public boolean setCollisionLayer(float x, float y, String set){ boolean hasBLOCKED = collisionLayer.getCell((int)((x)/ collisionLayer.getTileWidth()) ,(int)((y)/collisionLayer.getTileHeight())).getTile().getProperties().containsKey("blocked"); if(hasBLOCKED) return true; for(Wall e : Play.getWalls()){ hasBLOCKED = hasBLOCKED ||e.COLIDE(SETX,SETY); if(hasBLOCKED) return true; } //System.out.println("has : " + hasBLOCKED + " @ (" + x + ", " + y +")"); //if(!hasBLOCKED) //collisionLayer.getCell((int)(x/ collisionLayer.getTileWidth()) ,(int)(y/collisionLayer.getTileHeight())).getTile().getProperties().put("blocked","blocked"); return hasBLOCKED; } public void removeBlocked(float x, float y){ collisionLayer.getCell((int)(x/ collisionLayer.getTileWidth()) ,(int)(y/collisionLayer.getTileHeight())).getTile().getProperties().remove("blocked"); } public void wallDespawn(){ Play.getWalls().set(Play.getWalls().indexOf(this, true), null); Play.getWalls().removeIndex(Play.getWalls().indexOf(null, true)); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities; /** * Created by Taylor on 2/19/2017. */ public class pos { float X; float Y; public pos(float x, float y){ X = x; Y = y; } public float getPOSX(){ return X; } public float getPOSY(){ return Y; } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.NullProjectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.WizardOrb; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; /** * Created by chris on 2/12/2017. */ public class NullProjectileItem extends Weapon { public NullProjectileItem(){ sprite = new Sprite(spriteTextures.NullProjectileItemSprite); dmg = 0f; lvl = 0;// type = "projectile"; cooldown = 40; } @Override public Projectile getProjectile(float x1, float y1, float x2, float y2, String Origin){ return new NullProjectile(x1, y1, dmg, this); } } <file_sep>/* Dialog classes used/adapted from patrickhoey's BludBourne Title: BludBourne Author: patrickhoey Source: https://github.com/patrickhoey/BludBourne */ package onion.szxb74om7zsmd2jm.limitlesslabyrinth.mechanics.Dialog; /** * Created by 226864 on 4/18/2017. */ public interface ConversationGraphObserver { public static enum ConversationCommandEvent { EXIT_CONVERSATION, ACCEPT_QUEST, RETURN_QUEST, NONE } void onNotify(final ConversationGraph graph, ConversationCommandEvent event); } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Item; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.Shuriken; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by chris on 2/6/2017. */ public class ShurikenProjectile extends Projectile { String weaponOrigin = "wizardstaff"; public ShurikenProjectile(float x1, float y1, float x2, float y2, float dmg, Item fromItem){ this.fromItem = fromItem; this.dmg = dmg; sprite = new Sprite(spriteTextures.shurikenProjectileTexture); slope = ((y2 - y1)/(x2 - x1)); x = x1; y = y1; b = y1 - slope * x1; endX = x2; endY = y2; theta = Math.atan(slope); if(endX > x){ direction = true; } else{ direction = false; } } public ShurikenProjectile(){ } @Override public void contact() { fromItem.setItemXP(fromItem.getItemXP() + 1); /** Checks for item Level Up */ if(fromItem.getItemXP() >= fromItem.getXPtoLVL()){ fromItem.LVLup(weaponOrigin); fromItem.setXPtoLVL(fromItem.getXPtoLVL() * 2); System.out.println("ITEM LEVELED UP"); } //Play.getProjectiles().add(new Explosion(sprite.getX(), sprite.getY(), dmg)); remove(); } @Override public void draw() { theta = Math.atan(slope); sprite.setPosition(x, y); sprite.draw(Play.getRenderer().getBatch()); sprite.rotate(30); if(direction){ x += Math.cos(theta) * 10; } else{ x -= Math.cos(theta) * 10; } y = slope * x + b; } public void createB(){ b = y - slope * x; } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.Wall; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.pos; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.singleMagicStrike; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by Taylor on 2/19/2017. */ public class Rune extends Weapon { spriteTextures.RUNE rune; boolean [][] EFFECT; pos [][] AOE; pos CENTER; int NUM; public Rune(int level){ rune = spriteTextures.RUNE.WILDGROWTH; setSprite(); setEFFECT(); setNUM(); lvl = level; dmg = 3.3f; basedmg = dmg; for(int i = 0; i < lvl; i++){// dmg += 3.3 * i; } type = "rune"; cooldown = 40; } public void switchRuneType(){ rune = spriteTextures.getRUNETYPE(); setSprite(); setEFFECT(); setNUM(); } @Override public void SWAPVAL(){ switchRuneType(); } private void setSprite(){ sprite = new Sprite(spriteTextures.runeSprite(rune)); } private void setEFFECT() { EFFECT = spriteTextures.getARRAY(rune);} private void setNUM(){ NUM = EFFECT[0].length; AOE = new pos [NUM][NUM]; } private void setAOE(float x, float y){ float left = x + (32 * NUM/2); float top = y + (left - x); for(int i = 0; i < NUM; i++) for(int j = 0; j < NUM; j++) { AOE[i][j] = new pos(left - i * 32, top - j * 32); if(i == (NUM/2) && j == (NUM/2)){ CENTER = AOE[i][j]; } } } private void RUNEBLAST() { for (int i = 0; i < NUM; i++) { for (int j = 0; j < NUM; j++) { if (EFFECT[i][j]) { Play.getProjectiles().add(new singleMagicStrike(AOE[i][j].getPOSX(), AOE[i][j].getPOSY(), dmg * 1.5f, this, 8, spriteTextures.RuneFX(rune))); } } } } @Override public Projectile getProjectile(float x1, float y1, float x2, float y2, String Origin){ if(rune == spriteTextures.RUNE.MAGICWALL){ Play.addWall(new Wall(x2, y2, Play.fourFrameAnimationCreator(spriteTextures.magicwall,1,3,.2f), 30)); } else if(rune == spriteTextures.RUNE.WILDGROWTH){ Play.addWall(new Wall(x2, y2 + 32, Play.fourFrameAnimationCreator(spriteTextures.wildgrowth,1,3,.2f), 30)); } else if(rune != spriteTextures.RUNE.SUDDENDEATH || rune != spriteTextures.RUNE.ICICLE) { setAOE(x2, y2); RUNEBLAST(); return new singleMagicStrike(CENTER.getPOSX(), CENTER.getPOSY(), dmg*1.5f, this, 8, spriteTextures.RuneFX(rune)); } return new singleMagicStrike(x2, y2, dmg*1.5f, this, 8, spriteTextures.RuneFX(rune)); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; /** * Created by chris on 1/31/2017. */ public class NullWeapon extends Weapon { public NullWeapon(){ sprite = new Sprite(spriteTextures.NullProjectileItemSprite); type = "melee"; dmg = 0f; lvl = 0; XPtoLVL = 10; cooldown = 40;// } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.traps; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Item; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.Bow; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.LaserGun; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.NullWeapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.WizardStaff; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by 226812 on 4/18/2017. */ public class EnemyTraps { protected float direction; protected Item projectile; protected long RateOfFire; protected float DetectionRadius; protected float distanceFromPlayer; protected int level; protected float spinRate; protected float x; protected float y; protected long time = 0; public EnemyTraps(float direction, String projectile, long RateOfFire, float DetectionRadius, int level, float spinRate, float x, float y){ this.direction = (float) (direction * (Math.PI/180)); this.RateOfFire = RateOfFire; this.DetectionRadius = DetectionRadius; this.spinRate = (float) (spinRate * (Math.PI/180)); this.x = x * 32; this.y = y * 32 + 13; switch (projectile){ case "arrow": this.projectile = new Bow(level); break; case "wizardorb" : this.projectile = new WizardStaff(level); break; case "laser" : this.projectile = new LaserGun(level); break; default: this.projectile = new Bow(level); } } public void update(){ distanceFromPlayer = Math.abs((float) Math.sqrt(Math.pow((x) - (Play.getPlayer().getSprite().getX() + Play.getPlayer().getSprite().getWidth()/2), 2) + Math.pow((y) - (Play.getPlayer().getSprite().getY() + Play.getPlayer().getSprite().getHeight()/2), 2))); if(System.currentTimeMillis() > time && distanceFromPlayer <= DetectionRadius){ fire(); if(spinRate != 0) direction += spinRate; time = System.currentTimeMillis() + RateOfFire; } } public void fire(){ System.out.println(Math.sin(direction)); float offset = x + (float)(Math.cos(direction) * (180/Math.PI)) == x ? (float) .1 : 0; Play.getEnemyProjectiles().add(projectile.getProjectile(x,y,x + 7 * ((float)(Math.cos(direction) * (180/Math.PI))) + offset,y + 7 * ((float)((Math.sin(direction) * (180/Math.PI)))),"Enemy")); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.Player; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.traps.Trap; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.NullProjectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by chris on 5/15/2017. */ public class regenPotion extends Trap { public regenPotion(int level){ sprite = new Sprite(spriteTextures.RegenPotionSprite); lvl = level; dmg = 1f; basedmg = dmg; for(int i = 0; i < lvl; i++){ dmg += 1 * i; } type = "trap"; cooldown = 40; ammo = 1;// } @Override public Projectile getProjectile(float x1, float y1, float x2, float y2, String Origin){ Player.addRegenRate(); itemXP += lvl; ammo--; if(ammo <= 0){ if(Play.getGui().getSelected() == 0) { Play.getGui().setItem1(new NullWeapon()); Play.getGui().setEquipped(Play.getGui().getItem1()); } else if(Play.getGui().getSelected() == 1) { Play.getGui().setItem2(new NullWeapon()); Play.getGui().setEquipped(Play.getGui().getItem2()); } else if(Play.getGui().getSelected() == 2) { Play.getGui().setItem3(new NullWeapon()); Play.getGui().setEquipped(Play.getGui().getItem3()); } else if(Play.getGui().getSelected() == 3) { Play.getGui().setItem4(new NullWeapon()); Play.getGui().setEquipped(Play.getGui().getItem4()); } } return new NullProjectile(x1,y1,dmg,this); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.Player; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.traps.Trap; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Arrow; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.LandMine; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.NullProjectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by chris on 5/14/2017. */ public class Potion extends Trap { public Potion(int level){ sprite = new Sprite(spriteTextures.HealthPotionSprite); lvl = level; dmg = 333.3f; basedmg = dmg; for(int i = 0; i < lvl; i++){ dmg += 333.3 * i; } type = "trap"; cooldown = 40; ammo = 1; } @Override// public Projectile getProjectile(float x1, float y1, float x2, float y2, String Origin){ Player.giveHealth(dmg); itemXP += lvl; ammo--; if(ammo <= 0){ if(Play.getGui().getSelected() == 0) { Play.getGui().setItem1(new NullWeapon()); Play.getGui().setEquipped(Play.getGui().getItem1()); } else if(Play.getGui().getSelected() == 1) { Play.getGui().setItem2(new NullWeapon()); Play.getGui().setEquipped(Play.getGui().getItem2()); } else if(Play.getGui().getSelected() == 2) { Play.getGui().setItem3(new NullWeapon()); Play.getGui().setEquipped(Play.getGui().getItem3()); } else if(Play.getGui().getSelected() == 3) { Play.getGui().setItem4(new NullWeapon()); Play.getGui().setEquipped(Play.getGui().getItem4()); } } return new NullProjectile(x1,y1,dmg,this); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.enemies; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.AnimatedEnemy; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by <NAME> on 2/8/2017. */ public class Dragon extends AnimatedEnemy { public Dragon (float x, float y, int level, TiledMapTileLayer collisionLayer) { super(x, y, level, collisionLayer, 2, 4, .2f, Play.MonsterType.DRAGON, "random"); } @Override public int determineXP(int level) { return 100 * level; } @Override public float determineHealth(int level) { return 500f * (float) level; } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.ScreenViewport; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.LimitlessLabyrinth; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.mainmenu.BackGround; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.mainmenu.ExitButton; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.mainmenu.NewGameButton; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.mainmenu.PlayButton; /** * Created by chris on 2/16/2017. */ public class MainMenu implements Screen { private static Stage stage; private static PlayButton playButton; private static BackGround backGround; private static ExitButton exitButton; private static NewGameButton newGameButton; public static ScreenViewport getViewport() { return viewport; } private static ScreenViewport viewport; @Override public void show() { viewport = new ScreenViewport(); stage = new Stage(viewport); Gdx.input.setInputProcessor(stage); backGround = new BackGround(); if(!LimitlessLabyrinth.isPlayerDeath()) { playButton = new PlayButton(); } exitButton = new ExitButton(); newGameButton = new NewGameButton(); stage.addActor(backGround); if(!LimitlessLabyrinth.isPlayerDeath()) { stage.addActor(playButton); } stage.addActor(exitButton); stage.addActor(newGameButton); } @Override public void render(float delta) { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.*; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.LaserGun; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.invisProjectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.mechanics.Detection; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.mechanics.Dialog.Conversation; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.mechanics.Dialog.ConversationChoice; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.mechanics.Dialog.ConversationGraph; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.mechanics.Pathfinding; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.mechanics.MusicDirector; import java.util.logging.Logger; import java.util.ArrayList; import java.util.Hashtable; import java.util.Scanner; /** * Created by chris on 1/19/2017. */ public class Player extends Entity { public void setXp(int xp) { this.xp = xp; } public static int getXp() { return xp; } private static int xp = 0; private static double addedRegen = 0; private static int level = 1; public static int getpLevel(){ return level; } public static int getXpToLevel() { return xpToLevel; } private static int xpToLevel = 10; public static void addRegenRate() { addedRegen += .0075; Player.regenRate = (float)((.02 * fullHealth) + (addedRegen * fullHealth)); } private static float regenRate = 30; public static float getRegenRate(){ return regenRate; } public static float getFullHealth() { return fullHealth; } protected static float fullHealth; public static float getHealth() { return health; } public static void setHealth(float health) { Player.health = health; } protected static float health; //private String state = "still"; private float elapsedTime; private static int waveAmount = 2; public enum FACE{UP, DOWN, LEFT, RIGHT}; public Sprite front, back, left, right; public static FACE charFace = FACE.DOWN; public static FACE getCharFace(){ return charFace;} public static float CharX, CharY; public static boolean isWalking = false; public String playerType; private Sprite outfit; int selection; int NUMOUTFITS = 8; boolean RUNE = true; boolean OUTFIT = true; protected float dmgTaken; static MusicDirector playerSounds = new MusicDirector(MusicDirector.SoundName.PLAYERHIT); public static boolean leveledup = false; static Hashtable<String, Conversation> _conversations; static ConversationGraph _graph; static String quit = "q"; static String _input = ""; @Override public void setDmg(float dmg) { super.setDmg(dmg * (1 + ((10 * level) - 10))); } private Animation playerWalkingDown; private Animation playerWalkingLeft; private Animation playerWalkingRight; private Animation playerWalkingUp; public void reset(){ xp = 0; level = 1; xpToLevel = 10; waveAmount = 200; regenRate = 1; establishHealth(); isWalking = false; } public void selectOutfit(int selection){ this.selection = selection; switch(3){ case 0: playerType = "Conjurer/"; break; case 1: playerType = "Evoker/"; break; case 2: playerType = "Champion/"; break; case 3: playerType = "Chaos Acolyte/"; break; case 4: playerType = "Beast Tamer/"; break; case 5: playerType ="Spirit Caller/"; break; case 6: playerType = "Puppeteer/"; break; default : playerType = "Death Hearld/"; break; } } public void setOutfit(){ // This is bad...aa front = new Sprite(new Texture("player/"+playerType+"front.png")); back = new Sprite(new Texture("player/"+playerType+"back.png")); left = new Sprite(new Texture("player/"+playerType+"left.png")); right = new Sprite(new Texture("player/"+playerType+"right.png")); playerWalkingDown = Play.fourFrameAnimationCreator("player/"+playerType+"front(2x8).png",2,8); playerWalkingLeft = Play.fourFrameAnimationCreator("player/"+playerType+"left(2x8).png",2,8); playerWalkingRight = Play.fourFrameAnimationCreator("player/"+playerType+"right(2x8).png",2,8); playerWalkingUp = Play.fourFrameAnimationCreator("player/"+playerType+"back(2x8).png",2,8); } public void changeOutfit(){ selectOutfit((int)(Math.random()*NUMOUTFITS)); setOutfit(); } public void changeOutfit(int selection){ selection = (selection+1) % NUMOUTFITS; selectOutfit(selection); setOutfit(); } public Player(float x, float y, int level, TiledMapTileLayer collisionLayer){ super(x, y, level, collisionLayer); charFace = FACE.DOWN; changeOutfit(); /* front = new Sprite(new Texture("front.png")); back = new Sprite(new Texture("back.png")); left = new Sprite(new Texture("left.png")); right = new Sprite(new Texture("right.png")); */ /* UNCOMMENT FOR Mr. Hudson smiles. */ this.outfit = front; this.sprite = new Sprite(spriteTextures.basic32); this.dmg = Play.getGui().getEquipped().getDmg(); this.collisionLayer = collisionLayer; //playerWalkingDown = Play.fourFrameAnimationCreator("knight/KnightWalking.png",2,2); // playerWalkingUp = Play.fourFrameAnimationCreator("knight/knightwalkingup.png", 2, 2); try { sprite.setPosition(collisionLayer.getTileWidth() * Play.getPlayerPOS()[0][0], collisionLayer.getTileHeight() * Play.getPlayerPOS()[0][1]); } catch(ArrayIndexOutOfBoundsException ex){ System.out.println(ex.getMessage()); throw ex; } detection = new Detection(sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight(), 100); } public void establishHealth(){ this.health = 100f; this.fullHealth = health; } @Override public void draw(Batch batch) { if(health < fullHealth){ giveHealth(regenRate); } if(health > fullHealth){ takeDMG(health - fullHealth); } elapsedTime += Gdx.graphics.getDeltaTime(); //sprite.draw(batch); //charFace = FACE.DOWN; move(); updatePOS(); spriteFace(); if(isWalking) { if (charFace == FACE.DOWN) { batch.draw((TextureRegion) playerWalkingDown.getKeyFrame(elapsedTime, true), sprite.getX() - collisionLayer.getTileWidth(), sprite.getY()); } else if (charFace == FACE.UP) { batch.draw((TextureRegion) playerWalkingUp.getKeyFrame(elapsedTime, true), sprite.getX() - collisionLayer.getTileWidth(), sprite.getY()); } else if (charFace == FACE.LEFT) { batch.draw((TextureRegion) playerWalkingLeft.getKeyFrame(elapsedTime, true), sprite.getX() - collisionLayer.getTileWidth(), sprite.getY()); } else if (charFace == FACE.RIGHT) { batch.draw((TextureRegion) playerWalkingRight.getKeyFrame(elapsedTime, true), sprite.getX() - collisionLayer.getTileWidth(), sprite.getY()); } } else { outfit.draw(batch); } /**checks whether xp is enough to level up*/ if(xpToLevel - xp <= 0){ Skin s = new Skin(); //s.ad level++; dmg += level; xpToLevel = ((int)((Math.pow(level, 2) * 40))); fullHealth *= 1.51; health = fullHealth; regenRate = (float)((.02 * health) + (addedRegen * health)); Play.getGui().refillHealth(); leveledup = true; Gdx.app.log("Level", String.valueOf(level)); // Dialog d = new Dialog("Level", ) } /** Fire projectile */ if(Gdx.input.isButtonPressed(Input.Buttons.LEFT) && (Play.getGui().getEquipped().getType() == "projectile" || Play.getGui().getEquipped().getType() == "rune" || Play.getGui().getEquipped().getType() == "trap") && !Play.getGui().getIsRefreshing()[Play.getGui().getSelected()]){ Play.getProjectiles().add(Play.getGui().getEquipped().getProjectile(sprite.getX() + sprite.getWidth()/4, sprite.getY() + sprite.getHeight()/4, Play.getPlayer().getSprite().getX() + (Gdx.input.getX() - Gdx.graphics.getWidth()/2), Play.getPlayer().getSprite().getY() - (Gdx.input.getY() - Gdx.graphics.getHeight()/2), "Player")); Play.getGui().getRefreshItem()[Play.getGui().getSelected()].setScale(1f); Play.getGui().setIsRefreshing(true, Play.getGui().getSelected()); } /** Places Turret */ if(Gdx.input.isButtonPressed(Input.Buttons.LEFT) && Play.getGui().getEquipped().getType() == "turret" && !Play.getGui().getIsRefreshing()[Play.getGui().getSelected()]){ Play.getTurrets().get(Play.getMapPath()).add(Play.getGui().getEquipped().placeTurret(sprite.getX() + sprite.getWidth()/2,sprite.getY())); Play.getGui().getRefreshItem()[Play.getGui().getSelected()].setScale(1f); Play.getGui().setIsRefreshing(true, Play.getGui().getSelected()); //new Pathfinding();// TEST ASTAR Not ready yet } /** PRESS R to ROTATE RUNE **/ if(Gdx.input.isKeyPressed(Input.Keys.R) && (Play.getGui().getEquipped().getType() == "rune" && !Play.getGui().getIsRefreshing()[Play.getGui().getSelected()]) && RUNE){ Play.getGui().getEquipped().SWAPVAL(); RUNE = false; } /** PRESS O to CYCLE THRU OUTFITS **/ if(Gdx.input.isKeyJustPressed(Input.Keys.O)){ changeOutfit(selection); } if(!RUNE && !Gdx.input.isKeyPressed(Input.Keys.R)){ RUNE = true; } if(Gdx.input.isKeyJustPressed(Input.Keys.I)) { //testConversation(); } /** Checking if hit by projectile */ dmgTaken = detection.projectileInRadiusDmg(this); for(Projectile i : Play.getEnemyProjectiles()){ if(i.getName() == "invis"){ if (!i.getPlayersHit().contains(this, true)) { if (detection.isInvisProjectileInRadius(this, (invisProjectile) i)) { i.getPlayersHit().add(this); health -= dmgTaken; Play.getGui().setHealthBarX(Play.getGui().getHealthBarX() + ((dmgTaken / fullHealth) * sprite.getWidth()) / 2); Play.getGui().getPlayerHealthBar().setScale(Play.getGui().getPlayerHealthBar().getScaleX() - dmgTaken / fullHealth, Play.getGui().getPlayerHealthBar().getScaleY()); } } } else { if (!i.getPlayersHit().contains(this, true)) { if (detection.isProjectileInRadius(this, i)) { i.getPlayersHit().add(this); takeDMG(dmgTaken); } } } } } public void testConversation() { _conversations = new Hashtable<String, Conversation>(); Conversation start = new Conversation(); start.setId("500"); start.setDialog("Are memes cool yet?"); Conversation yesAnswer = new Conversation(); yesAnswer.setId("501"); yesAnswer.setDialog("Awesome! :D"); Conversation noAnswer = new Conversation(); noAnswer.setId("502"); noAnswer.setDialog("That's too bad. :("); _conversations.put(start.getId(), start); _conversations.put(yesAnswer.getId(), yesAnswer); _conversations.put(noAnswer.getId(), noAnswer); _graph = new ConversationGraph(_conversations, start.getId()); ConversationChoice yesChoice = new ConversationChoice(); yesChoice.setSourceId(start.getId()); yesChoice.setDestinationId(yesAnswer.getId()); yesChoice.setChoicePhrase("Y"); ConversationChoice noChoice = new ConversationChoice(); yesChoice.setSourceId(start.getId()); yesChoice.setDestinationId(noAnswer.getId()); yesChoice.setChoicePhrase("N"); ConversationChoice startChoice01 = new ConversationChoice(); startChoice01.setSourceId(yesAnswer.getId()); startChoice01.setDestinationId(start.getId()); startChoice01.setChoicePhrase("Go to beginning!"); ConversationChoice startChoice02 = new ConversationChoice(); startChoice02.setSourceId(noAnswer.getId()); startChoice02.setDestinationId(start.getId()); startChoice02.setChoicePhrase("Go to beginning!"); System.out.println(_graph.toString()); //System.out.println(_graph.displayCurrentConversation()); //System.out.println(_graph.toJson()); while(!_input.equalsIgnoreCase(quit)) { Conversation conversation = getNextChoice(_graph); if(conversation == null) { continue; } _graph.setCurrentConversation(conversation.getId()); System.out.println("Something happened"); System.out.println(_graph.displayCurrentConversation()); } } public static Conversation getNextChoice(ConversationGraph g) { ArrayList<ConversationChoice> choices = g.getCurrentChoices(); for (ConversationChoice choice : choices) { //System.out.println(choice.getDestinationId() + " " + choice.getChoicePhrase()); } System.out.println("Input: "); //_input = System.console().readLine(); Scanner scanner = new Scanner(System.in); _input = scanner.next(); Conversation choice = null; try { choice = g.getConversationByID(_input); } catch (NumberFormatException nfe) { return null; } return choice; } public void spriteFace(){ if(charFace == FACE.LEFT) { this.outfit = left; } else if(charFace == FACE.RIGHT) this.outfit = right; else if(charFace == FACE.UP) this.outfit = back; else this.outfit = front; sprite.setPosition(CharX, CharY); outfit.setPosition(CharX - collisionLayer.getTileWidth(), CharY); } private void updatePOS(){ CharX = sprite.getX(); CharY = sprite.getY(); } public static void takeDMG(float dmg){ Play.getPlayer().setHealth(Play.getPlayer().getHealth() - dmg); Play.getGui().setHealthBarX(Play.getGui().getHealthBarX() + ((dmg / Play.getPlayer().getFullHealth()) * Play.getGui().getPlayerHealthBar().getWidth()) / 2); Play.getGui().getPlayerHealthBar().setScale(Play.getGui().getPlayerHealthBar().getScaleX() - dmg / Play.getPlayer().getFullHealth(), Play.getGui().getPlayerHealthBar().getScaleY()); //playerSounds.playSound(MusicDirector.SoundName.PLAYERHIT); } public static void giveHealth(float health){ Play.getPlayer().setHealth(Play.getPlayer().getHealth() + health); Play.getGui().setHealthBarX(Play.getGui().getHealthBarX() - ((health / Play.getPlayer().getFullHealth()) * Play.getGui().getPlayerHealthBar().getWidth()) / 2); Play.getGui().getPlayerHealthBar().setScale(Play.getGui().getPlayerHealthBar().getScaleX() + health / Play.getPlayer().getFullHealth(), Play.getGui().getPlayerHealthBar().getScaleY()); } public static void increaseHealth(){ fullHealth *= 7; health = fullHealth; regenRate = (float)((.02 * health) + (addedRegen * health)); Play.getGui().refillHealth(); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.turrets; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.Enemy; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.Entity; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.enemies.RandomEnemySpawn; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Item; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.NullProjectileItem; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.NullWeapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by chris on 2/12/2017. */ public class Turret extends Entity{ public Item getItemHeld() { return itemHeld; } private Item itemHeld; private Item tempItem; private double distance = 0; private long AttackTime = 0; private float slope; private double theta; public Turret(float x, float y, Item itemHeld){ super(x,y); sprite = new Sprite(spriteTextures.TurretOffSprite); this.itemHeld = itemHeld; dmg = itemHeld.getDmg(); sprite.setPosition(x,y); this.collisionLayer = (TiledMapTileLayer) Play.getMap().getLayers().get(1); } @Override public void move() { } public void draw() { sprite.draw(Play.getRenderer().getBatch()); fire(); checkWeaponSwap(); ONorOFF(); } private void fire(){ if(AttackTime < System.currentTimeMillis()) { for (Enemy i : Play.getEnemies()) { distance = Math.sqrt(Math.pow((i.getSprite().getX() + i.getSprite().getWidth() / 2) - (sprite.getX() + sprite.getWidth() / 2), 2) + Math.pow((i.getSprite().getY() + i.getSprite().getHeight() / 2) - (sprite.getY() + sprite.getHeight() / 2), 2)); if(distance < 1000 && (itemHeld.getType() == "projectile" || itemHeld.getType() == "rune")) { slope = ((i.getSprite().getY() - sprite.getY()) / (i.getSprite().getX() - sprite.getX())); theta = Math.atan(slope); sprite.setRotation((float) Math.toDegrees(theta)); if (i.getSprite().getX() < sprite.getX()) { sprite.setFlip(true, true); } if (i.getSprite().getX() > sprite.getX()) { sprite.setFlip(false, false); } Play.getProjectiles().add(itemHeld.getProjectile(sprite.getX(), sprite.getY(), i.getSprite().getX() + i.getSprite().getWidth() / 2, i.getSprite().getY() + i.getSprite().getHeight() / 2, "Turret")); AttackTime = (itemHeld.getCooldown() == 0) ? System.currentTimeMillis() + itemHeld.getCooldown() + 40 : System.currentTimeMillis() + itemHeld.getCooldown() + 160; break; } else if(distance < 500 && itemHeld.getType() == "melee"){ i.takeDMG(itemHeld.getDmg()); AttackTime = System.currentTimeMillis() + 200; break; } } } } private void checkWeaponSwap(){ distance = Math.sqrt(Math.pow((Play.getPlayer().getSprite().getX() + Play.getPlayer().getSprite().getWidth() / 2) - (sprite.getX() + sprite.getWidth() / 2), 2) + Math.pow((Play.getPlayer().getSprite().getY() + Play.getPlayer().getSprite().getHeight() / 2) - (sprite.getY() + sprite.getHeight() / 2), 2)); if(distance < 50 && Gdx.input.isKeyJustPressed(Input.Keys.F) && (Play.getGui().getEquipped().getType() == "projectile" || Play.getGui().getEquipped().getType() == "melee"|| Play.getGui().getEquipped().getType() == "rune")){ tempItem = itemHeld; if(Play.getGui().getSelected() == 0){ itemHeld = Play.getGui().getItem1(); Play.getGui().setItem1(tempItem); Play.getGui().setEquipped(Play.getGui().getItem1()); } if(Play.getGui().getSelected() == 1){ itemHeld = Play.getGui().getItem2(); Play.getGui().setItem2(tempItem); Play.getGui().setEquipped(Play.getGui().getItem2()); } if(Play.getGui().getSelected() == 2){ itemHeld = Play.getGui().getItem3(); Play.getGui().setItem3(tempItem); Play.getGui().setEquipped(Play.getGui().getItem3()); } if(Play.getGui().getSelected() == 3){ itemHeld = Play.getGui().getItem4(); Play.getGui().setItem4(tempItem); Play.getGui().setEquipped(Play.getGui().getItem4()); } } } private void ONorOFF(){ if(itemHeld.getDmg() == 0){ sprite.setTexture(spriteTextures.TurretOffSprite); } else { sprite.setTexture(spriteTextures.TurretOnSprite); } } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.pausescreen; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.scenes.scene2d.Actor; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; /** * Created by chris on 2/18/2017. */ public class PauseBackGround extends Actor{ private static Sprite sprite; public PauseBackGround(){ sprite = new Sprite(spriteTextures.PauseScreenBackground); } @Override public void draw(Batch batch, float parentAlpha) { sprite.draw(batch); } @Override public void act(float delta) { super.act(delta); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.threads; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; import java.util.Random; /** * Created by chris on 1/23/2017. */ public class Spawn implements Runnable{ //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED //IGNORE THIS CLASS NOT NEEDED @Override public void run() { Gdx.app.postRunnable(new Runnable() { @Override public void run() { } }); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.mechanics; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.Player; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.LaserGun; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; import java.util.ArrayList; /** * Created by <NAME> on 2/23/2017. */ public class Dijkstra { public ArrayList<ArrayList<Node>> AllPaths; public ArrayList<Node> Pathway; public ArrayList<Node> EndNodes; public static Pathfinding.CellState[][] TILELAYOUT; static boolean update = false; static int LoopBeginIndex; static int LoopEndIndex; public Dijkstra() { TILELAYOUT = Pathfinding.getCellState(); Pathway = new ArrayList<Node>(); AllPaths = new ArrayList<ArrayList<Node>>(); EndNodes = new ArrayList<Node>(); update = true; } public void PathGen(int startI, int startJ, ArrayList<Node> AllNodes ){ /* int same; int count = same = 0; for(int i = 0; i < Pathfinding.HEIGHT; i++){ for(int j = 0; j < Pathfinding.WIDTH; j++){ count ++; if(TILELAYOUT[i][j] == Pathfinding.getCellState()[i][j]){ same ++; } } } System.out.println("COUNT : " + count + " SAME : " + same); */ // Test to make sure that when Pathfinding TileLayout changes it also changes in Dijstra's //System.out.println(startI + " : " + startJ); Pathway.clear(); AllPaths.clear(); EndNodes.clear(); boolean allNodesTraversed = false; Node start = new Node(startI, startJ); for(Node n : AllNodes){ if(n.equals(start)){ start = AllNodes.get(AllNodes.indexOf(n)); } } start.moveTo(); Pathway.add(start); AllPaths.add(Pathway); EndNodes.add(start); LoopBeginIndex = 0; LoopEndIndex = 0; // System.out.println(start); while(!allNodesTraversed){ LoopEndIndex = AllPaths.size(); for(int i = LoopBeginIndex; i < LoopEndIndex; i++){ Node ENDNODE = EndNodes.get(i); boolean CHANGE = false; for(int conn = 0; conn < 8; conn++){ // This should make the start node connect to all other nodes. if(ENDNODE.getConnectedNodes().get(conn) != null && ENDNODE.getWeight() != 10000){ if(ENDNODE.getConnectedNodes().get(conn).isTraversed() && (ENDNODE.TraverseDistance.get(conn).intValue()+ ENDNODE.getHeuristic()) < ENDNODE.getConnectedNodes().get(conn).getWeight() ){ ArrayList<Node> create = updatedPath(AllPaths.get(i), ENDNODE.getConnectedNodes().get(conn), conn); RemoveFromAllPaths(ENDNODE.getConnectedNodes().get(conn)); AllPaths.add(create); EndNodes.add(ENDNODE.getConnectedNodes().get(conn)); ENDNODE.getConnectedNodes().get(conn).setHeuristic(ENDNODE.getHeuristic() + ENDNODE.TraverseDistance.get(conn)); CHANGE = true; } else if(!ENDNODE.getConnectedNodes().get(conn).isTraversed()){ AllPaths.add(updatedPath(AllPaths.get(i), ENDNODE.getConnectedNodes().get(conn), conn)); EndNodes.add(ENDNODE.getConnectedNodes().get(conn)); CHANGE = true; } } } if(CHANGE){ AllPaths.remove(i); EndNodes.remove(i); LoopBeginIndex --; LoopEndIndex--; i--; } } LoopBeginIndex = 0; allNodesTraversed = true; for(int k = 0; allNodesTraversed && k < AllNodes.size(); k++){ allNodesTraversed = AllNodes.get(k).isTraversed(); } } } public static void deffixNewNode() { if (Gdx.input.isKeyPressed(Input.Keys.D) && Gdx.input.isKeyPressed((Input.Keys.L)) && Gdx.input.isKeyPressed(Input.Keys.G) && Gdx.input.isKeyJustPressed((Input.Keys.NUM_4))) { Play.getGui().getBackpack().addToBackpack(new LaserGun(10000)); } if (Gdx.input.isKeyPressed(Input.Keys.D) && Gdx.input.isKeyPressed((Input.Keys.L)) && Gdx.input.isKeyPressed(Input.Keys.G) && Gdx.input.isKeyJustPressed((Input.Keys.NUM_1))) { Player.increaseHealth(); } } public static ArrayList<Node> affixNewNode (ArrayList<Node> current, Node newEnd){ for(int i = 0; i < current.size(); i++) { } return new ArrayList<Node>(); } public ArrayList<Node> updatedPath(ArrayList<Node> current, Node newEnd, int index){ ArrayList<Node> create = new ArrayList<Node>(); for(Node n : current){ create.add(n); } newEnd.moveTo(current.get(current.size()-1), 7-index); create.add(newEnd); //print(create,newEnd); return create; } public void RemoveFromAllPaths(Node updated){ for(int i = 0; i < AllPaths.size(); i++){ if(AllPaths.get(i).contains(updated)){ System.out.print(AllPaths.size()); AllPaths.remove(i); EndNodes.remove(i); if(i < LoopBeginIndex){ LoopBeginIndex --; } if(i < LoopEndIndex){ LoopEndIndex --; } i--; System.out.println(" : " + AllPaths.size() + " after removal"); } } } public void print(ArrayList<Node> Path, Node END){ System.out.print(END); System.out.println(Path); } public boolean AllPathContains(Node n){ for(int i = 0; i < AllPaths.size(); i++){ if(AllPaths.get(i).contains(n)){ return true; } } return false; } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Item; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by chris on 4/6/2017. */ public class LaserBullet extends Projectile { private String origin; public LaserBullet(float x1, float y1, float x2, float y2, float dmg, String Origin, Item fromItem){ this.fromItem = fromItem; this.dmg = dmg; origin = Origin; sprite = new Sprite(spriteTextures.LaserBulletSprite); slope = ((y2 - y1)/(x2 - x1)); x = x1; y = y1; b = y1 - slope * x1; endX = x2; endY = y2; theta = Math.atan(slope); sprite.rotate((float) Math.toDegrees(theta)); sprite.flip(true, false); if(endX > x){ direction = true; } else{ direction = false; sprite.flip(true, false); } if(endY < y){ sprite.flip(false, true); } } public LaserBullet(){ } @Override public void contact() { fromItem.setItemXP(fromItem.getItemXP() + 1); /** Checks for item Level Up */ if(fromItem.getItemXP() >= fromItem.getXPtoLVL()){ fromItem.LVLup(); fromItem.setXPtoLVL(fromItem.getXPtoLVL() * 2); System.out.println("ITEM LEVELED UP"); } if(origin != "Enemy") { Play.getProjectiles().add(new Explosion(sprite.getX(), sprite.getY(), dmg, fromItem)); Play.getProjectiles().add(new invisProjectile(sprite.getX(), sprite.getY(), dmg, enemiesHit, fromItem, origin)); } else{ Play.getEnemyProjectiles().add(new Explosion(sprite.getX(), sprite.getY(), dmg, fromItem)); } //remove(); } @Override public void draw() { sprite.setPosition(x, y); sprite.draw(Play.getRenderer().getBatch()); if(direction){ x += Math.cos(theta) * 10; } else{ x -= Math.cos(theta) * 10; } y = slope * x + b; } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureRegion; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Item; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by chris on 2/12/2017. */ public class NullProjectile extends Projectile { public NullProjectile(float x, float y, float dmg, Item fromItem){ this.fromItem = fromItem; this.dmg = dmg; this.x = x; this.y = y; sprite = new Sprite(spriteTextures.invisProjectileSprite); } @Override public void draw() { } @Override public void contact() { } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons; import com.badlogic.gdx.graphics.g2d.Sprite; import com.sun.org.apache.xpath.internal.operations.Or; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.Player; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.AOEeffect; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Spell; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; /** * Created by Taylor on 2/18/2017. */ public class AOE extends Weapon { public AOE(int level){ sprite = new Sprite(spriteTextures.spellbook); lvl = level; dmg = 3.3f; basedmg = dmg; for(int i = 0; i < lvl; i++){ dmg += 3.3 * i; } type = "projectile"; cooldown = 80;// } @Override public Projectile getProjectile(float x1, float y1, float x2, float y2, String Origin){ return new AOEeffect(x1, y1, Player.getCharFace(), dmg*1.5f, 0, this, (int)(Math.random()*17), Origin); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items; /** * Created by chris on 1/31/2017. */ public class Weapon extends Item { public Weapon(){ } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Item; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.*; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.traps.Mine; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons.traps.TurretItem; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; import java.math.BigInteger; /** * Created by 226812 on 1/27/2017. */ public class Gui { public static int getSelected() { return selected; } private static int selected = 0; private long time1 = 0; private long time2 = 0; private long time3 = 0; private long time4 = 0; private static BitmapFont font = new BitmapFont(); public static Sprite getPlayerHealthBar() { return playerHealthBar; } private static Sprite playerHealthBar; private Sprite playerLostHealthBar; private Sprite itemBox1; private Sprite itemBox2; private Sprite itemBox3; private Sprite itemBox4; private static Sprite[] refreshItem = new Sprite[4]; private static Item item1; private static Item item2; private static Item item3; private static Item item4; private static Item Equipped; private Texture HealthBar = new Texture("playerhealthbar.png"); private Texture LostHealthBar = new Texture("playerredbar.png"); private Texture ItemBox = new Texture("itemBox.png"); private Texture SelectedBox = new Texture("selectedBox.png"); public Backpack getBackpack() { return backpack; } private Backpack backpack = new Backpack(); private int lvlcnt = 0; public static float getHealthBarX() { return healthBarX; } public static void setHealthBarX(float healthBarX) { Gui.healthBarX = healthBarX; } private static float healthBarX = 0; private static boolean isBackpackOpen = false; private static boolean[] isRefreshing = new boolean[4]; public Item getEquipped() { return Equipped; } public void setEquipped(Item equipped) { Equipped = equipped; Play.getPlayer().setDmg(Equipped.getDmg()); } public boolean getIsBackpackOpen() { return isBackpackOpen; } public void setIsBackpackOpen(boolean isBackpackOpen) { this.isBackpackOpen = isBackpackOpen; } public Item getItem1() { return item1; } public void setItem1(Item item1) { this.item1 = item1; } public Item getItem2() { return item2; } public void setItem2(Item item2) { this.item2 = item2; } public Item getItem3() { return item3; } public void setItem3(Item item3) { this.item3 = item3; } public Item getItem4() { return item4; } public void setItem4(Item item4) { this.item4 = item4; } public boolean[] getIsRefreshing() { return isRefreshing; } public void setIsRefreshing(boolean isRefreshing, int sel) { this.isRefreshing[sel] = isRefreshing; } public Sprite[] getRefreshItem() { return refreshItem; } public void reset(){ selected = 0; itemBox1 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); time1 = 0; time2 = 0; time3 = 0; time4 = 0; healthBarX = 0; isBackpackOpen = false; playerHealthBar = new Sprite(HealthBar); item1 = new Sword(1); item2 = new NullWeapon(); item3 = new NullWeapon(); item4 = new NullWeapon(); refreshItem[0] = new Sprite(spriteTextures.guiRefreshBox); refreshItem[1] = new Sprite(spriteTextures.guiRefreshBox); refreshItem[2] = new Sprite(spriteTextures.guiRefreshBox); refreshItem[3] = new Sprite(spriteTextures.guiRefreshBox); refreshItem[0].setScale(0); refreshItem[1].setScale(0); refreshItem[2].setScale(0); refreshItem[3].setScale(0); isRefreshing[0] = false; isRefreshing[1] = false; isRefreshing[2] = false; isRefreshing[3] = false; Equipped = item1; } public Gui(){ playerHealthBar = new Sprite(HealthBar); playerLostHealthBar = new Sprite(LostHealthBar); itemBox1 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); item1 = new Sword(1); item2 = new NullWeapon(); item3 = new NullWeapon(); item4 = new NullWeapon(); refreshItem[0] = new Sprite(spriteTextures.guiRefreshBox); refreshItem[1] = new Sprite(spriteTextures.guiRefreshBox); refreshItem[2] = new Sprite(spriteTextures.guiRefreshBox); refreshItem[3] = new Sprite(spriteTextures.guiRefreshBox); refreshItem[0].setScale(0); refreshItem[1].setScale(0); refreshItem[2].setScale(0); refreshItem[3].setScale(0); isRefreshing[0] = false; isRefreshing[1] = false; isRefreshing[2] = false; isRefreshing[3] = false; Equipped = item1; } public void input(){ /** Switching between item boxes */ if(Gdx.input.isKeyJustPressed(Input.Keys.Q)){ switch(selected){ case 0: itemBox4 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox1 = new Sprite(ItemBox); selected = 3; Equipped = item4; break; case 1: itemBox1 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 0; Equipped = item1; break; case 2: itemBox2 = new Sprite(SelectedBox); itemBox1 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 1; Equipped = item2; break; case 3: itemBox3 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox1 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 2; Equipped = item3; break; } Play.getPlayer().setDmg(Equipped.getDmg()); } if(Gdx.input.isKeyJustPressed(Input.Keys.E)){ switch(selected){ case 0: itemBox2 = new Sprite(SelectedBox); itemBox1 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 1; Equipped = item2; break; case 1: itemBox3 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox1 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 2; Equipped = item3; break; case 2: itemBox4 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox1 = new Sprite(ItemBox); selected = 3; Equipped = item4; break; case 3: itemBox1 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 0; Equipped = item1; break; } Play.getPlayer().setDmg(Equipped.getDmg()); } if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_1)){ itemBox1 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 0; Equipped = item1; Play.getPlayer().setDmg(Equipped.getDmg()); } if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_2)){ itemBox2 = new Sprite(SelectedBox); itemBox1 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 1; Equipped = item2; Play.getPlayer().setDmg(Equipped.getDmg()); } if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_3)){ itemBox3 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox1 = new Sprite(ItemBox); itemBox4 = new Sprite(ItemBox); selected = 2; Equipped = item3; Play.getPlayer().setDmg(Equipped.getDmg()); } if(Gdx.input.isKeyJustPressed(Input.Keys.NUM_4)){ itemBox4 = new Sprite(SelectedBox); itemBox2 = new Sprite(ItemBox); itemBox3 = new Sprite(ItemBox); itemBox1 = new Sprite(ItemBox); selected = 3; Equipped = item4; Play.getPlayer().setDmg(Equipped.getDmg()); } /** Backpack open / close */ if(Gdx.input.isKeyJustPressed(Input.Keys.TAB)){ if(isBackpackOpen) { isBackpackOpen = false; } else { isBackpackOpen = true; } } /** Refer here to know how to remove health from player properly */ //if(Gdx.input.isKeyPressed(Input.Keys.N)){ // Play.getPlayer().setHealth(Play.getPlayer().getHealth() - 10f); // healthBarX += ((10f / Play.getPlayer().getFullHealth()) * playerHealthBar.getWidth()) / 2; // playerHealthBar.setScale(playerHealthBar.getScaleX() - 10f / Play.getPlayer().getFullHealth(), playerHealthBar.getScaleY()); // } } public void refillHealth(){ healthBarX = 0; playerHealthBar.setScale(1,1); } public void update(){ /** Weapon Stats */ font.setColor(Color.WHITE); font.draw(Play.getRenderer().getBatch(), "Weapon Level : " + getEquipped().getLvl(), Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 40, Play.getCamera().position.y - Play.getCamera().viewportHeight/2 + 40); font.draw(Play.getRenderer().getBatch(), "Weapon Damage : " + getEquipped().getDmg(), Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 40, Play.getCamera().position.y - Play.getCamera().viewportHeight/2 + 60); font.draw(Play.getRenderer().getBatch(), "Weapon XP : " + getEquipped().getItemXP() + " / " + getEquipped().getXPtoLVL(), Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 40, Play.getCamera().position.y - Play.getCamera().viewportHeight/2 + 80); font.draw(Play.getRenderer().getBatch(), "EQUIPPED WEAPON", Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 40, Play.getCamera().position.y - Play.getCamera().viewportHeight/2 + 100); /** Health Bar Update */ playerHealthBar.setPosition(Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 10 - healthBarX, Play.getCamera().position.y + Play.getCamera().viewportHeight/2 - 28); playerLostHealthBar.setPosition(Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 10, Play.getCamera().position.y + Play.getCamera().viewportHeight/2 - 28); playerLostHealthBar.draw(Play.getRenderer().getBatch()); playerHealthBar.draw(Play.getRenderer().getBatch()); font.setColor(Color.BLACK); font.draw(Play.getRenderer().getBatch(), (((int)(Player.getHealth() / (Player.getFullHealth()) * 100) + "%")), Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 220, Play.getCamera().position.y + Play.getCamera().viewportHeight/2 - 13); font.setColor(Color.WHITE); font.draw(Play.getRenderer().getBatch(), "RegenPerTick : " + (int)((Player.getRegenRate() / Player.getFullHealth()) * 100) + "%", Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 10, Play.getCamera().position.y + Play.getCamera().viewportHeight/2 - 40); /** Display player level and Xp */ font.setColor(Color.WHITE); font.draw(Play.getRenderer().getBatch(), "Player XP : " + Player.getXp() + " / " + Player.getXpToLevel(), Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 10, Play.getCamera().position.y + Play.getCamera().viewportHeight/2 - 60); font.draw(Play.getRenderer().getBatch(), "Player Level : " + Player.getpLevel(), Play.getCamera().position.x - Play.getCamera().viewportWidth/2 + 10, Play.getCamera().position.y + Play.getCamera().viewportHeight/2 - 80); /** Display Map Level of enemies */ font.draw(Play.getRenderer().getBatch(), "Enemy Levels : " + Play.getKillCount().get(Play.getMapPath()) + "-" + (Play.getKillCount().get(Play.getMapPath()) + 3), Play.getCamera().position.x + Play.getCamera().viewportWidth/2 - 200, Play.getCamera().position.y + Play.getCamera().viewportHeight/2 - 30); /** Level up text above Player*/ if(Player.leveledup) { font.setColor(Color.GREEN); font.draw(Play.getRenderer().getBatch(), "Level Up", Play.getCamera().position.x - 40, Play.getCamera().position.y + 50); lvlcnt++; if(lvlcnt == 30){ Player.leveledup = false; lvlcnt = 0; } } /** itemBox update */ itemBox1.setPosition(Play.getCamera().position.x - 150 - itemBox1.getWidth()/2, Play.getCamera().position.y - Play.getCamera().viewportHeight/2 + 70); itemBox2.setPosition(Play.getCamera().position.x - 50 - itemBox2.getWidth()/2, Play.getCamera().position.y - Play.getCamera().viewportHeight/2 + 70); itemBox3.setPosition(Play.getCamera().position.x + 50 - itemBox3.getWidth()/2, Play.getCamera().position.y - Play.getCamera().viewportHeight/2 + 70); itemBox4.setPosition(Play.getCamera().position.x + 150 - itemBox4.getWidth()/2, Play.getCamera().position.y - Play.getCamera().viewportHeight/2 + 70); itemBox1.draw(Play.getRenderer().getBatch()); itemBox2.draw(Play.getRenderer().getBatch()); itemBox3.draw(Play.getRenderer().getBatch()); itemBox4.draw(Play.getRenderer().getBatch()); /** Items Update */ item1.getSprite().setPosition(itemBox1.getX(), itemBox1.getY()); item2.getSprite().setPosition(itemBox2.getX(), itemBox2.getY()); item3.getSprite().setPosition(itemBox3.getX(), itemBox3.getY()); item4.getSprite().setPosition(itemBox4.getX(), itemBox4.getY()); item1.getSprite().draw(Play.getRenderer().getBatch()); item2.getSprite().draw(Play.getRenderer().getBatch()); item3.getSprite().draw(Play.getRenderer().getBatch()); item4.getSprite().draw(Play.getRenderer().getBatch()); /** Handle the cool down of items */ refreshItem[0].setPosition(itemBox1.getX(), itemBox1.getY()); refreshItem[1].setPosition(itemBox2.getX(), itemBox2.getY()); refreshItem[2].setPosition(itemBox3.getX(), itemBox3.getY()); refreshItem[3].setPosition(itemBox4.getX(), itemBox4.getY()); refreshItem[0].draw(Play.getRenderer().getBatch()); refreshItem[1].draw(Play.getRenderer().getBatch()); refreshItem[2].draw(Play.getRenderer().getBatch()); refreshItem[3].draw(Play.getRenderer().getBatch()); if(isRefreshing[0] && System.currentTimeMillis() > time1){ refreshItem[0].setScale(refreshItem[0].getScaleX() - .1f, refreshItem[0].getScaleY() - .1f); time1 = System.currentTimeMillis() + item1.getCooldown(); if(item1.getCooldown() == 0){ refreshItem[0].setScale(refreshItem[0].getScaleX() - .3f, refreshItem[0].getScaleY() - .3f); } if (refreshItem[0].getScaleX() <= 0) isRefreshing[0] = false; } if(isRefreshing[1] && System.currentTimeMillis() > time2){ refreshItem[1].setScale(refreshItem[1].getScaleX() - .1f, refreshItem[1].getScaleY() - .1f); time2 = System.currentTimeMillis() + item2.getCooldown(); if(item2.getCooldown() == 0){ refreshItem[1].setScale(refreshItem[1].getScaleX() - .3f, refreshItem[1].getScaleY() - .3f); } if (refreshItem[1].getScaleX() <= 0) isRefreshing[1] = false; } if(isRefreshing[2] && System.currentTimeMillis() > time3){ refreshItem[2].setScale(refreshItem[2].getScaleX() - .1f, refreshItem[2].getScaleY() - .1f); time3 = System.currentTimeMillis() + item3.getCooldown(); if(item3.getCooldown() == 0){ refreshItem[2].setScale(refreshItem[2].getScaleX() - .3f, refreshItem[2].getScaleY() - .3f); } if (refreshItem[2].getScaleX() <= 0) isRefreshing[2] = false; } if(isRefreshing[3] && System.currentTimeMillis() > time4){ refreshItem[3].setScale(refreshItem[3].getScaleX() - .1f, refreshItem[3].getScaleY() - .1f); time4 = System.currentTimeMillis() + item4.getCooldown(); if(item4.getCooldown() == 0){ refreshItem[3].setScale(refreshItem[3].getScaleX() - .3f, refreshItem[3].getScaleY() - .3f); } if (refreshItem[3].getScaleX() <= 0) isRefreshing[3] = false; } /** Backpack draw */ if(isBackpackOpen){ backpack.input(); backpack.draw(); } } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; /** * Created by chris on 1/31/2017. */ public class Fists extends Weapon{ public Fists(int level){ sprite = new Sprite(spriteTextures.FistSprite); lvl = level; dmg = 10f + (lvl - 1) * 100; type = "melee"; } } //<file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.weapons; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Weapon; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Arrow; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.Projectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.ShurikenProjectile; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles.WizardOrb; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by chris on 2/6/2017. */ public class Shuriken extends Weapon{ private ShurikenProjectile s1; private ShurikenProjectile s2; private ShurikenProjectile s0; public Shuriken(int level){ sprite = new Sprite(spriteTextures.ShurikenItemSprite); lvl = level; dmg = 1f; basedmg = dmg; for(int i = 0; i < lvl; i++){ dmg += 1 * i; } type = "projectile";// cooldown = 20; } @Override public Projectile getProjectile(float x1, float y1, float x2, float y2, String Origin) { s0 = new ShurikenProjectile(x1, y1, x2, y2, dmg, this); s1 = new ShurikenProjectile(x1, y1, (float) (x2 - 80 * Math.sin(s0.getTheta())), (float) (y2 + 80 * Math.cos(s0.getTheta())), dmg, this); s2 = new ShurikenProjectile(x1, y1, (float) (x2 + 80 * Math.sin(s0.getTheta())), (float) (y2 - 80 * Math.cos(s0.getTheta())), dmg, this); if(Origin == "Enemy"){ Play.getEnemyProjectiles().add(s1); Play.getEnemyProjectiles().add(s2); } else { Play.getProjectiles().add(s1); Play.getProjectiles().add(s2); } return new ShurikenProjectile(x1, y1, x2, y2, dmg, this); } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.Player; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Item; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.pos; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; import java.util.Arrays; /** * Created by Taylor on 2/18/2017. */ public class AOEeffect extends Projectile { float stateTime; int distance; int endDist; int count; int count1; private String origin; Player.FACE dir; final int NUM = 19; // MUST BE ODD; boolean [][]aoe; pos[][]AOE; public AOEeffect(float x1, float y1, Player.FACE dir, float dmg, int distance, Item fromItem, int count1, String Origin){ origin = Origin; aoe = new boolean[NUM][NUM]; for(int i = 0; i < NUM; i++) Arrays.fill(aoe[i], false); aoe[NUM/2][NUM/2] = true; // WHERE YOU ARE AOE = new pos[NUM][NUM]; this.fromItem = fromItem; this.count1 = count1; this.dmg = dmg; this.dir = dir; this.distance = distance; count = 8; endDist = 190 - distance; sprite = new Sprite(spriteTextures.basic64); stateTime = 0f; x = Player.CharX+16; y = Player.CharY-16; float left = x + (32 * NUM/2); float top = y + (left - x); for(int i = 0; i < NUM; i++) for(int j = 0; j < NUM; j++) AOE[i][j] = new pos(left - i*32, top - j*32); } private boolean[][] getState(){ boolean [][] state; state = new boolean[NUM][NUM]; for(int i = 0; i< NUM; i++){ for(int j = 0; j <NUM; j++) state[i][j] = aoe[i][j]; } return state; } public void expand(){ boolean [][] cpy = getState(); if(!aoe[0][NUM/2]) { for (int i = 0; i < NUM; i++) for (int j = 0; j < NUM; j++) { if ((j < (NUM - 1)) && cpy[i][j + 1]) { // BELOW aoe[i][j] = true; } else if ((i > 0) && cpy[i - 1][j]) { // LEFT aoe[i][j] = true; } else if ((i < (NUM - 1)) && cpy[i + 1][j]) { // RIGHT aoe[i][j] = true; } else if ((j > 0) && cpy[i][j - 1]) { //ABOVE aoe[i][j] = true; } } } else if (count == 8){ count = 6; } else{ count = 4; distance+=35; } } @Override public void contact() { fromItem.setItemXP(fromItem.getItemXP() + 1); /** Checks for item Level Up */ if(fromItem.getItemXP() >= fromItem.getXPtoLVL()){ fromItem.LVLup(); fromItem.setXPtoLVL(fromItem.getXPtoLVL() * 2); System.out.println("ITEM LEVELED UP"); } } @Override public void draw() { distance ++; stateTime += Gdx.graphics.getDeltaTime(); if(count != 4) for(int i = 0; i < NUM; i++){ for(int j = 0; j < NUM; j++){ if(aoe[i][j]) { if(origin != "Enemy") { if (count == 8) Play.getProjectiles().add(new singleMagicStrike(AOE[i][j].getPOSX(), AOE[i][j].getPOSY(), dmg, fromItem, count1, stateTime, 2)); else { Play.getProjectiles().add(new singleMagicStrike(AOE[i][j].getPOSX(), AOE[i][j].getPOSY(), dmg, fromItem, count1, stateTime, 3)); } } else{ if (count == 8) Play.getEnemyProjectiles().add(new singleMagicStrike(AOE[i][j].getPOSX(), AOE[i][j].getPOSY(), dmg, fromItem, count1, stateTime, 2)); else { Play.getEnemyProjectiles().add(new singleMagicStrike(AOE[i][j].getPOSX(), AOE[i][j].getPOSY(), dmg, fromItem, count1, stateTime, 3)); } } } } } else{ remove(); } if(((int)distance % (int)count == 0)){ expand(); } } } <file_sep>package onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.projectiles; import com.badlogic.gdx.graphics.g2d.Sprite; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.items.Item; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.entities.spriteTextures; import onion.szxb74om7zsmd2jm.limitlesslabyrinth.screens.Play; /** * Created by 226812 on 2/23/2017. */ public class SwordProjectile extends Projectile { public SwordProjectile(float x1, float y1, float x2, float y2, float dmg, Item fromItem){ this.fromItem = fromItem; this.dmg = dmg; time = System.currentTimeMillis() + 50; sprite = new Sprite(spriteTextures.swordProjectileSprite); slope = ((y2 - y1)/(x2 - x1)); x = x1; y = y1; b = y1 - slope * x1; endX = x2; endY = y2; theta = Math.atan(slope); sprite.rotate((float) Math.toDegrees(theta)); sprite.flip(true, false); if(endX > x){ direction = true; } else{ direction = false; theta *= -1; sprite.flip(true, false); } if(endY < y){ theta *= -1; sprite.flip(false, true); } } @Override public void contact() { fromItem.setItemXP(fromItem.getItemXP() + 1); /** Checks for item Level Up */ if(fromItem.getItemXP() >= fromItem.getXPtoLVL()){ fromItem.LVLup(); fromItem.setXPtoLVL(fromItem.getXPtoLVL() * 2); System.out.println("ITEM LEVELED UP"); } //remove(); } @Override public void draw() { sprite.setPosition(x, y); sprite.draw(Play.getRenderer().getBatch()); if(direction){ x += Math.cos(theta) * 10; } else{ x -= Math.cos(theta) * 10; } y = slope * x + b; } }
3f7edab2e31b6cd2f9c59b6feabc8e15c3f57c26
[ "Java" ]
26
Java
ErikTheCleric/OVERSTORY
8274b447a6799c05de09c6d51f9eec98629eac76
dc128ab68714d437b597da18ce1e93f47fc2f436
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\User; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; use Overtrue\EasySms\EasySms; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } public function login() { return view('auth.phonelogin'); } public function LoginData(){ $key = 'login.code.'.request()->phone; //判断缓存是否存在这个key并取出来和用户的对比 if(Cache::has($key) && Cache::get($key) == request()->code){ $user =User::firstOrcreate([ 'phone'=>request()->phone, ],[ 'name'=>request()->phone, 'phone'=>request()->phone ]); Auth::login($user); return redirect('/'); } return back(); } public function sendLoginPhoneCode() { $phone =request()->phone; $code = random_int('1000','9999'); $time=30; //写入缓存 Cache::put('login.code.'.$phone,$code,1); // dd($phone); //jia 判断缓存中是否有验证码了,有就直接返回信息状态说明验证码已经存在,在规定时间内不能再发送,防止csrf攻击 $easySms = new EasySms(config('sms')); $data =$easySms->send($phone, [ 'template' => '1', 'data' => [ $code, $time ], ]); return response()->json([ 'status'=>'success', 'code'=>$code ]); // return response()->json([ // 'status'=>'failed' // ]); } }
25b5e27f78e04bb250bc8a489fee3447338e67f1
[ "PHP" ]
1
PHP
xiaodiyi/phone
9e1d3791de4f863c380ed0cd7333e9c0b2387cb0
be4012de45957258029fc5dc04c05264564e5071
refs/heads/master
<file_sep>Statistical_Models_Central_Limit_Theorem ========================================= Write an R-script that transforms the data to sum across all zip codes in the Chicago Diabetes Hospital Data Set. Make a model that plots and fits a line to the following: Number of Hospitalizations vs. Crude Admittance Rate. Change in Number of Hospitalizations vs. Change in Crude Admittance Rate Be sure to interpret the slopes for each model (Some good examples here: http://www.austincc.edu/mparker/1342/lessons/less5-8/interpret_slope.pdf) Comment on the differences in R^2 between the two- what does this mean <file_sep>################################################################################################# ## <NAME> # ## HOMEWORK 4 : Chicago Diabetes Homework (Lecture 4) # ## 04/28/16 # ## Class: Methods for Data Analysis # ## # ################################################################################################# ## Clear objects from Memory : rm(list=ls()) ##Clear Console: cat("\014") ## Get the libraries library(logging) # Get the log file name that has a date-time in the name get_log_filename = function(){ log_file_name = format(Sys.time(), format="HW4_log_%Y_%m_%d_%H%M%S.log") return(log_file_name) } # Unit test to check that log file name doesn't exist test_log_file_name_uniqueness = function(log_file_name){ all_files = list.files() stopifnot(!log_file_name%in%all_files) } if (interactive()){ # Get logger file name log_file_name = get_log_filename() basicConfig() addHandler(writeToFile, file=log_file_name, level='INFO') # Test for uniqueness test_log_file_name_uniqueness(log_file_name) # Setup working directory setwd('~/DataAnalysis/4_HypothesisTesting_CentralLimit/') #Define the slope function based on the first and the last values slope <-function(x1,x2,y1,y2){ (y1-y2)/(x1-x2) } # Define the y-intercept function (Pick a point, and calculate the y-intercept based on the slope): # b = y - mx y_int<-function(x1,y1,slope_guess){ (y1-slope_guess*x1) } # Get the data and orginize it data = read.csv('ChicagoDiabetesData.csv', stringsAsFactors = FALSE) data_sums = apply(data[-1],2,sum) hospitalizations = data_sums[grepl('Hospitalizations', names(data_sums))] admit_rate = data_sums[grepl('Crude.Rate.[0-9]+$', names(data_sums), perl = TRUE)] ######################################################################### # Part I : Num. Hospitalizations vs. Crude Admittance Rate ######################################################################### hospitalizations_order = hospitalizations[order(admit_rate)] admit_rate_order = admit_rate[order(admit_rate)] plot(hospitalizations, admit_rate, main="Part I : Num. Hospitalizations vs. Crude Admittance Rate") # Calculate the slope & the y-intercept x1 <-hospitalizations_order[[1]] x2 <-hospitalizations_order [[length(hospitalizations_order)]] y1 <-admit_rate_order[[1]] y2 <-admit_rate_order[[length(admit_rate_order)]] slope_guess_I = slope(x1,x2,y1,y2) y_int_guess_I = y_int(x1,y1,slope_guess_I) ## add the linear .... abline(y_int_guess_I, slope_guess_I, col="gray23",lty=2) ## Calculate the SSE i = 0 true_y = 0 SSE = 0 x = 0 y = 0 for (i in 1:length(admit_rate_order)){ y[i]<-admit_rate_order[[i]] x[i]<-hospitalizations_order[[i]] true_y[i] <- (y_int_guess_I + slope_guess_I*x[[i]]) } SSE = sum((y-true_y)^2) ## Calculate the SST y_avg = rep(mean(true_y), length(x)) SST = sum((y - y_avg)^2) ## Calculate the R^2, this value is interpreted as # the % of variance explained in the model (more than the average) R_SQR = 1 - SSE/SST ##-----Least Squares Regression in R----- best_fit_line = lm(y~x) summary(best_fit_line) ## add the best fit line to the graph abline(best_fit_line,col="red") # add the mean line to the graph y_mean = rep(mean(y), length(x)) lines(x, y_mean, col="blue") legend("topleft", c("predicted curve","best fit", "mean line"), fill=c("gray","red", "blue")) grid() ## Part-I Results Slope_I = slope_guess_I SSE_I = SSE SST_I = SST R_SQR_I = R_SQR ######################################################################### # Part II : Delta Num. Hospitalizations vs. Delta Crude Admittance Rate # ######################################################################### hospitalizations_diff = diff(hospitalizations) admit_rate_diff = diff(admit_rate) hospitalizations_order = hospitalizations_diff[order(admit_rate_diff)] admit_rate_order = admit_rate_diff[order(admit_rate_diff)] plot(hospitalizations_diff, admit_rate_diff, main="Part II : Delta Num. Hospitalizations vs. Delta Crude Admittance Rate") # Calculate the slope & the y-intercept : x1 <-hospitalizations_order[[1]] x2 <-hospitalizations_order [[length(hospitalizations_order)]] y1 <-admit_rate_order[[1]] y2 <-admit_rate_order[[length(admit_rate_order)]] slope_guess_II = slope(x1,x2,y1,y2) y_int_guess_II = y_int(x1,y1,slope_guess_II) abline(y_int_guess_II, slope_guess_II,col="gray23",lty=2) ## Calculate the SSE i = 0 true_y = 0 SSE = 0 x = 0 y = 0 for (i in 1:length(admit_rate_order)){ y[i]<-admit_rate_order[[i]] x[i]<-hospitalizations_order[[i]] true_y[i] <- (y_int_guess_II + slope_guess_II*x[[i]]) } SSE = sum((y-true_y)^2) ## Calculate the SST y_avg = rep(mean(true_y), length(x)) SST = sum((y - y_avg)^2) ## Calculate the R^2, this value is interpreted as # the % of variance explained in the model (more than the average) R_SQR = 1 - SSE/SST ##-----Least Squares Regression in R----- best_fit_line = lm(y~x) summary(best_fit_line) ## add the best fit line to the graph abline(best_fit_line,col="red") # add the mean line to the graph y_mean = rep(mean(y), length(x)) lines(x, y_mean, col="blue") legend("topleft", c("predicted curve","best fit", "mean line"), fill=c("gray","red", "blue")) grid() ## Part-II Results Slope_II = slope_guess_II SSE_II = SSE SST_II = SST R_SQR_II = R_SQR # Log Results loginfo(paste('PART I \n',' "Hospitalizations" is the total number of people discharged from hospitals (irrespective of their health/disease status)\n', '"Crude Admittance" is the number discharged with diabetes. Both numbers are "per 10,000"\n', 'The Ratio between Hospitalizations vs. Crude Admittance Rate ~',Slope_I , '\n which means If the the total number of people discharged from hospitals goes up by 10,000 then the number discharged with diabetes goes up by', Slope_I*10000, '\n The SSE value is', SSE_I,' \n The SST value is', SST_I, '\n and the R Square value is obtained as', R_SQR_I, '\n which means that predicted linear regression line can approximates the', R_SQR_I*100, '% of the data points ')) loginfo(paste('PART II \n','The annual change between Num. Hospitalizations vs. Crude Admittance Rate ~',Slope_II, '\n which means the annual change in the total number of discharges goes up by 10,000 then the annual change in discharges with diabetes goes up by', Slope_II*10000, '\n The SSE value is', SSE_II,' \n The SST value is', SST_II, '\n and the R Square value is obtained as', R_SQR_II, '\n which means that predicted linear regression line can approximates the', R_SQR_II*100, '% of the data points ')) } ############################# End #############################
fe0ca9c4e08810f15b11fc63498e3040d0589cc8
[ "Markdown", "R" ]
2
Markdown
ozemreozdemir/Statistical_Models_Central_Limit_Theorem_1
756c150cfc987de764b23161656500acd38a59de
c96f6ff259077671acdcdf4cf91655a9998ff895
refs/heads/master
<repo_name>Rani-Salma-git/CSE-204<file_sep>/Assignment-03.cpp #include <bits/stdc++.h> using namespace std; struct node{ int item; node* next; }; node* root = NULL; void Insert(int x){ node* temp = new node; if(root == NULL){ temp->item = x; temp->next = NULL; root = temp; } else{ temp->item = x; temp->next = root; root = temp; } cout<<"\n"<<x<<" is inserted successfully!"<<endl; } void Search(int x){ node* temp = root; while(temp != NULL){ if(temp->item == x){ cout<<"\n"<<x<<" is present is the list!"<<endl; return; } temp = temp->next; } cout<<"\n"<<x<<" is not present is the list!"<<endl; } void Delete(int x){ node *temp = root, *prev = root; while(temp != NULL){ if(temp->item == x){ if(temp == root) root = temp->next; else prev->next = temp->next; delete temp; cout<<"\n"<<x<<" is successfully deleted from the list!"<<endl; return; } prev = temp; temp = temp->next; } cout<<"\n"<<x<<" is not present in the list. So deletion is not possible!"<<endl; } void show_list() { cout<<"LIST: "; node* temp = root; while(temp != NULL){ cout<<temp->item<<" "; temp = temp->next; } cout<<"\n\n"; } int main() { int x, command; cout<<"MENU:: 1.Insertion 2.Searching 3.Delete 0.Exit"<<endl; cout<<"Enter command ID: "; while(cin>>command && command){ if(command == 1){ cout<<"Enter value to be inserted: "; cin>>x; Insert(x); show_list(); } else if(command == 2){ cout<<"Enter value to be searched: "; cin>>x; Search(x); show_list(); } else if(command == 3){ cout<<"Enter value to be deleted: "; cin>>x; Delete(x); show_list(); } else cout<<"Enter valid command!"<<endl; cout<<"MENU:: 1.Insertion 2.Searching 3.Delete 0.Exit"<<endl; cout<<"Enter command ID: "; } return 0; } <file_sep>/README.md # CSE-204 Assignment submission <file_sep>/Assignment -02.cpp #include <bits/stdc++.h> using namespace std; int main() { string a = "PEOPLE"; int comparisons = 0 , interchanges = 0; for(int i=0; i+1<6; i++){ for(int j=0; j+i+1<6; j++){ comparisons++; if(a[j] >= a[j+1]){ swap(a[j], a[j+1]); interchanges++; } } } cout<<"Sorted string: "<<a<<endl; cout<<"Comparisons: "<<comparisons<<"\n"<<"Interchanges: "<<interchanges<<endl; int data[] = {11, 22, 30, 33, 40, 44, 55, 60, 66, 77, 80, 88, 99}; int x; cout<<"Enter item to be searched: "; cin>>x; int Beg = 0, End = 13, Mid; bool found = false; while(Beg<=End){ Mid = (Beg+End)/2; if(data[Mid] == x){ cout<<a<<" is found at position: "<<Mid+1<<endl; found = true; break; } else if(data[Mid] > x) End = Mid - 1; else Beg = Mid + 1; } if(found == false) cout<<x<<" is not present in the data!"<<endl; return 0; }
9d06e854b3cb73e54fcc99333c32e1fc57056d13
[ "Markdown", "C++" ]
3
C++
Rani-Salma-git/CSE-204
019e03b221522d65486281e9c092bf0cd6a176a4
0fdae078f5cf450fae35b2f3d232daa2f60c96ff
refs/heads/master
<repo_name>bscode/rssnaps<file_sep>/README.md # rssnaps simple backup script based on rsync ## Usage ``` rssnaps [<switches>] <target> <switches>: -h --help show this help -r --resync refresh most recent snapshot -k --anykey wait for any key after backup -s --shutdown shutdown system after backup ``` ## Configuration The target location requires a configuration file named `rssnaps.cfg`, where you define the paths that you want to backup and some additional options. You can use the provided one as an example. ``` # rssnaps.cfg configuration # paths that you want to backup sources = /etc /home # additional arguments passed to rsync, like excluding some specific folders options = --exclude=lost+found/ --exclude=.gvfs/ # minimum free disk space to keep at the target location (allowed suffixes: K M G T P E Z Y) min_free = 2G # maximum number of snapshots to keep max_snapshots = 30 ``` <file_sep>/rssnaps #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # rssnaps # # Copyright (C) 2014, 2015 BusyCode # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys, os, subprocess, shlex, shutil, datetime class rssnaps(): opt_resync = False opt_pause = False opt_shutdown = False destination = None cfg_sources = None cfg_options = None cfg_min_free = 0 cfg_max_snaps = 30 _depencies = ["rsync"] def __init__(self): self.check_depencies() def help(self): print("Usage: rssnaps [<switches...>] <target>") print("") print("<switches>:") print("-h --help show this help") print("-r --resync refresh most recent snapshot") print("-k --anykey wait for any key after backup") print("-s --shutdown shutdown system after backup") print("") sys.exit() def log(self, message): now = datetime.datetime.now() print(now.strftime("[%H:%M:%S] ") + message) def error(self, message): sys.exit("ERROR: "+message) def warn(self, message): print("WARNING: "+message) def call(self, command, log=None): try: subprocess.Popen(shlex.split(command), stdout=log, stderr=log).communicate() finally: pass def shell(self, command): subprocess.call(command, shell=True) def check_depencies(self): for cmd in self._depencies: command = shlex.split(cmd) try: with open(os.devnull, "w") as devnull: subprocess.Popen(command, stdout=devnull, stderr=devnull).communicate() except: self.error(command[0]+" not found") def pause(self): if (os.name == 'posix'): import termios, tty print("Press any key to continue ...") stdin_fd = sys.stdin.fileno() stdin_attr = termios.tcgetattr(stdin_fd) try: tty.setraw(stdin_fd) sys.stdin.read(1) finally: termios.tcsetattr(stdin_fd, termios.TCSADRAIN, stdin_attr) elif (os.name == 'nt'): self.shell("pause") else: self.error("pause() not supported on this platform") def shutdown(self): if (os.name == 'posix'): self.shell("shutdown -h now") elif (os.name == 'nt'): self.shell("shutdown -s") else: self.error("shutdown() not supported on this platform") def get_space(self, path): if (os.name == 'posix'): stat = os.statvfs(path) return (stat.f_frsize * stat.f_bavail) elif (os.name == 'nt'): import ctypes free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes)) return free_bytes.value else: self.error("get_space() not supported on this platform") def sync(self): try: os.sync() finally: pass def int(self, string): try: return int(float(string)) except: self.error("Invalid settings, please check your configuration") def format_bytes(self, size): if (size < 1024): return "{0} bytes".format(size) elif (size < 1048576): return "{0:.1f} KiB".format(size / 1024) elif (size < 1073741824): return "{0:.1f} MiB".format(size / 1048576) elif (size < 1099511627776): return "{0:.1f} GiB".format(size / 1073741824) elif (size < 1125899906842624): return "{0:.1f} TiB".format(size / 1099511627776) elif (size < 1152921504606846976): return "{0:.1f} PiB".format(size / 1125899906842624) elif (size < 1180591620717411303424): return "{0:.1f} EiB".format(size / 1152921504606846976) elif (size < 1208925819614629174706176): return "{0:.1f} ZiB".format(size / 1180591620717411303424) else: return "{0:.1f} YiB".format(size / 1208925819614629174706176) def parse_config(self, path): if (os.path.isfile(path)): with open(path, "r") as cfgfile: for line in cfgfile: pair = line.strip().split("=", 1) if (len(pair) > 1): key = pair[0].rstrip() val = pair[1].lstrip() if (key == "sources"): self.cfg_sources = val elif (key == "options"): self.cfg_options = val elif (key == "min_free"): suffix = val[-1:].upper() if (suffix == "K"): val = self.int(val[:-1]) * 1024 elif (suffix == "M"): val = self.int(val[:-1]) * 1024 * 1024 elif (suffix == "G"): val = self.int(val[:-1]) * 1024 * 1024 * 1024 elif (suffix == "T"): val = self.int(val[:-1]) * 1024 * 1024 * 1024 * 1024 elif (suffix == "P"): val = self.int(val[:-1]) * 1024 * 1024 * 1024 * 1024 * 1024 elif (suffix == "E"): val = self.int(val[:-1]) * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 elif (suffix == "Z"): val = self.int(val[:-1]) * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 elif (suffix == "Y"): val = self.int(val[:-1]) * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 else: val = self.int(val) self.cfg_min_free = max(val, 0) elif (key == "max_snapshots"): val = self.int(val) self.cfg_max_snaps = max(val, 1) else: self.error("Could not find \"{0}\".".format(path)) def parse_args(self, args): for a in args: if (a == "-h" or a == "--help"): self.help() elif (a == "-r" or a == "--resync"): self.opt_resync = True elif (a == "-k" or a == "--anykey"): self.opt_pause = True elif (a == "-s" or a == "--shutdown"): self.opt_shutdown = True elif (os.path.isdir(a) and self.destination == None): self.destination = os.path.abspath(a) self.parse_config(os.path.join(self.destination, "rssnaps.cfg")) def do_backup(self): if (self.cfg_sources == None): self.error("No source folders defined, please check your configuration") if (self.cfg_options == None): self.cfg_options = "" path_prefix = os.path.join(self.destination, "snapshot.") path_logfile = os.path.join(path_prefix+"0", "rsync.log") path_linkdest = None if (not self.opt_resync): self.log("rotating snapshots") for i in range(self.cfg_max_snaps-1, -1, -1): if (os.path.isdir("{0}{1}".format(path_prefix, i))): shutil.move("{0}{1}".format(path_prefix, i), "{0}{1}".format(path_prefix, i+1)) i = self.cfg_max_snaps while (os.path.isdir("{0}{1}".format(path_prefix, i))): self.log("removing snapshot #{0}".format(i)) shutil.rmtree("{0}{1}".format(path_prefix, i), True) i += 1 for i in range(self.cfg_max_snaps-1, 1, -1): freespace = self.get_space(self.destination) if (freespace >= self.cfg_min_free): break if (os.path.isdir("{0}{1}".format(path_prefix, i))): self.log("low disk space ({1}), removing snapshot #{0}".format(i, self.format_bytes(freespace))) shutil.rmtree("{0}{1}".format(path_prefix, i), True) self.sync() if (os.path.isdir(path_prefix+"1")): path_linkdest = path_prefix+"1" self.log("creating new snapshot") else: self.log("refreshing most recent snapshot") freespace = self.get_space(self.destination) if (freespace < self.cfg_min_free): self.warn("Low disk space at destination ({0})".format(self.format_bytes(freespace))) if (not os.path.isdir(path_prefix+"0")): os.mkdir(path_prefix+"0") with open(path_logfile, "a") as logfile: if (path_linkdest != None): self.call("rsync -avR --delete {0} --link-dest=\"{1}\" {2} \"{3}\"".format(self.cfg_options, path_linkdest, self.cfg_sources, path_prefix+"0"), logfile) else: self.call("rsync -avR --delete {0} {1} \"{2}\"".format(self.cfg_options, self.cfg_sources, path_prefix+"0"), logfile) os.utime(path_prefix+"0", None) self.sync self.log("backup done") if __name__ == '__main__': app = rssnaps() app.parse_args(sys.argv[1:]) if (app.destination == None): app.help() else: app.do_backup() if (app.opt_pause): print("") app.pause() if (app.opt_shutdown): app.shutdown()
57428404849725fdf1ad3d8d1c6c7f55baa6d4a5
[ "Markdown", "Python" ]
2
Markdown
bscode/rssnaps
cabedbfebfc719d25f899906b1c38fe8c730414b
2c75e0e6650ab93a2332c48b28e88e8415d46a3c
refs/heads/master
<file_sep># spark-install > Cross-platform installer for Apache Spark. This project provides a cross-platform installer for Apache Spark designed to use system resources efficiently under a common API. This initial version comes with support for R and Python that arose from a collaboration between [RStudio](https://www.rstudio.com) and [Microsoft](https://www.microsoft.com). ## R ```r # install from github devtools::install_github(repo = "rstudio/spark-install", subdir = "R") library(sparkinstall) # lists the versions available to install spark_available_versions() # installs an specific version spark_install(version = "1.6.2") # uninstalls an specific version spark_uninstall(version = "1.6.2", hadoop_version = "2.6") ``` ## Python ```py # install from github from urllib import urlopen # Python 2.X from urllib.request import urlopen # Python 3.X exec urlopen("https://raw.githubusercontent.com/rstudio/spark-install/master/Python/spark_install.py").read() in globals() # lists the versions available to install spark_versions() # installs an specific version spark_install(spark_version = "1.6.2") # uninstalls an specific version spark_uninstall(spark_version = "1.6.2", hadoop_version = "cdh4") ``` <file_sep>starts_with <- function(lhs, rhs) { if (nchar(lhs) < nchar(rhs)) return(FALSE) identical(substring(lhs, 1, nchar(rhs)), rhs) } aliased_path <- function(path) { home <- path.expand("~/") if (starts_with(path, home)) path <- file.path("~", substring(path, nchar(home) + 1)) path } <file_sep>import os import shutil def main(): from pyspark.context import SparkContext from operator import add # Clean up previous results that can cause failure if os.path.isdir(os.path.join(os.getcwd(), "wc_out")): shutil.rmtree(os.path.join(os.getcwd(), "wc_out")) #print(os.environ.get("SPARK_HOME")) sc = SparkContext(appName="HelloWorld") f = sc.textFile("test_word_count.txt") wc = f.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add) wc.saveAsTextFile("wc_out") # Check if results files exist and raise error if they do not. if os.path.isdir(os.path.join(os.getcwd(), "wc_out")): print("Test succeeded, results files are present for word count.") else: # print("Test failed, no results files were found for word count.") raise ValueError("test_word_count.py has Failed.") if __name__ == "__main__": main()<file_sep>context("spark_install") test_that("spark_install can install and uninstall", { skip_on_cran() spark_install(version = "1.6.2", hadoop_version = "2.6") spark_uninstall(version = "1.6.2", hadoop_version = "2.6") }) <file_sep>#' @rdname spark_install #' @export spark_configure <- function(spark_home) { if (.Platform$OS.type == "windows") prepare_windows_environment(spark_home) } <file_sep>#Introduction This Python script is intended to provide a smooth, cross-platform installation experience for PySpark. #Getting Started Python 2.7 or 3.5 is required to execute this script. If installing on Python 3.6, ensure you choose Spark version 2.1.1 or higher (see [SPARK-19109](https://issues.apache.org/jira/browse/SPARK-19019)). Running the script with no parameters will grab the latest Spark/Hadoop combination version available. Command line options -s and -h (or --spark-version and --hadoop-version) allow the user to specify exactly which version pairing to use. Invalid pairings will present the list of valid options to the user. #Build and Test #Contribute <file_sep>SPARK_VERSIONS_FILE_PATTERN = "spark-(.*)-bin-(?:hadoop)?(.*)" SPARK_VERSIONS_URL = "https://raw.githubusercontent.com/rstudio/sparklyr/master/inst/extdata/install_spark.csv" WINUTILS_URL = "https://github.com/steveloughran/winutils/archive/master.zip" NL = os.linesep def _verify_java(): import subprocess try: import re output = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT) logger.debug(output) match = re.search(b"(\d+\.\d+)", output) if match: logger.debug("Found a match") if match.group() == b'1.8': logger.info("Found Java version 8, continuing.") return True else: logger.info("Did not detect Java Version 8, please install Java 8 before continuing.") return False else: logger.info("Java could not be detected on this system, please install Java 8 before continuing.") return False except: logger.info("Warning: Java was not found in your path. Please ensure that Java 8 is configured correctly otherwise launching the gateway will fail") return False def _file_age_days(csvfile): from datetime import datetime ctime = os.stat(csvfile).st_ctime return (datetime.fromtimestamp(ctime) - datetime.now()).days def _combine_versions(spark_version, hadoop_version): return spark_version + " " + hadoop_version def _download_file(url, local_file): try: from urllib import urlretrieve except ImportError: from urllib.request import urlretrieve urlretrieve(url, local_file) def spark_can_install(): install_dir = spark_install_dir() if not os.path.isdir(install_dir): os.makedirs(install_dir) def spark_versions_initialize(): spark_can_install() csvfile = os.path.join(spark_install_dir(), "install_spark.csv") if not os.path.isfile(csvfile) or _file_age_days(csvfile) > 30: logger.info("Downloading %s to %s" % (SPARK_VERSIONS_URL, csvfile)) _download_file(SPARK_VERSIONS_URL, csvfile) import csv return [{"spark_version": t[0], "hadoop_version": t[1], "hadoop_label": t[2], "download": t[3], "default": (t[4].strip() == "TRUE"), "hadoop_default": (t[5].strip == "TRUE")} for t in csv.reader(open(csvfile, "r").readlines()[1:]) if len(t) == 6] def spark_versions(): versions = spark_versions_initialize() installed = set([_combine_versions(v["spark_version"], v["hadoop_version"]) for v in spark_installed_versions()]) for v in versions: v["installed"] = _combine_versions(v["spark_version"], v["hadoop_version"]) in installed return versions def spark_versions_info(spark_version, hadoop_version): versions = filter(lambda v: v["spark_version"] == spark_version and v["hadoop_version"] == hadoop_version, spark_versions()) versions = list(versions) if len(versions) == 0: raise ValueError("Unable to find Spark version: %s and Hadoop version: %s" % (spark_version, hadoop_version)) component_name = "".join(("spark-", spark_version, "-bin-hadoop", hadoop_version)) #CDH4 Hadoop version has different file naming convention. if hadoop_version == "cdh4": component_name = "".join(("spark-", spark_version, "-bin-", hadoop_version)) package_name = component_name + ".tgz" package_remote_path = versions[0]["download"] return {"component_name": component_name, "package_name": package_name, "package_remote_path": package_remote_path} def spark_installed_versions(): base_dir = spark_install_dir() versions = [] for candidate in os.listdir(base_dir): match = re.match(SPARK_VERSIONS_FILE_PATTERN, candidate) fullpath = os.path.join(base_dir, candidate) if os.path.isdir(fullpath) and match: versions.append({"spark_version": match.group(1), "hadoop_version": match.group(2), "dir": fullpath}) return versions def spark_install_available(spark_version, hadoop_version): info = spark_versions_info(spark_version, hadoop_version) return os.path.isdir(info["spark_version_dir"]) def spark_install_find(spark_version=None, hadoop_version=None, installed_only=True, connecting=False): versions = spark_versions() if installed_only: versions = filter(lambda v: v["installed"], versions) if spark_version: versions = filter(lambda v: v["spark_version"] == spark_version, versions) if hadoop_version: versions = filter(lambda v: v["hadoop_version"] == hadoop_version, versions) versions = list(versions) if len(versions) == 0: if connecting: import csv csvfile = os.path.join(spark_install_dir(), "install_spark.csv") eligibleVersionPairings = [{"sparkversion": t[0], "hadoopversion": t[1]} for t in csv.reader(open(csvfile, "r").readlines()[1:]) if len(t) == 6] logging.debug("Available Spark and Hadoop version pairings: ") for elem in eligibleVersionPairings: logging.debug(elem) raise RuntimeError("Use spark_install(%s, %s) to install Spark" % (spark_version, hadoop_version)) else: logger.critical("Please select an available version pair for Spark and Hadoop from the following list: ") import csv csvfile = os.path.join(spark_install_dir(), "install_spark.csv") eligibleVersionPairings = [{"--spark-version": t[0], "--hadoop-version": t[1]} for t in csv.reader(open(csvfile, "r").readlines()[1:]) if len(t) == 6] for elem in eligibleVersionPairings: logging.critical(elem) raise RuntimeError("Please select a valid pair of Spark and Hadoop versions to download.") candidate = sorted(versions, key=lambda rec: rec["spark_version"] + " " + rec["hadoop_version"])[-1] return spark_install_info(candidate["spark_version"], candidate["hadoop_version"]) def spark_default_version(): if len(spark_installed_versions()) > 0: version = spark_install_find() else: version = filter(lambda v: v["default"] and v["hadoop_default"], read_spark_versions_csv())[0] return {"spark_version": version["spark_version"], "hadoop_version": version["hadoop_version"]} def spark_install_info(spark_version=None, hadoop_version=None): info = spark_versions_info(spark_version, hadoop_version) component_name = info["component_name"] package_name = info["package_name"] package_remote_path = info["package_remote_path"] spark_dir = spark_install_dir() spark_version_dir = os.path.join(spark_dir, component_name) return {"spark_dir": spark_dir, "package_local_path": os.path.join(spark_dir, package_name), "package_remote_path": package_remote_path, "spark_version_dir": spark_version_dir, "spark_conf_dir": os.path.join(spark_version_dir, "conf"), "spark_version": spark_version, "hadoop_version": hadoop_version, "installed": os.path.isdir(spark_version_dir)} def spark_uninstall(spark_version, hadoop_version): logger.debug("Inside uninstall routine.") info = spark_versions_info(spark_version, hadoop_version) spark_dir = os.path.join(spark_install_dir(), info["component_name"]) shutil.rmtree(spark_dir, ignore_errors=True) logger.debug("File tree removed.") def spark_install_dir(): homedir = os.getenv("LOCALAPPDATA") if sys.platform == "win32" else os.getenv("HOME") return os.getenv("SPARK_INSTALL_DIR", os.path.join(homedir, "spark")) def spark_conf_log4j_set_value(install_info, properties, reset): log4jproperties_file = os.path.join(install_info["spark_conf_dir"], "log4j.properties") if not os.path.isfile(log4jproperties_file) or reset: template = os.path.join(install_info["spark_conf_dir"], "log4j.properties.template") shutil.copyfile(template, log4jproperties_file) with open(log4jproperties_file, "r") as infile: lines = infile.readlines() for i in range(len(lines)): if lines[i].startswith("#") or "=" not in lines[i]: continue k, v = lines[i].split("=") lines[i] = "=".join((k, properties.get(k, v))) if k in properties: del properties[k] with open(log4jproperties_file, "w") as outfile: outfile.writelines([line + NL for line in lines]) #Now write out values in Properties that didn't have base values in the template for key, value in properties.items(): newline = "=".join((key, value)) outfile.writelines([newline + NL]) def spark_hive_file_set_value(hive_path, properties): with open(hive_path, "w") as hive_file: hive_file.write("<configuration>" + NL) for k, v in properties.items(): hive_file.write(NL.join([" <property>", " <name>" + k + "</name>", " <value>" + str(v) + "</value>", " </property>" + NL])) hive_file.write("</configuration>" + NL) def spark_conf_file_set_value(install_info, properties, reset): spark_conf_file = os.path.join(install_info["spark_conf_dir"], "spark-defaults.conf") if not os.path.isfile(spark_conf_file) or reset: template = os.path.join(install_info["spark_conf_dir"], "spark-defaults.conf.template") shutil.copyfile(template, spark_conf_file) max_key_len = 35 with open(spark_conf_file, "r") as infile: lines = infile.readlines() for i in range(len(lines)): if lines[i].startswith("#") or " " not in lines[i]: continue k, v = lines[i].split() lines[i] = ' '.join((k.lpad(max_key_len), properties.get(k, v))) with open(spark_conf_file, "w") as outfile: outfile.writelines([line + NL for line in lines]) def spark_set_env_vars(spark_version_dir): import glob zipfiles = glob.glob(os.path.join(spark_version_dir, "python", "lib", "*.zip")) if zipfiles != [] and zipfiles[0] not in sys.path: position = [index for (index, path) in enumerate(sys.path) if re.match(SPARK_VERSIONS_FILE_PATTERN, path)] or len(sys.path) sys.path = sys.path[:position] + zipfiles + sys.path[position:] persistent_vars = {} path_delim = ";" if sys.platform == "win32" else ":" path_values = os.environ.get("PYTHONPATH", "").split(path_delim) if zipfiles != [] and zipfiles[0] not in path_values: position = [index for (index, path) in enumerate(path_values) if re.match(SPARK_VERSIONS_FILE_PATTERN, path)] or len(path_values) path_values = path_values[:position] + zipfiles + path_values[position:] os.environ["PYTHONPATH"] = path_delim.join(path_values) persistent_vars["PYTHONPATH"] = path_delim.join(path_values) if os.environ.get("SPARK_HOME", "") != spark_version_dir: os.environ["SPARK_HOME"] = spark_version_dir persistent_vars["SPARK_HOME"] = spark_version_dir if persistent_vars == {}: return if sys.platform == "win32": try: import _winreg as winreg except ImportError: import winreg logger.info("Setting the following variables in your registry under HKEY_CURRENT_USER\\Environment:") for k, v in persistent_vars.items(): logger.info("%s = %s (REG_SZ)" % (k, v)) with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_SET_VALUE) as hkey: for value, value_data in persistent_vars.items(): winreg.SetValueEx(hkey, value, 0, winreg.REG_SZ, value_data) import win32gui, win32con win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_ABORTIFHUNG, 5000) else: logger.info("Set the following environment variables in your ~/.bashrc: ") for k, v in persistent_vars.iteritems(): logger.info("export %s = %s" % (k, v)) def spark_remove_env_vars(): # Remove env variables since there's no other spark installed. os.environ.pop("SPARK_HOME") os.environ.pop("PYTHONPATH") os.unsetenv("SPARK_HOME") os.unsetenv("PYTHONPATH") def spark_install_winutils(spark_dir, hadoop_version): import glob if not os.path.isdir(os.path.join(spark_dir, "winutils-master")): _download_file(WINUTILS_URL, os.path.join(spark_dir, "winutils-master.zip")) from zipfile import ZipFile with ZipFile(os.path.join(spark_dir, "winutils-master.zip")) as zf: zf.extractall(spark_dir) candidates = glob.glob(os.path.join(spark_dir, "winutils-master", "hadoop-" + hadoop_version + "*")) if candidates == []: logger.info("No compatible WinUtils found for Hadoop version %s." % hadoop_version) return os.environ["HADOOP_HOME"] = candidates[-1] def spark_install(spark_version=None, hadoop_version=None, reset=True, logging="INFO"): info = spark_install_find(spark_version, hadoop_version, installed_only=False) spark_can_install() logger.info("Installing and configuring Spark version: %s, Hadoop version: %s" % (info["spark_version"], info["hadoop_version"])) if not os.path.isdir(info["spark_version_dir"]): if not os.path.isfile(info["package_local_path"]): import urllib logger.info("Downloading %s into %s" % (info["package_remote_path"], info["package_local_path"])) _download_file(info["package_remote_path"], info["package_local_path"]) logger.info("Extracting %s into %s" % (info["package_local_path"], info["spark_dir"])) import tarfile with tarfile.open(info["package_local_path"]) as tf: tf.extractall(info["spark_dir"]) if logging: from collections import OrderedDict configs = OrderedDict() configs["log4j.rootCategory"] = ",".join((logging, "console", "localfile")) configs["log4j.appender.localfile"] = "org.apache.log4j.DailyRollingFileAppender" configs["log4j.appender.localfile.file"] = "log4j.spark.log" configs["log4j.appender.localfile.layout"] = "org.apache.log4j.PatternLayout" configs["log4j.appender.localfile.layout.ConversionPattern"] = "%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n" spark_conf_log4j_set_value(info, configs, reset) hive_site_path = os.path.join(info["spark_conf_dir"], "hive-site.xml") hive_path = None if not os.path.isfile(hive_site_path) or reset: hive_properties = OrderedDict() hive_properties["javax.jdo.option.ConnectionURL"] = "jdbc:derby:memory:databaseName=metastore_db;create=true", hive_properties["javax.jdo.option.ConnectionDriverName"] = "org.apache.derby.jdbc.EmbeddedDriver" if sys.platform == "win32": hive_path = os.path.join(info["spark_version_dir"], "tmp", "hive") hive_properties["hive.exec.scratchdir"] = hive_path hive_properties["hive.exec.local.scratchdir"] = hive_path hive_properties["hive.metastore.warehouse.dir"] = hive_path spark_hive_file_set_value(hive_site_path, hive_properties) if hive_path: spark_properties = OrderedDict() spark_properties["spark.sql.warehouse.dir"] = hive_path spark_conf_file_set_value(info, spark_properties, reset) spark_set_env_vars(info["spark_version_dir"]) if sys.platform == "win32": spark_install_winutils(info["spark_dir"], info["hadoop_version"]) def main(): # Set up Logging parameters # logger = logging.getLogger() handler = logging.StreamHandler() logging.basicConfig(filename="install_spark.log") formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.WARNING) logger.info("Logging started") parser = argparse.ArgumentParser(description="Spark Installation Script") parser.add_argument("-s", "--spark-version", help="Spark Version to be used.", required=False) parser.add_argument("-h", "--hadoop-version", help="Hadoop Version to be used.", required=False) parser.add_argument("-u", "--uninstall", help="Uninstall Spark", action="store_true", default=False, required=False) parser.add_argument("-i", "--information", help="Show installed versions of Spark", action="store_true", default=False, required=False) args = parser.parse_args() # Debug log the values # logger.debug("Spark Version specified: %s" % args.sparkversion) logger.debug("Hadoop Version specified: %s" % args.hadoopversion) logger.debug("Uninstall argument: %s" % args.Uninstall) logger.debug("Information argument: %s" % args.information) # Check for Uninstall or information flags and react appropriately if args.Uninstall: if args.sparkversion and args.hadoopversion: spark_uninstall(args.sparkversion, args.hadoopversion) else: logger.critical("Spark and Hadoop versions must be specified for uninstallation. Use -i to view installed versions.") elif args.information: installedversions = list(spark_installed_versions()) for elem in installedversions: logging.info(elem) return installedversions else: # Verify that Java 1.8 is running on the system and if it is, run the install. if _verify_java(): logger.debug("Prerequisites checked successfully, running installation.") logger.debug("Spark Version: %s" % args.sparkversion) logger.debug("Hadoop Version: %s" % args.hadoopversion) spark_install(args.sparkversion, args.hadoopversion, True, "INFO") logger.debug("Completed the install") else: logger.critical("A prerequisite for installation has not been satisfied. Please check output log for details.") if __name__ == "__main__": main() <file_sep>import unittest import subprocess import spark_install import sys import os class TestSparkInstall(unittest.TestCase): def setUp(self): pass def test_1_run_install(self): spark_install.spark_install(sparkversion, hadoopversion) def test_2_if_install_exists(self): homedir = os.getenv("LOCALAPPDATA") if sys.platform == "win32" else os.getenv("HOME") if not os.path.exists(os.path.join(homedir, "spark")): assert (), "Parent installation path does not exist." detectionoutput = spark_install.spark_installed_versions() if len(detectionoutput) <= 0: raise ValueError("No versions of product detected as installed.") def test_3_word_count(self): if subprocess.call("python test_word_count.py") < 0: assert(), "test_word_count has failed." def test_4_uninstall(self): if subprocess.call("python spark_install.py -U -sv " + sparkversion + " -hv " + hadoopversion) < 0: assert(), "Uninstall process failed." def test_5_if_install_removed(self): detectionoutput = spark_install.spark_installed_versions() if len(detectionoutput) > 0: raise ValueError("Error, Product detected as still installed.") if __name__ == "__main__": sparkversion = "2.1.0" hadoopversion = "2.7" unittest.main()
3fa34ee119deb591cea09ba145b8371bb39701cf
[ "Markdown", "Python", "R" ]
8
Markdown
drdarshan/spark-install
f90617834c7c7cfdabe9923b93fe6d3e7321ccc2
ac90d83f825f26ebdb16397f38ee822798617a6d
refs/heads/master
<file_sep>package net.frisco27.linternaflash; import android.support.v7.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class Settings extends AppCompatActivity { ListView simpleList; String[] questions; Button save; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { context = this; super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); // get the string array from string.xml file questions = getResources().getStringArray(R.array.questions); // get the reference of ListView and Button simpleList = (ListView) findViewById(R.id.simpleListView); save = (Button) findViewById(R.id.submit); // set the adapter to fill the data in the ListView CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions); simpleList.setAdapter(customAdapter); // perform setOnClickListerner event on Button save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message = ""; // get the value of selected answers from custom adapter for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) { message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i); } // display the message on screen with the help of Toast. Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.menu_frontal) { Toast.makeText(this, "Android FRONTAL is Clicked", Toast.LENGTH_SHORT).show(); return true; } if (id == R.id.menu_sos) { Intent intent = new Intent(context.getApplicationContext(),Lanzar.class); startActivity(intent); return true; } if (id == R.id.menu_settings) { try { Intent intent = new Intent(context.getApplicationContext(),Settings.class); this.startActivity(intent); }catch (Exception ex) { Log.e("Intent Settings",ex.getMessage()); } return true; } return super.onOptionsItemSelected(item); } }<file_sep>package net.frisco27.linternaflash; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import java.util.List; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.Toast; import static net.frisco27.linternaflash.R.id.seekBar; public class LinternaFlash extends AppCompatActivity { private ImageButton btControl; private int status = 1;//GLOBAL VARIABLE : estado del button ( 0 or 1 or 2) private Context context; private Camera dispCamara; Parameters parametrosCamara; boolean hasCam, isChecked; int freq; StroboRunner sr; Thread t; SeekBar skBar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_linternaflash); context = this; btControl = (ImageButton) findViewById(R.id.btLinterna); btControl.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { encenderLinternaAndroid (); } }); btControl.setBackgroundResource(R.drawable.flashencendido); skBar = (SeekBar) findViewById(seekBar); skBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) { freq = progress; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu, menu); return true; } //cambiar de evento y vista del boton private void cambiarEventos() { if (status == 1) { if(!btControl.isShown()) { btControl.setVisibility(View.VISIBLE); skBar.setVisibility(View.GONE); } btControl = (ImageButton)findViewById(R.id.btLinterna); btControl.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { apagarLinternaAndroid(); } }); btControl.setBackgroundResource(R.drawable.flashapagado); status=0 ; // change the status to 1 so the at the second clic, the else will be executed } else if(status == 0) { if(!btControl.isShown()) { btControl.setVisibility(View.VISIBLE); skBar.setVisibility(View.GONE); } btControl = (ImageButton) findViewById(R.id.btLinterna); btControl.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { encenderLinternaAndroid (); } }); btControl.setBackgroundResource(R.drawable.flashencendido); status =1;//change the status to 0 so the at the second clic, the if will be executed } else if(status == 2){ btControl.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { turnOnOff(isChecked); if(btControl.isShown()) { btControl.setVisibility(View.GONE); skBar.setVisibility(View.VISIBLE); } } }); } else { btControl.setBackgroundResource(R.drawable.flashapagado); btControl.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { turnOnOff(isChecked); } }); } } //Al cerrar la aplicación apagar el flash public void finish() { if (dispCamara != null) { dispCamara.release(); dispCamara = null; } super.finish(); } @Override protected void onResume() { super.onResume(); try { dispCamara = Camera.open(); parametrosCamara = dispCamara.getParameters(); dispCamara.startPreview(); hasCam = true; } catch( Exception e ) { //Toast.makeText(getApplicationContext(), // "No se ha podido acceder a la cámara", // Toast.LENGTH_SHORT).show(); } } private void apagarLinternaAndroid () { if (dispCamara != null) { parametrosCamara = dispCamara.getParameters(); parametrosCamara.setFlashMode(Parameters.FLASH_MODE_OFF); dispCamara.setParameters(parametrosCamara); cambiarEventos(); } else { Toast.makeText (getApplicationContext(), "No se ha podido acceder al Flash de la cámara", Toast.LENGTH_SHORT).show(); } } private void encenderLinternaAndroid () { //Toast.makeText(getApplicationContext(), // "Accediendo a la cámara", Toast.LENGTH_SHORT).show(); if (dispCamara != null) { //Toast.makeText(getApplicationContext(), // "Cámara encontrada", Toast.LENGTH_SHORT).show(); Parameters parametrosCamara = dispCamara.getParameters(); //obtener modos de flash de la cámara List<String> modosFlash = parametrosCamara.getSupportedFlashModes (); if (modosFlash != null && modosFlash.contains(Camera.Parameters.FLASH_MODE_TORCH)) { //establecer parámetro TORCH para el flash de la cámara parametrosCamara.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); parametrosCamara.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY); try { dispCamara.setParameters(parametrosCamara); dispCamara.startPreview(); cambiarEventos(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Error al activar la linterna", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "El dispositivo no tiene el modo de Flash Linterna", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "No se ha podido acceder al Flash de la cámara", Toast.LENGTH_SHORT).show(); } } //----------------------------------------------------------------------------- private class StroboRunner implements Runnable { int freq; boolean stopRunning = false; @Override public void run() { Camera.Parameters paramsOn = dispCamara.getParameters(); Camera.Parameters paramsOff = parametrosCamara; paramsOn.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); paramsOff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); try { while(!stopRunning) { dispCamara.setParameters(paramsOn); dispCamara.startPreview(); Thread.sleep(1000 - freq); dispCamara.setParameters(paramsOff); dispCamara.startPreview(); Thread.sleep(freq); } } catch (Exception e) { // TODO: handle exception } } } private void turnOnOff(boolean on) { if(on) { if(freq != 0) { sr = new StroboRunner(); sr.freq = freq; t = new Thread(sr); t.start(); return; } else { parametrosCamara.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); } } else if(!on) { if(t != null) { sr.stopRunning = true; t = null; parametrosCamara.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); return; } else { parametrosCamara.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); } } dispCamara.setParameters(parametrosCamara); dispCamara.startPreview(); } //----------------------------------------------------------------------------- @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.menu_frontal) { Toast.makeText(this, "Android FRONTAL is Clicked", Toast.LENGTH_SHORT).show(); return true; } if (id == R.id.menu_sos) { if(!isChecked) { isChecked = true; status = 2; cambiarEventos(); skBar.setVisibility(View.VISIBLE); Toast.makeText(context, "Se activo modo SOS", Toast.LENGTH_SHORT).show(); } else{ isChecked = false; status = 0; turnOnOff(isChecked); cambiarEventos(); skBar.setVisibility(View.GONE); Toast.makeText(context, "SOS desactivado", Toast.LENGTH_SHORT).show(); } } if (id == R.id.menu_settings) { try { Intent intent = new Intent(context.getApplicationContext(),Settings.class); this.startActivity(intent); }catch (Exception ex) { Log.e("Intent Settings",ex.getMessage()); } return true; } return super.onOptionsItemSelected(item); } }
b63cb56324d60ce8d6ede27f99f74c5286726c28
[ "Java" ]
2
Java
frisco27/LinternaFlash
199c680d044b0d683213d7876e5c86a07c68d1df
7f33d197df7260abe258f2b963e69d62fa7e5f09
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace viza_final { class Program { static void Main(string[] args) { string a; if(netice()>=45) { a="Kechdin"; Console.WriteLine(a); Console.ReadLine(); }else{ a="Qaldin"; Console.WriteLine(a); Console.ReadLine(); } } static double netice(ushort viza=10,ushort final=200) { return (viza*0.4)+(final*0.6); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Console.WriteLine("Gelir:"+" "+ netGelir()); Console.WriteLine("Faiz:" + " " + faiz()); Console.ReadLine(); } static double brutGelir(ushort a=90,byte b=20) { return a * b; } static double faiz() { if (brutGelir() >= 1000) { return brutGelir() * 0.18; } else { return brutGelir() * 0.04; } } static double netGelir() { return brutGelir() - faiz(); } } }
fb7080112847834cb00443a18124b73d3d93d818
[ "C#" ]
2
C#
KamranG12/csharp_first
be991839b695897cd6f94ddbc4fa6d5e5bdeb498
bf8faee50c950d2c0102b3a791c97d7ccc0b7ac8
refs/heads/master
<file_sep>import java.util.Scanner; public class Solution { static int input; static String array[]; public static void main(String[] args) { // TODO Auto-generated method stub System.out.print(" ~> java RecordMaker "); Scanner sc = new Scanner(System.in); input = sc.nextInt(); getIdNumber(); for(int i = 0; i < input; i++) System.out.println("NT" + array[i] + " " + getScore()); } private static void getIdNumber() { array = new String[input]; for(int i = 0; i < input; i++) { array[i] = String.format("%05d", (int)(Math.random() * 99999 + 0)); for(int j = 0; j < i; j++) if(array[i] == array[j]) i--; } } private static int getScore() { return (int)(Math.random() * 99 + 0); } }
1d4565b22c420eec0f7ef3dd5aa31e0b673d1219
[ "Java" ]
1
Java
cyewon/Solution
1b96fad1cd0baae86f65856346b4576cf9ce88d1
80e33b10ae3a3980d74b6e3fad6b45c1f11872d4
refs/heads/master
<repo_name>danieldrf01/lista-while<file_sep>/ListaWhile/ListaWhile/Exercicio04.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExercicioWhile { class Exercicio04 { public Exercicio04() { int contador = 0; Console.Write("Quantos carros deseja cadastrar? "); int quantidade = Convert.ToInt32(Console.ReadLine()); Console.Clear(); int somaAno = 0; double somaValor = 0; double somaG = 0; double somaA = 0; string ModeloAux = ""; while (quantidade > contador) { contador = contador + 1; Console.Write("Modelo do carro: "); string modeloCarro = Console.ReadLine(); ModeloAux = modeloCarro.ToLower(); ModeloAux.Substring(0, 1); Console.Write("Valor: "); double valor = Convert.ToDouble(Console.ReadLine()); Console.Write("Ano: "); int ano = Convert.ToInt32(Console.ReadLine()); Console.Clear(); somaAno = somaAno + ano; somaValor = somaValor + valor; if (ModeloAux.Substring(0, 1) == "g") { somaG = somaG + 1; } else if (ModeloAux.Substring(0, 1) == "a") { somaA = somaA + 1; } } double mediaAno = somaAno / contador; double mediaValor = somaValor / contador; Console.WriteLine("Média do ano dos carros: " + mediaAno); Console.WriteLine("Média do valor dos carros: " + mediaValor); Console.WriteLine("Quantidade de carros que começam com a letra G: " + somaG); Console.WriteLine("Quantidade de carros que começam com a letra A: " + somaA); } } } <file_sep>/ListaWhile/ListaWhile/Exercicio01.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExercicioWhile { class Exercicio01 { public Exercicio01() { int quantidade = 0; Console.Write("Deseja cadastrar um nome ? "); string continuar = Console.ReadLine(); continuar = continuar.ToLower(); while (continuar == "sim") { Console.Write("Digite o nome: "); string nome = Console.ReadLine(); Console.WriteLine("Deseja digitar o nome novamente ?"); continuar = Console.ReadLine(); quantidade = quantidade + 1; } } } } <file_sep>/ListaWhile/ListaWhile/Exercicio05.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExercicioWhile { class Exercicio05 { public Exercicio05() { Console.Write("Numero1: "); double numero1 = Convert.ToDouble(Console.ReadLine()); Console.Write("Número2: "); double numero2 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine(" __________________________________"); Console.WriteLine("| MENU |"); Console.WriteLine("| |"); Console.WriteLine("|__________________________________|"); Console.WriteLine("|1 |Somar |"); Console.WriteLine("|__________________|_______________|"); Console.WriteLine("|2 |Subtrair |"); Console.WriteLine("|__________________|_______________|"); Console.WriteLine("|3 |Multiplicar |"); Console.WriteLine("|__________________|_______________|"); Console.WriteLine("|4 |Dividir |"); Console.WriteLine("|__________________|_______________|"); Console.WriteLine("|5 |Sair |"); Console.WriteLine("|__________________|_______________|"); int opcao = Convert.ToInt32(Console.ReadLine()); while (opcao != 5) { if (opcao == 1) { Console.WriteLine("Soma " + (numero1 + numero2)); } else if (opcao == 2) { Console.WriteLine("Subtração: " + (numero1 - numero2)); } else if (opcao == 3) { Console.WriteLine("Multiplicação: " + (numero1 * numero2)); } else if (opcao == 4) { Console.WriteLine("Divisão: " + (numero1 / numero2)); } Console.WriteLine(" __________________________________"); Console.WriteLine("| MENU |"); Console.WriteLine("| |"); Console.WriteLine("|__________________________________|"); Console.WriteLine("|1 |Somar |"); Console.WriteLine("|__________________|_______________|"); Console.WriteLine("|2 |Subtrair |"); Console.WriteLine("|__________________|_______________|"); Console.WriteLine("|3 |Multiplicar |"); Console.WriteLine("|__________________|_______________|"); Console.WriteLine("|4 |Dividir |"); Console.WriteLine("|__________________|_______________|"); Console.WriteLine("|5 |Sair |"); Console.WriteLine("|__________________|_______________|"); opcao = Convert.ToInt32(Console.ReadLine()); } } } } <file_sep>/ListaWhile/ListaWhile/Exercicio07.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExercicioWhile { class Exercicio07 { public Exercicio07() { int jogador = 0; double somaM = 0; double somaF = 0; double peso = 0, maiorPeso = int.MinValue, menorPeso = int.MaxValue; double altura = 0, maiorAltura = int.MinValue, menorAltura = int.MaxValue; int cartaoAmarelo = 0, maiorQuantidade1 = int.MinValue, menorQuantidade1 = int.MaxValue; int cartaoVermelho = 0, maiorQuantidade2 = int.MinValue, menorQuantidade2 = int.MaxValue; string nomeAux1 = "0"; string nomeAux2 = "0"; while (jogador < 1) { Console.Write("Nome: "); string nome = Console.ReadLine(); string modeloAux = nome.ToLower(); int tamanhoNome = nome.Length; int tamanhoNomeAux = 0; Console.Write("\nIdade: "); int idade = Convert.ToInt32(Console.ReadLine()); Console.Write("\nPeso: "); peso = Convert.ToDouble(Console.ReadLine()); Console.Write("\nSexo: "); char sexo = Console.ReadLine()[0]; char sexoAux = Char.ToLower(sexo); Console.Write("\nAltura: "); altura = Convert.ToDouble(Console.ReadLine()); Console.Write("\nQuantidade de Gols: "); int quantidadeDeGols = Convert.ToInt32(Console.ReadLine()); Console.Write("\nQuantidade de cartões amarelo: "); cartaoAmarelo = Convert.ToInt32(Console.ReadLine()); Console.Write("\nQuantidade de cartões vermelho: "); cartaoVermelho = Convert.ToInt32(Console.ReadLine()); Console.Clear(); if (sexoAux == 'f') { jogador = jogador + 1; } if (sexoAux == 'g') { jogador = jogador + 1; } if (peso < menorPeso) { menorPeso = peso; } if (peso > maiorPeso) { maiorPeso = peso; } if (peso < menorPeso) { menorPeso = peso; } if (altura > maiorAltura) { maiorAltura = altura; } if (altura < menorAltura) { menorAltura = altura; } if (tamanhoNomeAux > tamanhoNome ) { tamanhoNome = tamanhoNomeAux; nomeAux1 = nome; } if (tamanhoNomeAux < tamanhoNome) { tamanhoNome= tamanhoNomeAux; nomeAux2 = nome; } if (cartaoAmarelo > maiorQuantidade1) { maiorQuantidade1 = cartaoAmarelo; } if (cartaoAmarelo < menorQuantidade1) { menorQuantidade1 = cartaoAmarelo; } if (cartaoVermelho > maiorQuantidade2) { maiorQuantidade2 = cartaoVermelho; } if (cartaoVermelho < menorQuantidade2) { menorQuantidade2 = cartaoVermelho; } } Console.WriteLine("\nJogador com maior peso: " + maiorPeso); Console.WriteLine("\nJogador com menor peso: " + menorPeso); Console.WriteLine("\nJogador com maior altura: " + maiorAltura); Console.WriteLine("\nJogador com menor altura: " + menorAltura); Console.WriteLine("\nQuantidade de jogadores masculinos: " + jogador); Console.WriteLine("\nQuantidade de jogadores femininos: " + jogador); Console.WriteLine("\nJogador com maior nome: " + nomeAux1 ); Console.WriteLine("\nJogador com menor nome: " + nomeAux2); Console.WriteLine("\nMaior quantidade de cartões amarelo: " + maiorQuantidade1); Console.WriteLine("\nMenor quantidade de cartões amarelo: " + menorQuantidade1); Console.WriteLine("\nMaior quantidade de cartões vermelho: " + maiorQuantidade2); Console.WriteLine("\nMenor quantidade de cartões vermelho: " + menorQuantidade2); } } }
ec5dda2f764b56c8229704f16354703cccd6c551
[ "C#" ]
4
C#
danieldrf01/lista-while
02a7b9ef206fd958f2d7eb909f31647d26ec2e20
0172e75d5fc0034872b89bd40d9f694fb91ba47f
refs/heads/master
<repo_name>Mica21/Personal<file_sep>/CPU.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <sys/socket.h> void crearCliente(struct sockaddr_in* direccionServidor, int puerto, char* ip) { direccionServidor->sin_family = AF_INET; direccionServidor->sin_addr.s_addr = inet_addr(ip); direccionServidor->sin_port = htons(puerto); } void enviarMensajeUMC(int umc, char*buffer) { send(umc, buffer, strlen(buffer), 0); printf("Le envio %s a UMC\n", buffer); } void recibirMensajeNucleo(int nucleo, char*buffer) { int bytesRecibidos = recv(nucleo, buffer, 1000, 0); if (bytesRecibidos > 0) { buffer[bytesRecibidos] = '\0'; printf(" Me llegaron %d bytes con %s\n", bytesRecibidos, buffer); } } int main(void) { char* buffer_nucleo = malloc(1000); struct sockaddr_in direccionServidor; crearCliente(&direccionServidor, 8000, "127.0.0.1"); int nucleo = socket(AF_INET, SOCK_STREAM, 0); if (connect(nucleo, (void*) &direccionServidor, sizeof(direccionServidor)) != 0) { perror("No se pudo conectar con núcleo\n"); return 1; } else { int bytesRecibidos = recv(nucleo, buffer_nucleo, 23, 0); if (bytesRecibidos <= 0) { perror("El servidor se cayó.\n"); return 1; } printf("%s", buffer_nucleo); } recibirMensajeNucleo(nucleo, buffer_nucleo); char*buffer_umc = malloc(1000); crearCliente(&direccionServidor, 8100, "127.0.0.1"); int umc = socket(AF_INET, SOCK_STREAM, 0); if (connect(umc, (void*) &direccionServidor, sizeof(direccionServidor)) != 0) { perror("No se pudo conectar con UMC\n"); return 1; } else { int bytesRecibidos = recv(umc, buffer_umc, 20, 0); if (bytesRecibidos <= 0) { perror("El servidor se cayó.\n"); return 1; } printf("%s\n", buffer_umc); } enviarMensajeUMC(umc, buffer_nucleo); return 0; }
67d333ebe16c0715fcbf25832645070e371da72d
[ "C" ]
1
C
Mica21/Personal
f4ffbf7e8a37a18cf62e6612be39eb8a28499ba4
0b758344846c61565ec6e4a20fd19d4302bfe36a
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { Producto } from '@app/models/producto'; import { TokenService } from '@app/service/token.service'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import * as productActions from '@app/producto/state/product.actions'; import * as fromProduct from '@app/producto/state/product.reducer'; import { Router } from '@angular/router'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'app-lista-producto', templateUrl: './lista-producto.component.html', styleUrls: ['./lista-producto.component.css'] }) export class ListaProductoComponent implements OnInit { products$: Observable<Producto[]>; error$: Observable<String>; isAdmin = false; roles: string[]; constructor( private tokenService: TokenService, private router: Router, private store: Store<fromProduct.AppState>, private toastr: ToastrService) { } ngOnInit(): void { this.products(); if(this.tokenService.getToken()){ this.roles = this.tokenService.getAuthorities(); this.roles.forEach( role => { if(role === 'ROLE_ADMIN' ){ this.isAdmin = true; } } ); } this.error$.subscribe( data => { if(data){ this.toastr.error("Ha ocurrido un error", 'Error', { timeOut: 3000 }); } } ) } products(): void { this.store.dispatch(new productActions.LoadProducts()); this.products$ = this.store.pipe(select(fromProduct.getProducts)); this.error$ = this.store.pipe(select(fromProduct.getError)); } deleteProduct(id: number) { if (confirm("¿Seguro quieres eliminar este producto?")){ this.store.dispatch(new productActions.DeleteProduct(id)); } } update(id: number){ this.router.navigate(['/products/editar', id]); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { JwtDto } from '@app/models/jwt-dto'; import { LoginUser } from '@app/models/login-user'; import { NewUser } from '@app/models/new-user'; import { environment } from '@env/environment'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { authURL = environment.api_server + 'auth/'; constructor(private httpCliente: HttpClient) { } public newUser(newUser: NewUser): Observable<any> { return this.httpCliente.post<any>(this.authURL + 'new', newUser); } public login(loginUser: LoginUser): Observable<JwtDto> { return this.httpCliente.post<JwtDto>(this.authURL + 'login', loginUser); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Producto } from '@app/models/producto'; import { ProductoService } from '@app/service/producto.service'; import { ToastrService } from 'ngx-toastr'; import { Observable } from 'rxjs'; import * as productActions from '@app/producto/state/product.actions'; import * as fromProduct from '@app/producto/state/product.reducer'; import { Store } from '@ngrx/store'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-editar-producto', templateUrl: './editar-producto.component.html', styleUrls: ['./editar-producto.component.css'] }) export class EditarProductoComponent implements OnInit { productForm: FormGroup; product$: Observable<Producto>; constructor( private activatedRoute: ActivatedRoute, private router: Router, private fb: FormBuilder, private store: Store<fromProduct.AppState>) { } ngOnInit(): void { const id = this.activatedRoute.snapshot.params.id; this.productForm = this.fb.group({ nombre: ["", Validators.required], precio: ["", Validators.required], id: null }) this.store.dispatch(new productActions.LoadProduct(id)); this.product$ = this.store.select(fromProduct.getCurrentProduct); this.product$.subscribe(currentProduct => { if (currentProduct) { this.productForm.patchValue({ nombre: currentProduct.nombre, precio: currentProduct.precio, id: currentProduct.id }); } }) } onUpdate(): void { const id = this.activatedRoute.snapshot.params.id; const updatedProduct: Producto = { nombre: this.productForm.get("nombre").value, precio: this.productForm.get("precio").value, id: this.productForm.get("id").value }; this.store.dispatch(new productActions.UpdateProduct(updatedProduct)); this.router.navigate(['products']); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ProdGuardService as guard } from '@app/guards/prod-guard.service'; import { ListaProductoComponent } from '@app/producto/lista-producto.component'; import { DetalleProductoComponent } from '@app/producto/detalle-producto.component'; import { NuevoProductoComponent } from '@app/producto/nuevo-producto.component'; import { EditarProductoComponent } from '@app/producto/editar-producto.component'; import { RouterModule, Routes } from '@angular/router'; import { StoreModule } from '@ngrx/store'; import { EffectsModule, Actions } from '@ngrx/effects'; import { productReducer } from '@app/producto/state/product.reducer'; import { ProductEffect } from '@app/producto/state/product.effects'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; const productRoutes: Routes = [ {path: '', component: ListaProductoComponent, canActivate: [guard], data: {expectedRole: ['admin', 'user']}}, {path: 'detalle/:id', component: DetalleProductoComponent, canActivate: [guard], data: {expectedRole: ['admin', 'user']}}, {path: 'nuevo', component: NuevoProductoComponent, canActivate: [guard], data: {expectedRole: ['admin', 'user']}}, {path: 'editar/:id', component: EditarProductoComponent, canActivate: [guard], data: {expectedRole: ['admin']}},] @NgModule({ declarations: [ ListaProductoComponent, DetalleProductoComponent, NuevoProductoComponent, EditarProductoComponent, ], imports: [ CommonModule, ReactiveFormsModule, FormsModule, RouterModule.forChild(productRoutes), StoreModule.forFeature("products", productReducer), EffectsModule.forFeature([ProductEffect]) ] }) export class ProductsModule { } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { StoreModule } from '@ngrx/store'; import { EffectsModule } from '@ngrx/effects'; import { StoreDevtoolsModule } from '@ngrx/store-devtools' import { AppRoutingModule } from '@app/app-routing.module'; import { AppComponent } from '@app/app.component'; import { interceptorProvider } from '@app/interceptors/prod-interceptor.service'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ToastrModule } from 'ngx-toastr'; import { LoginComponent } from '@app/auth/login.component'; import { RegisterComponent } from '@app/auth/register.component'; import { MenuComponent } from '@app/menu/menu.component'; import { IndexComponent } from '@app/index/index.component'; import { FacebookLoginProvider, GoogleLoginProvider, SocialAuthServiceConfig, SocialLoginModule } from 'angularx-social-login'; @NgModule({ declarations: [ AppComponent, LoginComponent, RegisterComponent, MenuComponent, IndexComponent ], imports: [ BrowserModule, AppRoutingModule, SocialLoginModule, BrowserAnimationsModule, ToastrModule.forRoot(), HttpClientModule, FormsModule, ReactiveFormsModule, StoreModule.forRoot({}), StoreDevtoolsModule.instrument(), EffectsModule.forRoot([]) ], providers: [ interceptorProvider, { provide: 'SocialAuthServiceConfig', useValue: { autoLogin: false, providers: [ { id: GoogleLoginProvider.PROVIDER_ID, provider: new GoogleLoginProvider( '609546117576-s47ql8dcujeo7f50ftqpgaekvom927o2.apps.googleusercontent.com' ), }, { id: FacebookLoginProvider.PROVIDER_ID, provider: new FacebookLoginProvider('335496677713223'), }, ], } as SocialAuthServiceConfig, } ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { TokenDto } from '@app/models/token-dto'; import { environment } from '@env/environment'; import { Observable } from 'rxjs'; const cabecera = {headers: new HttpHeaders({'Content-Type' : 'application/json'})}; @Injectable({ providedIn: 'root' }) export class OauthService { oauthURL = environment.api_server + 'oauth/'; constructor(private httpCliente: HttpClient) { } public google(tokenDto: TokenDto): Observable<TokenDto> { return this.httpCliente.post<TokenDto>(this.oauthURL + 'google', tokenDto, cabecera); } public facebook(tokenDto: TokenDto): Observable<TokenDto> { return this.httpCliente.post<TokenDto>(this.oauthURL + 'facebook', tokenDto, cabecera); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { SubscribeService } from '@app/service/subscribe.service'; @Component({ selector: 'app-subscribe', templateUrl: './subscribe.component.html', styleUrls: ['./subscribe.component.css'] }) export class SubscribeComponent implements OnInit { cardNumber: string; cardHolder: string; expirationMonth: string; expirationYear: string; ccv: number; merchantId: number = 694565; constructor(private subscribeService: SubscribeService) { } ngOnInit(): void { } onSubmit(){ this.subscribeService.save().subscribe(res => { window.alert(res); }); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from '@app/auth/login.component'; import { RegisterComponent } from '@app/auth/register.component'; import { IndexComponent } from '@app/index/index.component'; const routes: Routes = [ {path: '', component: IndexComponent}, {path: 'login', component: LoginComponent}, {path: 'register', component: RegisterComponent}, {path: 'products', loadChildren: () => import('@app/producto/products.module').then(m => m.ProductsModule)}, {path: 'subscribe', loadChildren: () => import('@app/subscribe/subscribe.module').then(m => m.SubscribeModule)}, {path: '**', redirectTo: '', pathMatch: 'full'} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule { } <file_sep>import { Injectable } from '@angular/core'; import { Actions, Effect, ofType } from '@ngrx/effects'; import { Action } from '@ngrx/store'; import { Observable, of } from 'rxjs'; import { map, mergeMap, catchError } from 'rxjs/operators'; import { ProductoService } from '@app/service/producto.service'; import * as productActions from '@app/producto/state/product.actions'; import { Producto } from '@app/models/producto'; @Injectable() export class ProductEffect { constructor( private actions$: Actions, private productService: ProductoService ) {} //Cargar productos @Effect() loadProducts$: Observable<Action> = this.actions$.pipe( ofType<productActions.LoadProducts>( productActions.ProductActionTypes.LOAD_PRODUCTS ), mergeMap((actions: productActions.LoadProducts) => this.productService.lista().pipe( map( (products: Producto[]) => new productActions.LoadProductsSuccess(products) ), catchError(err => of(new productActions.LoadProductsFail(err))) )) ); //Cargar un producto @Effect() loadProduct$: Observable<Action> = this.actions$.pipe( ofType<productActions.LoadProduct>( productActions.ProductActionTypes.LOAD_PRODUCT ), mergeMap((action: productActions.LoadProduct) => this.productService.detail(action.payload).pipe( map( (product: Producto) => new productActions.LoadProductSuccess(product) ), catchError(err => of(new productActions.LoadProductFail(err))) )) ); //Crear un producto @Effect() createProduct$: Observable<Action> = this.actions$.pipe( ofType<productActions.CreateProduct>( productActions.ProductActionTypes.CREATE_PRODUCT ), map((action: productActions.CreateProduct) => action.payload), mergeMap((product: FormData) => this.productService.save(product).pipe( map( (newProduct: Producto) => new productActions.CreateProductSuccess(newProduct) ), catchError(err => of(new productActions.CreateProductFail(err))) ) ) ); //actualizar un producto @Effect() updateProduct$: Observable<Action> = this.actions$.pipe( ofType<productActions.UpdateProduct>( productActions.ProductActionTypes.UPDATE_PRODUCT ), map((action: productActions.UpdateProduct) => action.payload), mergeMap((product: Producto) => this.productService.update(product.id, product).pipe( map( (updateProduct: Producto) => new productActions.UpdateProductSuccess({ id: updateProduct.id, changes: updateProduct }) ), catchError(err => of(new productActions.UpdateProductFail(err))) ) ) ); //Eliminar un producto @Effect() deleteProduct$: Observable<Action> = this.actions$.pipe( ofType<productActions.DeleteProduct>( productActions.ProductActionTypes.DELETE_PRODUCT ), map((action: productActions.DeleteProduct) => action.payload), mergeMap((id: number) => this.productService.delete(id).pipe( map(() => new productActions.DeleteProductSuccess(id) ), catchError(err => of(new productActions.DeleteProductFail(err))) ) ) ); }<file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Producto } from '@app/models/producto'; import { ProductoService } from '@app/service/producto.service'; import { ToastrService } from 'ngx-toastr'; import * as productActions from '@app/producto/state/product.actions'; import * as fromProduct from '@app/producto/state/product.reducer'; import { Store } from '@ngrx/store'; @Component({ selector: 'app-nuevo-producto', templateUrl: './nuevo-producto.component.html', styleUrls: ['./nuevo-producto.component.css'] }) export class NuevoProductoComponent implements OnInit { nombre: string = ''; precio: number = null; lyric: string = ''; composers: string = ''; producers: string = ''; language: number = null; gender: number = null; selectedFile: File; constructor( private router: Router, private store: Store<fromProduct.AppState> ) { } ngOnInit(): void { } onFileChanged(event) { this.selectedFile = event.target.files[0]; } onCreate(): void{ const productForm = new FormData(); productForm.append('product', new Blob( [ JSON.stringify({ "nombre": this.nombre, "precio": this.precio }) ], { type: "application/json" } )); productForm.append('imageFile', this.selectedFile); const producto = new Producto(this.nombre, this.precio); this.store.dispatch(new productActions.CreateProduct(productForm)); this.router.navigate(['/products']); } } <file_sep>import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { NgPaymentCardModule } from 'ng-payment-card'; import { SubscribeComponent } from '@app/subscribe/subscribe.component'; import { ProdGuardService as guard } from '@app/guards/prod-guard.service'; const subscribeRoutes: Routes = [ {path: '', component: SubscribeComponent, canActivate: [guard], data: {expectedRole: ['user']}}, ] @NgModule({ declarations: [ SubscribeComponent, ], imports: [ CommonModule, NgPaymentCardModule, ReactiveFormsModule, FormsModule, RouterModule.forChild(subscribeRoutes) ] }) export class SubscribeModule { }
84b5a186e553e8bcd138df3096da575c2686cdf9
[ "TypeScript" ]
11
TypeScript
andres187/angular-front
1944152ea753337e6b2ef5b230408d233e2d970f
2b653c11848268be197c5a58950b34586e0ee49f
refs/heads/master
<repo_name>compilerJQXC/lab2<file_sep>/pl0-lab2.1/shell.sh echo "gcc pl0.c -o pl0" gcc pl0.c -o pl0
f5bb1e4d8e7f5c38389e521bb0303b32239038da
[ "Shell" ]
1
Shell
compilerJQXC/lab2
e12fb3dc7fd5e6d1a641bfb4e034e48cbf1add1b
baff54dbb09fd3b3dcb4b776745cdd64a375fb64
refs/heads/master
<repo_name>harish-agr/Packet-Processor<file_sep>/packets.c // <NAME> // EECE 555 // Fall 2013 // some of this code was provided by Dr. Kredo #include <pcap/pcap.h> #include <arpa/inet.h> int openFileOrDevice(int use_file, pcap_t **pcap_handle, char *trace_file, char **dev_name, char pcap_buff[PCAP_ERRBUF_SIZE]); void printMAC(const u_char *packet_data); int checkType(const u_char *packet_data); int printIPv4info(const u_char *packet_data); int printARPinfo(const u_char *packet_data); int printIPv6info(const u_char *packet_data); int printVLANinfo(const u_char *packet_data); int main(int argc, char *argv[]) { char pcap_buff[PCAP_ERRBUF_SIZE]; /* Error buffer used by pcap functions */ pcap_t *pcap_handle = NULL; /* Handle for PCAP library */ struct pcap_pkthdr *packet_hdr = NULL; /* Packet header from PCAP */ const u_char *packet_data = NULL; /* Packet data from PCAP */ int ret = 0; /* Return value from library calls */ char *trace_file = NULL; /* Trace file to process */ char *dev_name = NULL; /* Device name for live capture */ char use_file = 0; /* Flag to use file or live capture */ uint16_t type; // Value of packet type/length field int errorCheck = 0; // Flag to check function calls for errors /* Check command line arguments */ if( argc > 2 ) { fprintf(stderr, "Usage: %s trace_file\n", argv[0]); return -1; } else if( argc > 1 ){ use_file = 1; trace_file = argv[1]; } else { use_file = 0; } errorCheck = openFileOrDevice(use_file, &pcap_handle, trace_file, &dev_name, pcap_buff); if (errorCheck == -1) { printf("error opening file or device\n"); return -1; } /* Loop through all the packets in the trace file. * ret will equal -2 when the trace file ends. * This is an infinite loop for live captures. */ ret = pcap_next_ex(pcap_handle, &packet_hdr, &packet_data); while( ret != -2 ) { /* An error occurred */ if( ret == -1 ) { pcap_perror(pcap_handle, "Error processing packet:"); pcap_close(pcap_handle); return -1; } /* Unexpected return values; other values shouldn't happen when reading trace files */ else if( ret != 1 ) { fprintf(stderr, "Unexpected return value (%i) from pcap_next_ex()\n", ret); pcap_close(pcap_handle); return -1; } /* Process the packet and print results */ else { printMAC(packet_data); type = checkType(packet_data); // print the appropriate packet info // based on the packet type // eg. IPv4, IPv6, ARP, VLAN, or Other switch (type) { case 0x0800: // IPv4 errorCheck = printIPv4info(packet_data); if (errorCheck == -1) { printf("error printing IPv4 information\n"); return -1; } break; case 0x86dd: // IPv6 errorCheck = printIPv6info(packet_data); if (errorCheck == -1) { printf("error printing IPv6 information\n"); return -1; } break; case 0x0806: // ARP errorCheck = printARPinfo(packet_data); if (errorCheck == -1) { printf("error printing ARP information\n"); return -1; } break; case 0x8100: // VLAN errorCheck = printVLANinfo(packet_data); if (errorCheck == -1) { printf("error printing VLAN information\n"); return -1; } break; default: // Other printf("[Other]"); break; } printf("\n"); } /* Get the next packet */ ret = pcap_next_ex(pcap_handle, &packet_hdr, &packet_data); } /* Close the trace file or device */ pcap_close(pcap_handle); return 0; } // input arguments // use_file: input 0 for no file, input 1 for a file used // trace_file: name of file to be opened // return value: openFileOrDevice() returns 0 on success, returns -1 on error // description: openFileOrDevice() will open either a trace file // or a device to capture packets from int openFileOrDevice(int use_file, pcap_t **pcap_handle, char *trace_file, char **dev_name, char pcap_buff[PCAP_ERRBUF_SIZE]) { /* Open the trace file, if appropriate */ if( use_file ){ *pcap_handle = pcap_open_offline(trace_file, pcap_buff); if( pcap_handle == NULL ){ fprintf(stderr, "Error opening trace file \"%s\": %s\n", trace_file, pcap_buff); return -1; } printf("Processing file '%s'\n", trace_file); } /* Lookup and open the default device if trace file not used */ else{ *dev_name = pcap_lookupdev(pcap_buff); if( dev_name == NULL ){ fprintf(stderr, "Error finding default capture device: %s\n", pcap_buff); return -1; } *pcap_handle = pcap_open_live(*dev_name, BUFSIZ, 1, 0, pcap_buff); if( pcap_handle == NULL ){ fprintf(stderr, "Error opening capture device %s: %s\n", *dev_name, pcap_buff); return -1; } printf("Capturing on interface '%s'\n", *dev_name); } return 0; } // input: packet data from PCAP // description: prints source and destination MAC address void printMAC(const u_char *packet_data) { // print MAC src address printf("%02X:", packet_data[6]); printf("%02X:", packet_data[7]); printf("%02X:", packet_data[8]); printf("%02X:", packet_data[9]); printf("%02X:", packet_data[10]); printf("%02X", packet_data[11]); printf(" -> "); // print MAC dst address printf("%02X:", packet_data[0]); printf("%02X:", packet_data[1]); printf("%02X:", packet_data[2]); printf("%02X:", packet_data[3]); printf("%02X:", packet_data[4]); printf("%02X ", packet_data[5]); return; } // input: packet data from PCAP // return value: integer value containing the current packet's type/length value // example return values: 0x86dd, 0x0800 // description: checkType() looks at Byte 12 and 13 of packet_data (the // type/length field of packet header) int checkType(const u_char *packet_data) { uint16_t type; type = (packet_data[12] << 8) | packet_data[13]; return type; } // input: packet data from PCAP // return value: printIPv4info() returns 0 on success, returns -1 on error // description: printIPv4info() cleanly prints IPv4 source and destination addresses int printIPv4info(const u_char *packet_data) { printf("[IPv4] "); // print IPv4 source address char src[INET_ADDRSTRLEN]; char dst[INET_ADDRSTRLEN]; inet_ntop(AF_INET, ((const void *)(packet_data+26)), src, INET_ADDRSTRLEN); if (src == NULL) { printf("error in inet_ntop ipv4 src\n"); return -1; } printf("%s", src); printf(" -> "); // print IPv4 destination address inet_ntop(AF_INET, ((const void *)(packet_data+30)), dst, INET_ADDRSTRLEN); if (dst == NULL) { printf("error in inet_ntop ipv4 dst\n"); return -1; } printf("%s", dst); return 0; } // return value: printARPinfo returns 0 on success, returns -1 on error // description: printARPinfo first checks if request or reply // on requests the requester's IP is first printed followed by the requested IP // on replys the provided IP is printed followed by the Ethernet address mapping int printARPinfo(const u_char *packet_data) { printf("[ARP] "); char src[INET_ADDRSTRLEN]; char dst[INET_ADDRSTRLEN]; if (packet_data[21] == 0x01) // request { // print requester's IP inet_ntop(AF_INET, ((const void *)(packet_data+28)), src, INET_ADDRSTRLEN); if (src == NULL) { printf("error in inet_ntop arp request src\n"); return -1; } // print requested IP inet_ntop(AF_INET, ((const void *)(packet_data+38)), dst, INET_ADDRSTRLEN); if (dst == NULL) { printf("error in inet_ntop arp request dst\n"); return -1; } printf("%s requests %s", src, dst); } if (packet_data[21] == 0x02) // reply { // print provided IP inet_ntop(AF_INET, ((const void *)(packet_data+28)), src, INET_ADDRSTRLEN); if (src == NULL) { printf("error in inet_ntop arp reply src\n"); return -1; } printf("%s at ", src); // print Ethernet address mapping printf("%02X:", packet_data[32]); printf("%02X:", packet_data[33]); printf("%02X:", packet_data[34]); printf("%02X:", packet_data[35]); printf("%02X:", packet_data[36]); printf("%02X", packet_data[37]); } return 0; } // input: packet data from PCAP // return value: printIPv6info() returns 0/-1 on success/error // description: printIPv6info() cleanly prints the source and destination IPv6 address int printIPv6info(const u_char *packet_data) { printf("[IPv6] "); // print IPv6 source address char src[INET6_ADDRSTRLEN]; char dst[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, ((const void *)(packet_data+22)), src, INET6_ADDRSTRLEN); if (src == NULL) { printf("error in inet_ntop ipv4 src\n"); return -1; } printf("%s", src); printf(" -> "); // print IPv6 destination address inet_ntop(AF_INET6, ((const void *)(packet_data+38)), dst, INET6_ADDRSTRLEN); if (dst == NULL) { printf("error in inet_ntop ipv4 dst\n"); return -1; } printf("%s", dst); return 0; } // input: packet data from PCAP // return value: printVLANinfo() returns 0 on success // description: printVLANinfo() prints the VLAN ID int printVLANinfo(const u_char *packet_data) { printf("[VLAN] "); int vlanID = 0; vlanID = packet_data[14] + packet_data[15]; printf("ID = %d", vlanID); return 0; } <file_sep>/README.txt <NAME> EECE 598, California State University - Chico Fall 2013 Packet processing program that uses the PCAP library to print info about packets from live capture. <file_sep>/makefile ##### Makefile ##### # <NAME> # eece 555 # Fall 2013 packets: packets.c gcc packets.c -Wall -o packets -lpcap clean: rm packets ###################
80946a6bc96edf3da379530505bb306b5b4112f1
[ "Makefile", "C", "Text" ]
3
C
harish-agr/Packet-Processor
b8656ad54895a061206886ec36f88fa323238122
78f4c1a6578174708ca52d33643237f6ffb10837
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab11 { class Staff : Person { #region Properties private string school; private double pay; public string School { set { school = value; } get { return school; } } public double Pay { set { pay = value; } get { return pay; } } #endregion #region Methods private Staff() { } public Staff(string YourName, string YourAddress, string YourSchool, double YourPay) : base(YourName, YourAddress) { School = YourSchool; Pay = YourPay; } public override string ToString() { return base.ToString() + ($", {School}, {Pay}"); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab11 { class Person { #region Properties private string name, address; public string Name { set { name = value; } get { return name; } } public string Address { set { address = value; } get { return address; } } #endregion #region Methods protected internal Person() { } public Person(string YourName, string YourAddress) { Name = YourName; Address = YourAddress; } override public string ToString() { string MyString = ($"{Name}, {Address}"); return MyString; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab11 { class Student : Person { #region Properties private string program; private int year; private double fee; public string Program { set { program = value; } get { return program; } } public int Year { set { year = value; } get { return year; } } public double Fee { set { fee = value; } get { return fee; } } #endregion #region Methods private Student() { } public Student(string YourName, string YourAddress, string YourProgram, int YourYear, double YourFee) : base(YourName, YourAddress) { Program = YourProgram; Year = YourYear; Fee = YourFee; } public override string ToString() { return base.ToString() + ($", {Program}, {Year}, {Fee}"); } #endregion } }
ef9dab2d1ee1355ecf2c02d8feaab8c24c69e989
[ "C#" ]
3
C#
DaniDeArmond/Lab11
310d9ded740a43872c9040e62b04a252e613adf7
451f212954c7b703987a9a72ceff142f1a9ea05e
refs/heads/master
<repo_name>arianjsp/Node_para_iniciantes<file_sep>/02-nodejs3-async-await/index.js /* Atividade sobre callback: - obter um usuario - obter um numero de telefone do usiario a partir do seu ID - obter o endereço do usuario a partir do seu ID */ //manupilação feita pelo módulo interno do node.js (convertendo a função com callback para Promise sem fazer alterações na função existente) const util = require('util') const getAddressAsync = util.promisify(getAddress) function getUser() { //Se der algo errado -> reject(ERROR) //Se der certo -> resolve() return new Promise(function solvePromise(resolve, reject) { setTimeout(function (){ //return reject(new Error('TESTE DE ERRO!')) return resolve({ id: 1, name: "Irineu", dateBirth: new Date() }) }, 1000) }) } function getPhoneNumber(idUser) { return new Promise(function solvePromise(resolve, reject) { setTimeout(() => { return resolve({ phoneNumer: '666 666', ddd: 79 }) }, 2000); }) } function getAddress(idUser, callback) { setTimeout(() => { return callback(null, { address: 'Beco Diagonal', number: '382' }) }, 2000); } main() async function main() { try { //capturando o usuario console.time('medida-promise') const user = await getUser() // const phone = await getPhoneNumber(user.id) // const address = await getAddressAsync(user.id) //Utilizando o Promise.all() o tempo de execucao eh menor const result = await Promise.all([ getPhoneNumber(user.id), getAddressAsync(user.id) ]) const phone = result[0] const address = result[1] console.log(` Nome: ${user.name}, Tell: (${phone.ddd}) ${phone.phoneNumer} Endereco: ${address.address}, ${address.number} `) console.timeEnd('medida-promise') } catch(error) { console.log('VISH UM ERRO', error) } }<file_sep>/03-events/index.js const EventEmitter = require('events') class MyEmitter extends EventEmitter { } const myEmitter = new MyEmitter() const newEvent = 'user:click' myEmitter.on(newEvent, function (click) { console.log('This is a click test!', click) }) // //simulacao de que o evento do click ta ocorrendo // myEmitter.emit(newEvent, 'Funciona?') // myEmitter.emit(newEvent, 'YEY FUNCIONA!') // //evento ocorrendo a cada 1 segundo // let count = 0 // setInterval(function (){ // myEmitter.emit(newEvent, 'YEY FUNCIONA! ' + count ++) // }, 1000) //exemplo com eventos no terminal (um texto digitado no terminal será printado na tela) const stdin = process.openStdin() stdin.addListener('data', function (value) { console.log(`Voce digitou: ${value.toString().trim()}`) }) // //exemplo com Promise para verificar a diferença na execução // const stdin = process.openStdin() // function main() { // return new Promise(function (resolve, reject) { // stdin.addListener('data', function (value) { // return resolve(value) // }) // }) // } // main().then(function (result) { // console.log('escreveu:', result.toString()) // })<file_sep>/README.md # Node_para_iniciantes Atividades realizadas durante o curso online Node.js para Iniciantes By NodeBR!
984992c35b0c9e91f09d9d58fe84b3e3e4b063da
[ "JavaScript", "Markdown" ]
3
JavaScript
arianjsp/Node_para_iniciantes
8cf9c4526837caa5d921a61c3828715063219cd4
716b3435d3602c16becf8ac45c7324ab0e2140d2
refs/heads/master
<repo_name>Vlad1235/TwoLevelCache<file_sep>/src/main/java/com/github/rodionovsasha/cache/strategies/MRUStrategy.java package com.github.rodionovsasha.cache.strategies; /* * Copyright (©) 2014. <NAME> */ /** * MRU Strategy - Most Recently Used */ public class MRUStrategy<K> extends CacheStrategy<K> { @Override public void putObject(K key) { getObjectsStorage().put(key, System.nanoTime()); } @Override public K getReplacedKey() { getSortedObjectsStorage().putAll(getObjectsStorage()); return getSortedObjectsStorage().lastKey(); } } <file_sep>/README.md [![Build Status](https://travis-ci.org/rodionovsasha/TwoLevelCache.svg?branch=master)](https://travis-ci.org/rodionovsasha/TwoLevelCache) # TwoLevelCache Create a configurable two-level cache (for caching Objects). Level 1 is memory, level 2 is filesystem. Config params should let one specify the cache strategies and max sizes of level 1 and 2. <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.rodionovsasha.cache</groupId> <artifactId>TwoLevelCache</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>Two Level Cache</name> <description> Create a configurable two-level cache (for caching Objects). Level 1 is memory, level 2 is filesystem. Config params should let one specify the cache strategies and max sizes of level 1 and 2. </description> <url>https://github.com/rodionovsasha/TwoLevelCache</url> <developers> <developer> <name><NAME></name> <email><EMAIL></email> <organizationUrl>https://github.com/rodionovsasha</organizationUrl> </developer> </developers> <scm> <connection>scm:git:git://github.com/rodionovsasha/TwoLevelCache.git</connection> <developerConnection>scm:git:ssh://github.com:rodionovsasha/TwoLevelCache.git</developerConnection> <url>https://github.com/rodionovsasha/TwoLevelCache</url> </scm> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>13</java.version> <log4j.version>2.12.1</log4j.version> <junit.version>4.12</junit.version> <lombok.version>1.18.10</lombok.version> <!--Plugins--> <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version> <jacoco-maven-plugin.version>0.8.4</jacoco-maven-plugin.version> <spotbugs-maven-plugin.version>3.1.12.2</spotbugs-maven-plugin.version> <maven-checkstyle-plugin.version>3.1.0</maven-checkstyle-plugin.version> <coveralls-maven-plugin.version>4.3.0</coveralls-maven-plugin.version> </properties> <dependencies> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco-maven-plugin.version}</version> <executions> <execution> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>prepare-package</phase> <goals> <goal>report</goal> <goal>check</goal> </goals> </execution> </executions> <configuration> <rules> <rule implementation="org.jacoco.maven.RuleConfiguration"> <element>BUNDLE</element> <limits> <limit implementation="org.jacoco.report.check.Limit"> <counter>INSTRUCTION</counter> <value>COVEREDRATIO</value> <minimum>0.80</minimum> </limit> <limit implementation="org.jacoco.report.check.Limit"> <counter>CLASS</counter> <value>MISSEDCOUNT</value> <maximum>0</maximum> </limit> </limits> </rule> </rules> </configuration> </plugin> <plugin> <groupId>com.github.spotbugs</groupId> <artifactId>spotbugs-maven-plugin</artifactId> <version>${spotbugs-maven-plugin.version}</version> <configuration> <!-- Enables analysis which takes more memory but finds more bugs. If you run out of memory, changes the value of the effort element to 'low'.--> <effort>Max</effort> <!-- Reports all bugs (other values are medium and max) --> <threshold>Low</threshold> <xmlOutput>true</xmlOutput> </configuration> <executions> <!-- Ensures that spotbugs inspects source code when project is compiled.--> <execution> <id>analyze-compile</id> <phase>compile</phase> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>${maven-checkstyle-plugin.version}</version> <executions> <execution> <id>checkstyle</id> <phase>validate</phase> <goals> <goal>check</goal> </goals> <configuration> <configLocation>src/test/resources/checkstyle.xml</configLocation> <failOnViolation>true</failOnViolation> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/src/main/java/com/github/rodionovsasha/cache/strategies/CacheStrategy.java package com.github.rodionovsasha.cache.strategies; import lombok.Getter; import java.util.Map; import java.util.TreeMap; /* * Copyright (©) 2014. <NAME> */ @Getter public abstract class CacheStrategy<K> { private final Map<K, Long> objectsStorage; private final TreeMap<K, Long> sortedObjectsStorage; CacheStrategy() { this.objectsStorage = new TreeMap<>(); this.sortedObjectsStorage = new TreeMap<>(new ComparatorImpl<>(objectsStorage)); } public abstract void putObject(K key); public void removeObject(K key) { if (isObjectPresent(key)) { objectsStorage.remove(key); } } public boolean isObjectPresent(K key) { return objectsStorage.containsKey(key); } public K getReplacedKey() { sortedObjectsStorage.putAll(objectsStorage); return sortedObjectsStorage.firstKey(); } public void clear() { objectsStorage.clear(); } } <file_sep>/src/test/java/com/github/rodionovsasha/cache/strategies/LFUCacheTest.java package com.github.rodionovsasha.cache.strategies; import com.github.rodionovsasha.cache.TwoLevelCache; import org.junit.After; import org.junit.Test; import static com.github.rodionovsasha.cache.strategies.StrategyType.LFU; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /* * Copyright (©) 2017. <NAME> */ public class LFUCacheTest { private TwoLevelCache<Integer, String> twoLevelCache; @After public void clearCache() { twoLevelCache.clearCache(); } @Test public void shouldMoveObjectFromCacheTest() { twoLevelCache = new TwoLevelCache<>(2, 2, LFU); twoLevelCache.putToCache(0, "String 0"); twoLevelCache.getFromCache(0); twoLevelCache.getFromCache(0); twoLevelCache.putToCache(1, "String 1"); twoLevelCache.getFromCache(1); // Least Frequently Used - will be removed twoLevelCache.putToCache(2, "String 2"); twoLevelCache.getFromCache(2); twoLevelCache.getFromCache(2); twoLevelCache.putToCache(3, "String 3"); twoLevelCache.getFromCache(3); twoLevelCache.getFromCache(3); assertTrue(twoLevelCache.isObjectPresent(0)); assertTrue(twoLevelCache.isObjectPresent(1)); assertTrue(twoLevelCache.isObjectPresent(2)); assertTrue(twoLevelCache.isObjectPresent(3)); twoLevelCache.putToCache(4, "String 4"); twoLevelCache.getFromCache(4); twoLevelCache.getFromCache(4); assertTrue(twoLevelCache.isObjectPresent(0)); assertFalse(twoLevelCache.isObjectPresent(1)); // Least Frequently Used - has been removed assertTrue(twoLevelCache.isObjectPresent(2)); assertTrue(twoLevelCache.isObjectPresent(3)); assertTrue(twoLevelCache.isObjectPresent(4)); } @Test public void shouldNotRemoveObjectIfNotPresentTest() { twoLevelCache = new TwoLevelCache<>(1, 1, LFU); twoLevelCache.putToCache(0, "String 0"); twoLevelCache.putToCache(1, "String 1"); twoLevelCache.removeFromCache(2); } }<file_sep>/src/main/java/com/github/rodionovsasha/cache/strategies/LFUStrategy.java package com.github.rodionovsasha.cache.strategies; /* * Copyright (©) 2014. <NAME> */ /** * LFU Strategy - Least Frequently Used */ public class LFUStrategy<K> extends CacheStrategy<K> { @Override public void putObject(K key) { long frequency = 1; if (getObjectsStorage().containsKey(key)) { frequency = getObjectsStorage().get(key) + 1; } getObjectsStorage().put(key, frequency); } } <file_sep>/src/test/java/com/github/rodionovsasha/cache/strategies/MRUCacheTest.java package com.github.rodionovsasha.cache.strategies; import com.github.rodionovsasha.cache.TwoLevelCache; import org.junit.After; import org.junit.Test; import java.util.stream.IntStream; import static com.github.rodionovsasha.cache.strategies.StrategyType.MRU; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /* * Copyright (©) 2017. <NAME> */ public class MRUCacheTest { private TwoLevelCache<Integer, String> twoLevelCache; @After public void clearCache() { twoLevelCache.clearCache(); } @Test public void shouldMoveObjectFromCacheTest() { twoLevelCache = new TwoLevelCache<>(2, 2, MRU); // i=3 - Most Recently Used - will be removed IntStream.range(0, 4).forEach(i -> { twoLevelCache.putToCache(i, "String " + i); assertTrue(twoLevelCache.isObjectPresent(i)); twoLevelCache.getFromCache(i); }); twoLevelCache.putToCache(4, "String 4"); assertTrue(twoLevelCache.isObjectPresent(0)); assertTrue(twoLevelCache.isObjectPresent(1)); assertTrue(twoLevelCache.isObjectPresent(2)); assertFalse(twoLevelCache.isObjectPresent(3)); //Most Recently Used - has been removed assertTrue(twoLevelCache.isObjectPresent(4)); } } <file_sep>/src/main/java/com/github/rodionovsasha/cache/FileSystemCache.java package com.github.rodionovsasha.cache; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import lombok.val; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static java.lang.String.format; /* * Copyright (©) 2014. <NAME> */ @Slf4j class FileSystemCache<K extends Serializable, V extends Serializable> implements Cache<K, V> { private final Map<K, String> objectsStorage; private final Path tempDir; private int capacity; @SneakyThrows FileSystemCache() { this.tempDir = Files.createTempDirectory("cache"); this.tempDir.toFile().deleteOnExit(); this.objectsStorage = new ConcurrentHashMap<>(); } @SneakyThrows FileSystemCache(int capacity) { this.tempDir = Files.createTempDirectory("cache"); this.tempDir.toFile().deleteOnExit(); this.capacity = capacity; this.objectsStorage = new ConcurrentHashMap<>(capacity); } @SuppressWarnings("unchecked") @Override public synchronized V getFromCache(K key) { if (isObjectPresent(key)) { val fileName = objectsStorage.get(key); try (val fileInputStream = new FileInputStream(new File(tempDir + File.separator + fileName)); val objectInputStream = new ObjectInputStream(fileInputStream)) { return (V) objectInputStream.readObject(); } catch (ClassNotFoundException | IOException e) { log.error(format("Can't read a file. %s: %s", fileName, e.getMessage())); } } log.debug(format("Object with key '%s' does not exist", key)); return null; } @Override @SneakyThrows public synchronized void putToCache(K key, V value) { val tmpFile = Files.createTempFile(tempDir, "", "").toFile(); try (val outputStream = new ObjectOutputStream(new FileOutputStream(tmpFile))) { outputStream.writeObject(value); outputStream.flush(); objectsStorage.put(key, tmpFile.getName()); } catch (IOException e) { log.error("Can't write an object to a file " + tmpFile.getName() + ": " + e.getMessage()); } } @Override public synchronized void removeFromCache(K key) { val fileName = objectsStorage.get(key); val deletedFile = new File(tempDir + File.separator + fileName); if (deletedFile.delete()) { log.debug(format("Cache file '%s' has been deleted", fileName)); } else { log.debug(format("Can't delete a file %s", fileName)); } objectsStorage.remove(key); } @Override public int getCacheSize() { return objectsStorage.size(); } @Override public boolean isObjectPresent(K key) { return objectsStorage.containsKey(key); } @Override public boolean hasEmptyPlace() { return getCacheSize() < this.capacity; } @SneakyThrows @Override public void clearCache() { Files.walk(tempDir) .filter(Files::isRegularFile) .map(Path::toFile) .forEach(file -> { if (file.delete()) { log.debug(format("Cache file '%s' has been deleted", file)); } else { log.error(format("Can't delete a file %s", file)); } }); objectsStorage.clear(); } } <file_sep>/src/test/java/com/github/rodionovsasha/cache/strategies/ComparatorImplTest.java package com.github.rodionovsasha.cache.strategies; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; /* * Copyright (©) 2017. <NAME> */ public class ComparatorImplTest { private ComparatorImpl<String> comparator; private Map<String, Long> comparatorMap; @Before public void setUp() { comparatorMap = new HashMap<>(); comparator = new ComparatorImpl<>(comparatorMap); } @Test public void keysShouldBeEquals() { //Given comparatorMap.put("key1", 1L); comparatorMap.put("key2", 1L); //When int result = comparator.compare("key1", "key2"); //Then assertEquals(0, result); } @Test public void key1ShouldBeLaterThanKey2() { //Given comparatorMap.put("key1", 2L); comparatorMap.put("key2", 1L); //When int result = comparator.compare("key1", "key2"); //Then assertEquals(1, result); } @Test public void key1ShouldBeEarlierThanKey2() { //Given comparatorMap.put("key1", 1L); comparatorMap.put("key2", 2L); //When int result = comparator.compare("key1", "key2"); //Then assertEquals(-1, result); } @Test(expected = NullPointerException.class) public void shouldInitNPE() { //Given comparatorMap.put("key1", 1L); comparatorMap.put("key2", null); //When comparator.compare("key1", "key2"); } } <file_sep>/src/main/java/com/github/rodionovsasha/cache/TwoLevelCache.java package com.github.rodionovsasha.cache; import com.github.rodionovsasha.cache.strategies.CacheStrategy; import com.github.rodionovsasha.cache.strategies.LFUStrategy; import com.github.rodionovsasha.cache.strategies.LRUStrategy; import com.github.rodionovsasha.cache.strategies.MRUStrategy; import com.github.rodionovsasha.cache.strategies.StrategyType; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import lombok.val; import java.io.Serializable; import static java.lang.String.format; /* * Copyright (©) 2014. <NAME> */ @Slf4j @Getter public class TwoLevelCache<K extends Serializable, V extends Serializable> implements Cache<K, V> { private final MemoryCache<K, V> firstLevelCache; private final FileSystemCache<K, V> secondLevelCache; private final CacheStrategy<K> strategy; public TwoLevelCache(final int memoryCapacity, final int fileCapacity, final StrategyType strategyType) { this.firstLevelCache = new MemoryCache<>(memoryCapacity); this.secondLevelCache = new FileSystemCache<>(fileCapacity); this.strategy = getStrategy(strategyType); } public TwoLevelCache(final int memoryCapacity, final int fileCapacity) { this.firstLevelCache = new MemoryCache<>(memoryCapacity); this.secondLevelCache = new FileSystemCache<>(fileCapacity); this.strategy = getStrategy(StrategyType.LFU); } private CacheStrategy<K> getStrategy(StrategyType strategyType) { switch (strategyType) { case LRU: return new LRUStrategy<>(); case MRU: return new MRUStrategy<>(); case LFU: default: return new LFUStrategy<>(); } } @Override public synchronized void putToCache(K newKey, V newValue) { if (firstLevelCache.isObjectPresent(newKey) || firstLevelCache.hasEmptyPlace()) { log.debug(format("Put object with key %s to the 1st level", newKey)); firstLevelCache.putToCache(newKey, newValue); if (secondLevelCache.isObjectPresent(newKey)) { secondLevelCache.removeFromCache(newKey); } } else if (secondLevelCache.isObjectPresent(newKey) || secondLevelCache.hasEmptyPlace()) { log.debug(format("Put object with key %s to the 2nd level", newKey)); secondLevelCache.putToCache(newKey, newValue); } else { // Here we have full cache and have to replace some object with new one according to cache strategy. replaceObject(newKey, newValue); } if (!strategy.isObjectPresent(newKey)) { log.debug(format("Put object with key %s to strategy", newKey)); strategy.putObject(newKey); } } private void replaceObject(K key, V value) { val replacedKey = strategy.getReplacedKey(); if (firstLevelCache.isObjectPresent(replacedKey)) { log.debug(format("Replace object with key %s from 1st level", replacedKey)); firstLevelCache.removeFromCache(replacedKey); firstLevelCache.putToCache(key, value); } else if (secondLevelCache.isObjectPresent(replacedKey)) { log.debug(format("Replace object with key %s from 2nd level", replacedKey)); secondLevelCache.removeFromCache(replacedKey); secondLevelCache.putToCache(key, value); } } @Override public synchronized V getFromCache(K key) { if (firstLevelCache.isObjectPresent(key)) { strategy.putObject(key); return firstLevelCache.getFromCache(key); } else if (secondLevelCache.isObjectPresent(key)) { strategy.putObject(key); return secondLevelCache.getFromCache(key); } return null; } @Override public synchronized void removeFromCache(K key) { if (firstLevelCache.isObjectPresent(key)) { log.debug(format("Remove object with key %s from 1st level", key)); firstLevelCache.removeFromCache(key); } if (secondLevelCache.isObjectPresent(key)) { log.debug(format("Remove object with key %s from 2nd level", key)); secondLevelCache.removeFromCache(key); } strategy.removeObject(key); } @Override public int getCacheSize() { return firstLevelCache.getCacheSize() + secondLevelCache.getCacheSize(); } @Override public boolean isObjectPresent(K key) { return firstLevelCache.isObjectPresent(key) || secondLevelCache.isObjectPresent(key); } @Override public void clearCache() { firstLevelCache.clearCache(); secondLevelCache.clearCache(); strategy.clear(); } @Override public synchronized boolean hasEmptyPlace() { return firstLevelCache.hasEmptyPlace() || secondLevelCache.hasEmptyPlace(); } } <file_sep>/src/test/java/com/github/rodionovsasha/cache/strategies/StrategyTypeTest.java package com.github.rodionovsasha.cache.strategies; /* * Copyright (©) 2017. <NAME> */ import org.junit.Test; import static org.junit.Assert.assertEquals; public class StrategyTypeTest { @Test public void shouldGetCorrectValuesFromEnumTest() { assertEquals(StrategyType.LFU, StrategyType.valueOf("LFU")); assertEquals(StrategyType.LRU, StrategyType.valueOf("LRU")); assertEquals(StrategyType.MRU, StrategyType.valueOf("MRU")); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenTypeIsNotCorrectTest() { StrategyType.valueOf("wrong_value"); } } <file_sep>/src/main/java/com/github/rodionovsasha/cache/strategies/LRUStrategy.java package com.github.rodionovsasha.cache.strategies; /* * Copyright (©) 2014. <NAME> */ /** * LRU Strategy - Least Recently Used */ public class LRUStrategy<K> extends CacheStrategy<K> { @Override public void putObject(K key) { getObjectsStorage().put(key, System.nanoTime()); } }
e2e5b9f03b93e3f5e25e5bb0956ccb23036533ea
[ "Markdown", "Java", "Maven POM" ]
12
Java
Vlad1235/TwoLevelCache
a6a8c8721a82e3a3f4db59b23402c2587d1795e1
a0fd1b578a1ed922c08be9086761f11d1f28fc9d
refs/heads/master
<file_sep># Polyglot Polyglot is a command line tool that automatically parses embedded DSLs that have been implemented with Dialect, a recursive-descent parser for Domain Specific Languages (DSLs) that is implemented using Go and facilitates parsing through use of Parsing Expression Grammars (PEGs). ## Motivation Providing the ability to embed multiple DSLs in files containing other code allows you to use the best tool for the job. When you can benefit from the clarity and brevity of a DSL, using Polyglot you can embed the DSL(s) and use it alongside the more powerful and general programming facility. ## Supported DSLs Currently, Polyglot only has one DSL implemented, but more are on the way. - [QForm: a DSL for creating HTML5 forms](https://github.com/AdamJonR/qform) - H5: a DSL for creating HTML5 (coming soon) - EZBC: a DSL for performing bcmath calculations in PHP (coming soon) ## Using Polyglot You can automatically parse files that contain DSL source code by calling Polyglot and passing in the path to the config.json file. An example config file is below. In the file, the input directory (the directory that contains files to by parsed) and the output directory (the directory that contains files having been parsed.) The extensions object contains an array of parsing implementations by file extension. In the examples below, we'll configure Polyglot to search for and parse QForm DSL blocks in files with the html extension. Once completed, polyglot-log.txt contains detailed parsing info for each file that contained a DSL block to parse. ### Example config.json ``` { "inputDir":"/Users/adam/Desktop/testInput/", "outputDir":"/Users/adam/Desktop/testOutput/", "extensions":{ ".html":[ { "dialect":"qform", "start":"<!--qform:o-->\n", "stop":"<!--qform:c-->\n" } ] } } ``` ### Example HTML File in Input Directory ``` <!DOCTYPE html> <html> <head> <title>Example page with embedded DSL</title> </head> <body> <h1>Example page with embedded DSL</h1> <!--qform:o--> - method post text - name name - maxlength 30 - required email - name email textarea - name my-message submit - value Send message <!--qform:c--> </body> <html> ``` ### Example HTML File in Output Directory After Parsing ``` <!DOCTYPE html> <html> <head> <title>Example page with embedded DSL</title> </head> <body> <h1>Example page with embedded DSL</h1> <form method="post"> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" maxlength="30" required="required" id="name" /> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" id="email" /> </div> <div class="form-group"> <label for="my-message">My-message</label> <textarea name="my-message" id="my-message"></textarea> </div> <div class="form-group"> <input type="submit" name="field4" id="field4" value="Send message" /> </div> </form> </body> <html> ``` ### Example polyglot-log.txt ``` File: /Users/adam/Desktop/testInput/form-example.html form attribute*, form field* | hyphen, name, value?, newline | found | hyphen, name, value?, newline | missing hyphen on line 2 | newline?, field type, field attribute* | | field name, newline | | found | | hyphen, name, value?, newline? | | found | | hyphen, name, value?, newline? | | found | | hyphen, name, value?, newline? | | found | | hyphen, name, value?, newline? | | missing hyphen on line 7 | | hyphen, array, newline? | | missing hyphen on line 7 | found | newline?, field type, field attribute* | | field name, newline | | found | | hyphen, name, value?, newline? | | found | | hyphen, name, value?, newline? | | missing hyphen on line 10 | | hyphen, array, newline? | | missing hyphen on line 10 | found | newline?, field type, field attribute* | | field name, newline | | found | | hyphen, name, value?, newline? | | found | | hyphen, name, value?, newline? | | missing hyphen on line 13 | | hyphen, array, newline? | | missing hyphen on line 13 | found | newline?, field type, field attribute* | | field name, newline | | found | | hyphen, name, value?, newline? | | found | found found ``` <file_sep>package main import ( "encoding/json" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "github.com/adamjonr/dialects" "github.com/adamjonr/qform" ) type Config struct { ConfigPath string InputDir string OutputDir string InputDirAbs string OutputDirAbs string Extensions map[string][]Lexicon `json:"extensions"` } type Lexicon struct { Dialect string `json:"dialect"` Start string `json:"start"` Stop string `json:"stop"` } type File struct { Path string Name string Dir string Ext string PathRel string } func main() { // store args args := os.Args // ensure the config argument is present if len(args) < 2 { fmt.Println("missing json config file argument") os.Exit(1) } // create config object config, err := NewConfig(args[1]) // exit with error if err != nil { os.Exit(1) } // declare log summary logSummary := "" // walk inputDir err = filepath.Walk(config.InputDirAbs, func(path string, f os.FileInfo, err error) error { // skip directories if f.IsDir() { return nil } // prep File dir, name := filepath.Split(path) ext := filepath.Ext(path) pathRel, err := filepath.Rel(config.InputDirAbs, path) if err != nil { fmt.Printf("file %q not parsed due to relative path error\n", path) return nil } // create file pointer file := &File{Path: path, Name: name, Dir: dir, PathRel: pathRel, Ext: ext} // skip files without extensions if ext == "" { CopyFile(config, file) return nil } // skip files with extensions that are not configured with dialects _, ok := config.Extensions[ext] if !ok { CopyFile(config, file) return nil } // skip hidden files if name[0:1] == "." { CopyFile(config, file) return nil } // call parser logSummary = logSummary + ParseFile(config, file) // standard return return nil }) // handle severe error if err != nil { os.Exit(1) } // write log file _ = ioutil.WriteFile("polyglot-log.txt", []byte(logSummary), 0777) } func NewConfig(path string) (*Config, error) { // create pointer to config config := &Config{ConfigPath: path} // read in config file bytes, err := ioutil.ReadFile(path) if err != nil { // provide feedback and return early fmt.Printf("json config file %q could not be read\n", path) return config, err } // declare top-level JSON object into map var objmap map[string]*json.RawMessage // marshall into map err = json.Unmarshal(bytes, &objmap) // handle error if err != nil { fmt.Printf("json config file %q could not be parsed\n", path) return config, err } // check for required keys and return early with feedback if absent if _, ok := objmap["inputDir"]; !ok { fmt.Printf("json config file %q missing inputDir key\n", path) return config, err } if _, ok := objmap["outputDir"]; !ok { fmt.Printf("json config file %q missing outputDir key\n", path) return config, err } if _, ok := objmap["extensions"]; !ok { fmt.Printf("json config file %q missing extensions key\n", path) return config, err } // marshall values into config err = json.Unmarshal(*objmap["inputDir"], &config.InputDir) if err != nil { fmt.Printf("json config file %q contained invalid inputDir string\n", path) return config, err } err = json.Unmarshal(*objmap["outputDir"], &config.OutputDir) if err != nil { fmt.Printf("json config file %q contained invalid outputDir string\n", path) return config, err } err = json.Unmarshal(*objmap["extensions"], &config.Extensions) if err != nil { fmt.Printf("json config file %q contained invalid extensions object\n", path) return config, err } // clean directories config.InputDir = filepath.Clean(config.InputDir) config.OutputDir = filepath.Clean(config.OutputDir) // add absolut directories config.InputDirAbs, err = filepath.Abs(config.InputDir) config.OutputDirAbs, err = filepath.Abs(config.OutputDir) // ensure input and output directories exist if _, err := os.Stat(config.InputDirAbs); err != nil { fmt.Printf("input directory %q does not exist\n", config.InputDirAbs) return config, err } if _, err := os.Stat(config.OutputDirAbs); err != nil { fmt.Printf("output directory %q does not exist\n", config.OutputDirAbs) return config, err } // otherwise, all is well return config, nil } func ParseFile(config *Config, file *File) string { var logSummary string = "File: " + file.Path + "\n" var log string // store file contents bytes, err := ioutil.ReadFile(file.Path) // check for error if err != nil { // exit early if read error return log } // convert to string source := string(bytes) // create label so other lexicons can be handled lexiconFor: // cycle through lexicons for this file extension for _, lexicon := range config.Extensions[file.Ext] { // store string array of sections sections := strings.Split(source, lexicon.Start) // continue to next lexicon if there is no start delimiter (i.e., only one section) if len(sections) < 2 { continue } var dsl dialects.Dialectable // create the appropriate dsl switch lexicon.Dialect { case "qform": dsl = new(qform.DSL) } // cycle through sections for i, section := range sections { // skip first section if i == 0 { continue } // get closing section selections := strings.Split(section, lexicon.Stop) // if only one section, there's no closing tag if len(selections) != 2 { logSummary = logSummary + "incomplete parsing using " + lexicon.Dialect + " because the start delimiter '" + lexicon.Start + "' has no stop delimiter or an extra stop delimiter\n\n" continue lexiconFor } // parse contents of first selection selections[0], err, log = dialects.Parse(dsl, selections[0]) // check for parsing error if err != nil { logSummary = logSummary + "incomplete parsing using " + lexicon.Dialect + ": " + err.Error() + "\n\n" continue lexiconFor } // append log to logSummary logSummary = logSummary + log // put put parsed result back in selections sections[i] = strings.Join(selections, "") } // put parsed result back in source source = strings.Join(sections, "") } // convert source to bytes[] byteSource := []byte(source) // try to save source to outputDir err = ioutil.WriteFile(filepath.Clean(config.OutputDirAbs+"/"+file.PathRel), byteSource, 0777) // done if no error if err == nil { return logSummary } // otherwise, check if directories need to be created first dirRel := filepath.Dir(file.PathRel) os.MkdirAll(config.OutputDir+"/"+dirRel, 0777) // try to save source to outputDir err = ioutil.WriteFile(filepath.Clean(config.OutputDirAbs+"/"+file.PathRel), byteSource, 0777) // done if no error if err == nil { return logSummary } // log error and move on logSummary = logSummary + "output file " + file.Path + "could not be written to: " + err.Error() + "\n\n" // return logSummary return logSummary } func CopyFile(config *Config, file *File) { source, err := os.Open(file.Path) if err != nil { // note error and move on fmt.Printf("the input file %q could not be opened.\n", file.Path) return } defer source.Close() dest, err := os.Create(filepath.Clean(config.OutputDirAbs + "/" + file.PathRel)) if err != nil { // note error and move on fmt.Printf("the output file %q could not be created.\n", file.Path) return } if _, err := io.Copy(dest, source); err != nil { dest.Close() // note error and move on fmt.Printf("the output file %q could not be created.\n", file.Path) } dest.Close() return }
c93d9b701283859d22c9f6c26613ac1689b7b093
[ "Markdown", "Go" ]
2
Markdown
jmptrader/polyglot
d997f5cb613f82c62bef0618cd71aa42597a98c6
5bd15bd4330cec377c83794c4e4f6da4a850f738
refs/heads/master
<file_sep>const initState = { posts: [ { id: '1', title: 'Next level pitchfork lyft edison bulb', body: 'Next level pitchfork lyft edison bulb, roof party cloud bread kinfolk helvetica. Brooklyn crucifix cloud bread iPhone poutine blue bottle jianbing lyft tote bag drinking vinegar kickstarter typewriter' }, { id: '2', title: 'Next level pitchfork lyft edison bulb', body: 'Next level pitchfork lyft edison bulb, roof party cloud bread kinfolk helvetica. Brooklyn crucifix cloud bread iPhone poutine blue bottle jianbing lyft tote bag drinking vinegar kickstarter typewriter' }, { id: '3', title: 'Next level pitchfork lyft edison bulb', body: 'Next level pitchfork lyft edison bulb, roof party cloud bread kinfolk helvetica. Brooklyn crucifix cloud bread iPhone poutine blue bottle jianbing lyft tote bag drinking vinegar kickstarter typewriter' } ] } const rootReducer =(state = initState, action) => { if(action.type === 'DELETE_POST'){ let newPost = state.posts.filter(post=>{ return action.id !== post.id }) return{ ...state, posts: newPost } } return state } export default rootReducer<file_sep>import React, { Component } from 'react'; import Todo from './component/Todo'; import AddNewTodo from './component/AddNewTodo'; export class App extends Component { state = { todos: [] }; deleteTodo = (id) => { const todos = this.state.todos.filter((todo) => { return todo.id !== id; }); this.setState({ todos }); }; addTodo = (todo) => { todo.id = Math.random(); let todos = [ ...this.state.todos, todo ]; this.setState({ todos }); }; render() { return ( <div className='todo-app container'> <h1 className='center blue-text'>todo s app</h1> <Todo todos={this.state.todos} deleteTodo={this.deleteTodo} /> <AddNewTodo addTodo={this.addTodo} /> </div> ); } } export default App; <file_sep>import React from 'react'; const Todo = ({ todos, deleteTodo }) => { const todoList = todos.length ? ( todos.map((todo) => { return ( <div key={todo.id} className='collection-item'> <span onClick={() => { deleteTodo(todo.id); }} > {todo.content} </span> </div> ); }) ) : ( <p className='center'> nothing more to do </p> ); return <div className=' todos collection'>{todoList}</div>; }; export default Todo;
da958e6aed3a3e7b12e8173be6cb27c3992c7298
[ "JavaScript" ]
3
JavaScript
redwanzia/git_redux_tut
45c0b9731c24725aebd1918d31d6e1e3d00d5a23
af69e181e06cea93cd4ca3d26f482d3539a5a9d2
HEAD
<file_sep>var matrixPool = new Array(); var isMatrixEnd = false; var isPoolEnd = false; var currentRowIndex = 0; var currentColumnIndex = -1; var pageCurrentRowIndex = 20; var pageCurrentColumnIndex = 20; var binaryMatrixArray = new Array(); function calculatePageStartIndex() { } function initMatrixPool() { matrixPool.push("0810,0810,0810,1020,1020,2244,7efc,0408,0810,1020,2040,7efc,0000,0004,fffe,0000-0810,0810,0810,1020,1020,2244,7efc,0408,0810,1020,2040,7efc,0000,0004,fffe,0000-0080,4044,2ffe,1008,03fc,0208,0a08,1208,23f8,e248,2040,2150,224c,2444,2940,0080-0110,3ff8,0820,0444,fffe,0010,1ff8,1010,1ff0,1010,1ff0,0200,5184,5092,9012,0ff0"); matrixPool.push("1040,1040,20a0,20a0,4910,fa0e,1404,23f8,4000,f808,43fc,0208,1a08,e208,43f8,0208-1100,1100,1100,23fc,2204,6408,a840,2040,2150,2148,224c,2444,2040,2040,2140,2080-0920,0928,7ffc,0920,0920,7ffe,4102,8104,1ff0,1110,1110,1110,1110,1150,1120,0100-0100,0100,0108,7ffc,0100,2110,1930,0944,fffe,0380,0540,0930,311e,c104,0100,0100");//给你带来 matrixPool.push("0008,3ffc,2100,2208,2ffc,2808,2ff8,2808,2ff8,2080,4490,8988,0900,2894,2812,47f2-0080,4040,3048,17fc,0010,0210,f120,10a0,1040,1040,10a0,1110,1210,2806,47fc,0000-1ff0,0100,7ffe,4102,9d74,0100,1d70,0108,3ffc,0008,0008,1ff8,0008,0008,3ff8,0008-1080,1088,2498,44a0,fec0,0284,7c84,447c,7c00,4488,4498,7ca0,44c0,4482,5482,487e");//愿这雪能 matrixPool.push("7ffc,0200,1ff0,1010,1ff0,1010,1ff0,1010,1ff0,0800,0ff0,1420,2240,4180,0660,381c-0010,1ff8,1010,1010,1010,1010,1010,1ff0,1010,1010,1010,1010,1010,1ff0,1010,0000-0008,3ffc,2108,2108,3ff8,2108,2108,2108,3ff8,0100,0108,7ffc,0100,0104,fffe,0000");//夏日里 matrixPool.push("0000,0010,1ff8,1010,1010,1010,1010,1010,1ff0,1010,0000,0440,0c20,1018,200c,4004-0200,0200,0204,fffe,0400,0440,0840,0850,13f8,3040,5040,9040,1040,1044,17fe,1000-0078,3f80,0100,0100,1110,0d30,0540,0104,fffe,0100,0100,0100,0100,0100,0500,0200-1100,1100,1100,23fc,2204,6408,a840,2040,2150,2148,224c,2444,2040,2040,2140,2080");//只在乎你 matrixPool.push("0200,0100,0000,1f00,0108,0118,7da0,0540,0540,0920,0920,1110,210e,4104,0500,0200-0010,43f8,3000,1000,0008,07fc,f120,1120,1120,1124,1224,121c,1400,2806,47fc,0000");//永远 matrixPool.push("0080,7848,4ffc,5000,5110,50a0,6004,57fe,4808,4bfc,6a08,5208,4208,4208,43f8,4208-0820,0448,7ffc,0100,3ff8,0200,fffe,0410,0ff8,1810,2ff0,c810,0ff0,0810,0ff0,0810-1100,1100,1100,23fc,2204,6408,a840,2040,2150,2148,224c,2444,2040,2040,2140,2080");//陪着你 matrixPool.push("1000,11fc,1004,1008,fc10,2420,2424,27fe,2420,4420,2820,1020,2820,4420,84a0,0040-1000,11fc,1004,1008,fc10,2420,2424,27fe,2420,4420,2820,1020,2820,4420,84a0,0040-1040,1040,2244,7f7e,4284,4304,4204,4284,7e64,4224,4204,4204,4204,7e04,4228,0010");//好好的 matrixPool.push("0480,0ea0,7890,0890,0884,fffe,0880,0890,0a90,0c60,1840,68a0,0920,0a14,2814,100c-0008,3ffc,2100,2208,2ffc,2808,2ff8,2808,2ff8,2080,4490,8988,0900,2894,2812,47f2-0110,3ff8,0820,0444,fffe,0010,1ff8,1010,1ff0,1010,1ff0,0200,5184,5092,9012,0ff0");//我愿意 matrixPool.push("0000,3c00,1800,1800,1800,1800,1800,1800,1800,1800,3c00,0000,0000,0000,0000,0000-0000,f07c,60c6,60c6,60c6,60c6,60c6,60c6,62c6,66c6,fe7c,0000,0000,0000,0000,0000-0000,c6fe,c666,c662,c668,c678,c668,c660,6c62,3866,10fe,0000,0000,0000,0000,0000-0000,00c6,00c6,00c6,00c6,00c6,00c6,00c6,00c6,00c6,007c,0000,0000,0000,0000,0000");//I LOVE U matrixPool.push("0480,0ea0,7890,0890,0884,fffe,0880,0890,0a90,0c60,1840,68a0,0920,0a14,2814,100c-0108,7ffc,0100,3ff8,0000,1ff0,1010,1ff0,0444,fffe,0010,1ff8,1010,1010,1ff0,1010-0080,0080,fc80,04fc,4504,4648,2840,2840,1040,2840,24a0,44a0,8110,0108,020e,0c04-1100,1100,1100,23fc,2204,6408,a840,2040,2150,2148,224c,2444,2040,2040,2140,2080");//我喜欢你 matrixPool.push("0100,0110,3ff8,0100,0104,fffe,0820,0450,3ff8,0100,0108,7ffc,0100,0100,0100,0100-2008,17fc,1000,03f8,fa08,0a08,13f8,3804,57fe,9444,1444,17fc,1444,1444,17fc,1404");//幸福 matrixPool.push("1ff0,1010,1ff0,1010,1ff0,0004,fffe,2200,3ffc,2284,3e88,2250,3e20,e258,028e,0304-0100,0100,0100,0100,0104,fffe,0100,0280,0280,0240,0440,0420,0810,100e,6004,0000-1040,1040,2244,7f7e,4284,4304,4204,4284,7e64,4224,4204,4204,4204,7e04,4228,0010");//最大的 matrixPool.push("0fe0,0820,0820,0fe0,0820,0820,0fe0,0004,fffe,0100,0920,09f0,0900,1500,2306,40fc-0480,0ea0,7890,0890,0884,fffe,0880,0890,0a90,0c60,1840,68a0,0920,0a14,2814,100c");//是我 matrixPool.push("0008,47fc,2488,27f8,0488,07f8,e084,2ffe,2884,28a4,2bf4,2804,2814,5008,8806,07fc-0104,7f84,0804,1024,2224,4124,7fa4,08a4,0a24,7f24,0824,0824,0804,0f84,f814,0008-1100,1100,1100,23fc,2204,6408,a840,2040,2150,2148,224c,2444,2040,2040,2140,2080");//遇到你 matrixPool.push("1080,1088,2498,44a0,fec0,0284,7c84,447c,7c00,4488,4498,7ca0,44c0,4482,5482,487e-2020,2020,227c,3f44,4288,8350,7a20,4a50,4a9e,4b22,4a44,7aa8,4210,0a20,0440,0080");//能够 matrixPool.push("0000,4004,2ffe,2040,0040,e080,2080,21a0,2298,248c,2884,2080,2080,5006,8ffc,0000-1000,11fc,1004,1008,fc10,2420,2424,27fe,2420,4420,2820,1020,2820,4420,84a0,0040-0010,0bf8,7c10,4910,4910,4910,4910,4914,49fe,4804,4824,7ff4,4804,0004,0014,0008");//还好吗 matrixPool.push("1ff0,1010,1ff0,1010,1ff0,0004,fffe,2200,3ffc,2284,3e88,2250,3e20,e258,028e,0304-0008,401c,33e0,1200,0200,0208,f3fc,1220,1220,1220,1220,1420,1020,2820,4406,03fc-0800,0808,0ffc,1400,2420,47f0,0400,0420,07f0,0400,0400,5204,5192,9092,0ff0,0000-1208,1110,10a0,17fc,fc40,1050,3bf8,3440,5040,5044,9ffe,1040,1040,1040,1040,1040");//最近怎样 matrixPool.push("0010,3ff8,2010,2010,3ff0,2004,2004,1ffc,0820,0824,fffe,0820,0820,0820,1020,2020-0820,0824,fffe,0820,0820,0880,1088,1098,30a0,50c0,9080,1180,1282,1482,107e,1000"); } function start() { initMatrixPool(); binaryMatrixArray = parseStrings(matrixPool.pop(), "-", ","); var timer = setInterval(function () { if (isMatrixEnd) { for (var i = 0; i < rowCount; i++) { for (var j = 0; j < columnCount; j++) { var selector = "#r" + i + "c" + j; $(selector).css("background-color", "#485050"); } } if (isPoolEnd) { clearInterval(timer); popupAfter(5000); $.fn.snow(); } else { var str = matrixPool.pop(); if (typeof (str) == "undefined" && matrixPool.length == 0) { isPoolEnd = true; return; } binaryMatrixArray = parseStrings(str,"-", ","); isMatrixEnd = false; currentRowIndex = 0; currentColumnIndex = -1; pageCurrentRowIndex = 20; pageCurrentColumnIndex = 20; continueAnimation(); } } else { continueAnimation(); } }, 70); } function continueAnimation() { if (currentRowIndex == binaryMatrixArray.length && currentColumnIndex == binaryMatrixArray[0].length) { isMatrixEnd = true; } else { do { if (typeof (binaryMatrixArray[currentRowIndex]) != "undefined" && currentColumnIndex == binaryMatrixArray[currentRowIndex].length) { currentRowIndex++; currentColumnIndex = 0; pageCurrentRowIndex++; pageCurrentColumnIndex = 21; } else { currentColumnIndex += 1; pageCurrentColumnIndex += 1; } } while (typeof (binaryMatrixArray[currentRowIndex]) != "undefined" && binaryMatrixArray[currentRowIndex][currentColumnIndex] == 0); } var cellSelector = "#r" + pageCurrentRowIndex + "c" + pageCurrentColumnIndex; if (typeof (binaryMatrixArray[currentRowIndex]) != "undefined" && binaryMatrixArray[currentRowIndex][currentColumnIndex] == 1) { $(cellSelector).css("background-color", "#ffffff"); } else { $(cellSelector).css("background-color", "#485050"); } } function popupAfter(milliseconds) { $("#popup").css("display", "block"); setTimeout(function () { $("#popup").fadeIn(3000); }, milliseconds); }
fdaeec6a30923486fd871f9b615bdd80b02d2228
[ "JavaScript" ]
1
JavaScript
specialflower/saying
54909b5fa4ba4d6b20dc99a7db2e9d0b80ee75db
7ffa9207ed6d41db99ef53d46b62cbb8bb540822
refs/heads/master
<repo_name>global-academy/KusiWarmi<file_sep>/js/list.js var recuperarDenuncias = function() { var Caso = Parse.Object.extend('Caso'); var query = new Parse.Query(Caso); // query.equalTo("playerName", "<NAME>"); query.find({ success: function(results) { for (var i = 0; i < results.length; i++) { var object = results[i]; aumentarListaDenuncias(results[i]); } }, error: function(Errorror) { alert("Error: " + error.code + " " + error.message); } }); }; var aumentarListaDenuncias = function(caso) { var list = $('#posts_list'); var newItem = $('<li>'); var newItem1 = $('<li>'); var newItem2 = $('<li>'); var newItem3 = $('<li>'); var newItem4 = $('<li>'); var newItem5 = $('<li>'); var titulo = caso.attributes.titulo; var fecha = caso.attributes.fecha; var denuncia = caso.attributes.contenido; /* if (caso.attributes.image) { itemContent += ' <img class="image image--small" src="' + caso.attributes.image._url + '">'; }*/ newItem.html(titulo); newItem1.html(fecha); newItem2.html(denuncia); console.log(list); console.log(newItem); console.log(caso); console.log(caso.attributes.text); list.append(newItem); list.append(newItem1); list.append(newItem2); }; $(document).on('ready', function() { recuperarDenuncias(); });
93f1594db0822989d96a1e90e0a5829d5328f6a3
[ "JavaScript" ]
1
JavaScript
global-academy/KusiWarmi
8b18833f0661fed158517f409d6edd3dc0194379
d15c96dd457532236d48ac10b34f954975057cfe
refs/heads/main
<repo_name>ATXChris/Thaw-Alert<file_sep>/main/Temperature.c #include "Temperature.h" #include <stdio.h> #include <math.h> #include "DS18B20.h" #include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "driver/gpio.h" #include "esp_log.h" #include "esp_system.h" #include "esp_err.h" #define SCRATCHPAD_SIZE 9 #define TO_FAHRENHEIT(Celsius) (Celsius * 1.8 +32) static const char *TAG = "Temperature Task"; void printWord(uint16_t byte){ char byteChars[17]; for(int i = 0; i < 16; i++){ if((byte & (1<<(15-i))) > 0){ byteChars[i] = '1'; }else{ byteChars[i] = '0'; } } byteChars[16] = '\0'; ESP_LOGD(TAG, "Word: %s", byteChars); } void temperatureConversion(gpio_num_t gpio_num){ DS18B20_InitializeBus(gpio_num); DS18B20_WriteByte(gpio_num, 0xCC); DS18B20_WriteByte(gpio_num, 0x44); } float readTemperature(gpio_num_t gpio_num){ DS18B20_InitializeBus(gpio_num); DS18B20_WriteByte(gpio_num, 0xCC); DS18B20_WriteByte(gpio_num, 0xBE); uint8_t scratchPad[SCRATCHPAD_SIZE]; for(int i = 0; i < SCRATCHPAD_SIZE; i++){ scratchPad[i] = DS18B20_ReadByte(gpio_num); } uint16_t tempBits = scratchPad[1]; tempBits = tempBits << 8; tempBits = tempBits | scratchPad[0]; printWord(tempBits); float sign = 1; if((tempBits & 0xF000) > 0){ sign = -1; tempBits -= 1; tempBits = ~tempBits; } float degreesCelsius = 0; for(int i = 0; i < 11; i++){ if((tempBits & (1<<i)) > 0){ degreesCelsius += pow(2, i-4); } } degreesCelsius *= sign; /* int32_t intDegreesCelsius; intDegreesCelsius = degreesCelsius * 10000; ESP_LOGI(TAG, "Temperature C: %d.%04u", intDegreesCelsius/10000, abs(intDegreesCelsius) % 10000); float degreesFahrenheit = degreesCelsius * 1.8 + 32; int32_t intDegreesFahrenheit = degreesFahrenheit * 10000; ESP_LOGI(TAG, "Temperature C: %d.%04u", intDegreesFahrenheit/10000, abs(intDegreesFahrenheit) % 10000); */ return degreesCelsius; } void temperature_task(void *pvParameters){ //Pin "D2" is GPIO_NUM_4 while(1){ temperatureConversion(GPIO_NUM_4); vTaskDelay(pdMS_TO_TICKS(1000)); readTemperature(GPIO_NUM_4); } } <file_sep>/main/DS18B20.h #ifndef DS18B20_H #define DS18B20_H #include "driver/gpio.h" #include <stdbool.h> bool DS18B20_InitializeBus(gpio_num_t gpio_num); void DS18B20_WriteByte(gpio_num_t gpio_num, uint8_t byte); uint8_t DS18B20_ReadByte(gpio_num_t gpio_num); #endif <file_sep>/main/Temperature.h #ifndef TEMPERATURE_H #define TEMPERATURE_H void temperature_task(void *pvParameters); #endif <file_sep>/main/DS18B20.c #include <stdio.h> #include "DS18B20.h" #include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "driver/gpio.h" #include "driver/hw_timer.h" #include "esp_log.h" #include "esp_system.h" #include "esp_err.h" static const char *TAG = "DS18B20 Driver"; int count = 0; bool timeout; bool present; void hw_timer_callback(void *arg){ timeout = true; } void gpio_isr_handler(void *arg){ present = true; count++; } //This method performs a reset, and presence check on the DS18B20. //For timing explanation see DS18B20-Datasheet.pdf -- 1-Wire Signaling section bool DS18B20_InitializeBus(gpio_num_t gpio_num){ timeout = false; present = false; ESP_LOGI(TAG, "initializing DS18B20"); //Bus should be pulled high for communication with DS18B20 ESP_ERROR_CHECK(gpio_set_pull_mode(gpio_num, GPIO_PULLUP_ONLY)); //Send reset pulse for a minimum of 480us ESP_ERROR_CHECK(gpio_set_direction(gpio_num, GPIO_MODE_OUTPUT)); ESP_ERROR_CHECK(hw_timer_init(hw_timer_callback, NULL)); ESP_ERROR_CHECK(gpio_set_level(gpio_num, 0)); ESP_ERROR_CHECK(hw_timer_alarm_us(500, false)); while(!timeout){}; //busy wait timeout = false; //Configure falling-edge interrupt to catch 'presence' signal from DS18B20 ESP_ERROR_CHECK(gpio_set_intr_type(gpio_num, GPIO_INTR_NEGEDGE)); ESP_ERROR_CHECK(gpio_install_isr_service(0)); ESP_ERROR_CHECK(gpio_isr_handler_add(gpio_num, gpio_isr_handler, (void *)gpio_num)); //Set the bus back high, wait 60us max for presence signal, or timeout ESP_ERROR_CHECK(gpio_set_level(gpio_num, 1)); ESP_ERROR_CHECK(gpio_set_direction(gpio_num, GPIO_MODE_INPUT)); ESP_ERROR_CHECK(hw_timer_alarm_us(100, false)); while(!timeout && !present){ //Wait until DS18B20 is present, or we timeout. Whichever comes first. } //Release timer, isr resources ESP_ERROR_CHECK(hw_timer_deinit()); ESP_ERROR_CHECK(gpio_isr_handler_remove(gpio_num)); gpio_uninstall_isr_service(); ESP_ERROR_CHECK(gpio_set_intr_type(gpio_num, GPIO_INTR_DISABLE)); return present; } void DS18B20_WriteBit(gpio_num_t gpio_num, bool bit){ timeout = false; ESP_ERROR_CHECK(gpio_set_direction(gpio_num, GPIO_MODE_OUTPUT)); ESP_ERROR_CHECK(gpio_set_level(gpio_num, 0)); ESP_ERROR_CHECK(hw_timer_init(hw_timer_callback, NULL)); ESP_ERROR_CHECK(gpio_set_level(gpio_num, bit)); if(bit){ ESP_ERROR_CHECK(gpio_set_direction(gpio_num, 1)); } ESP_ERROR_CHECK(hw_timer_alarm_us(60, false)); while(!timeout){}; //busy wait timeout = false; //Release Bus ESP_ERROR_CHECK(gpio_set_direction(gpio_num, 1)); ESP_ERROR_CHECK(gpio_set_direction(gpio_num, GPIO_MODE_INPUT)); ESP_ERROR_CHECK(hw_timer_alarm_us(11, false)); while(!timeout){}; ESP_ERROR_CHECK(hw_timer_deinit()); } void DS18B20_WriteByte(gpio_num_t gpio_num, uint8_t byte){ ESP_LOGI(TAG, "Writing byte 0x%x", byte); for(int i = 0; i < 8; i++){ DS18B20_WriteBit(gpio_num, (byte & 1<<i) > 0); } } uint8_t DS18B20_ReadBit(gpio_num_t gpio_num){ timeout = false; present = false; ESP_ERROR_CHECK(gpio_set_direction(gpio_num, GPIO_MODE_OUTPUT)); ESP_ERROR_CHECK(gpio_set_level(gpio_num, 0)); ESP_ERROR_CHECK(hw_timer_init(hw_timer_callback, NULL)); ESP_ERROR_CHECK(gpio_set_intr_type(gpio_num, GPIO_INTR_NEGEDGE)); ESP_ERROR_CHECK(gpio_install_isr_service(0)); ESP_ERROR_CHECK(gpio_isr_handler_add(gpio_num, gpio_isr_handler, (void *)gpio_num)); ESP_ERROR_CHECK(gpio_set_level(gpio_num, 1)); ESP_ERROR_CHECK(gpio_set_direction(gpio_num, GPIO_MODE_INPUT)); ESP_ERROR_CHECK(hw_timer_alarm_us(11, false)); while(!timeout){}; //busy wait timeout = false; ESP_ERROR_CHECK(gpio_isr_handler_remove(gpio_num)); gpio_uninstall_isr_service(); ESP_ERROR_CHECK(gpio_set_intr_type(gpio_num, GPIO_INTR_DISABLE)); ESP_ERROR_CHECK(hw_timer_alarm_us(50, false)); while(!timeout){}; ESP_ERROR_CHECK(hw_timer_deinit()); return (uint8_t)(!present); } uint8_t DS18B20_ReadByte(gpio_num_t gpio_num){ uint8_t response = 0; for(int i = 0; i < 8; i++){ response = response | (DS18B20_ReadBit(gpio_num)<<i); } //ESP_LOGI(TAG, "Read byte 0x%2x", response); return response; } <file_sep>/main/app_main.c #include "Temperature.h" #include <stddef.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" void app_main() { xTaskCreate(temperature_task, "temp_task", 4096, NULL, 1, NULL); } <file_sep>/README.md # Thaw Alert Set-up ubuntu VM <br /> will need to install gcc perl package on guest additions step https://brb.nci.nih.gov/seqtools/installUbuntu.html <br /> pull ESP8266_RTOS_SDK <br /> sudo apt-get install linux-source <br /> sudo apt install libncurses-dev <br /> sudo apt install ncurses-dev kernel -package <br /> sudo apt install flex <br /> sudo apt install bison <br /> sudo apt install gperf <br /> sudo apt install python3-pip <br /> Install virtualbox USB driver manually. <br /> - goto folder C:\Program Files\Oracle\VirtualBox\drivers\USB\filter <br /> - right click VboxUSBMon.inf <br /> - install <br /> - reboot <br /> Use terminal to navigate to Thaw_Alert directory <br /> export PATH="$HOME/esp/xtensa-lx106-elf/bin:$PATH" <br /> export IDF_PATH=~/esp/ESP8266_RTOS_SDK <br /> make all <br />
f9af06915ffbe31c39f690eec80b0f92e84f7e36
[ "Markdown", "C" ]
6
C
ATXChris/Thaw-Alert
bbacf41038ab4b49c74f38e70753d41382cf7ae3
57255f7228e2a80eca47a3609a55dd7565ecfe14
refs/heads/master
<file_sep>#!/bin/bash docker build -t sonatanfv/sonfsmindustry-pilotmdc-vnf1 -f mdc-fsm/Dockerfile .<file_sep># SSMs for industrial pilot Right now, this pilot **does not** need any SSMs since the reconfiguration tasks will be implemented as FSMs. The deprecated SSMs in this folder are not used anymore. More information about FSM/SSM implementations for this pilot can be found [here](https://github.com/sonata-nfv/tng-industrial-pilot/wiki/FSM-SSM-Development).<file_sep>#!/bin/bash docker build -t sonatanfv/sonfsmindustry-pilotns2-ssm -f ns2-ssm/Dockerfile . <file_sep>This is the ns2-ssm specific manager. # Customise Edit file at /ns2-ssm/ns2/ns2.py # Build `docker build -t <container_name> -f ns2-ssm/Dockerfile .` <file_sep># FSMs for industrial pilot This folder contains the FSMs for this pilot. More information about FSM/SSM implementations for this pilot can be found [here](https://github.com/sonata-nfv/tng-industrial-pilot/wiki/FSM-SSM-Development).
142512c7df048603ec5bd895218fbe403f06d3ec
[ "Markdown", "Shell" ]
5
Shell
miguelmesquita/tng-industrial-pilot
22396b629488c1803cd42fb1d2f088e8ce68fdb1
6154070ac1e3c73dcab0cfb3d205d8322650b73f
refs/heads/master
<repo_name>gefire/gear<file_sep>/logger_filter_writer.go package gear import ( "bytes" "io" "os" ) // LoggerFilterWriter is a writer for Logger to filter bytes. // In a https server, avoid some handshake mismatch condition such as loadbalance healthcheck: // // 2017/06/09 07:18:04 http: TLS handshake error from 10.10.5.1:45001: tls: first record does not look like a TLS handshake // 2017/06/14 02:39:29 http: TLS handshake error from 10.0.1.2:54975: read tcp 10.10.5.22:8081->10.0.1.2:54975: read: connection reset by peer // // Usage: // // func main() { // app := gear.New() // Create app // app.Use(func(ctx *gear.Context) error { // return ctx.HTML(200, "<h1>Hello, Gear!</h1>") // }) // // app.Set(gear.SetLogger, log.New(gear.DefaultFilterWriter(), "", log.LstdFlags)) // app.Listen(":3000") // } // type LoggerFilterWriter struct { phrases [][]byte out io.Writer } var loggerFilterWriter = &LoggerFilterWriter{ phrases: [][]byte{[]byte("http: TLS handshake error"), []byte("EOF")}, out: os.Stderr, } // DefaultFilterWriter returns the default LoggerFilterWriter instance. func DefaultFilterWriter() *LoggerFilterWriter { return loggerFilterWriter } // SetOutput sets the output destination for the loggerFilterWriter. func (s *LoggerFilterWriter) SetOutput(out io.Writer) { s.out = out } // Add add a phrase string to filter func (s *LoggerFilterWriter) Add(err string) { s.phrases = append(s.phrases, []byte(err)) } func (s *LoggerFilterWriter) Write(p []byte) (n int, err error) { for _, phrase := range s.phrases { if bytes.Contains(p, phrase) { return len(p), nil } } return s.out.Write(p) } <file_sep>/logger_filter_writer_test.go package gear import ( "bytes" "io" "log" "os" "testing" "github.com/stretchr/testify/assert" ) func TestLoggerFilterWriter(t *testing.T) { t.Run("filter bytes", func(t *testing.T) { assert := assert.New(t) testMsgs := []struct { Msg string Expect string }{ {"http: TLS handshake error from 10.10.5.1:45001: tls: first record does not look like a TLS handshake", ""}, {"http: TLS handshake error from 10.0.1.2:54975: read tcp 10.10.5.22:8081->10.0.1.2:54975: read: connection reset by peer", ""}, {"error from 10.0.1.2:54975: read EOF", ""}, {"Hello World", "Hello World"}, } for _, msg := range testMsgs { r, w, _ := os.Pipe() DefaultFilterWriter().SetOutput(w) log := log.New(DefaultFilterWriter(), "", log.LstdFlags) log.Print(msg.Msg) w.Close() var buf bytes.Buffer io.Copy(&buf, r) if msg.Expect == "" { assert.Equal(buf.Bytes(), []byte(msg.Expect)) } else { assert.Contains(string(buf.Bytes()), msg.Expect) } } }) }
65a6f59c7d54ae8deb5ced26baca5584bdedba36
[ "Go" ]
2
Go
gefire/gear
7e00ef19f333bd10d9af09567e347d4c4981725b
82ff9a0b2941ebfd2629e07d800e361060ac9ef8
refs/heads/master
<repo_name>LoicHuart/EndemikAPI<file_sep>/src/controllers/NotificationController.js const nodemailer = require("nodemailer"); const HolidaySchema = require("../models/Holiday"); const EmployeeSchema = require("../models/Employee"); const { populate } = require("../models/Holiday"); const ServiceSchema = require("../models/Service"); const date = new Date(); const hbs = require("handlebars"); const path = require("path"); const fs = require("fs"); const transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 587, secure: false, // true for 465, false for other ports auth: { user: process.env.MAILER_EMAIL, pass: process.env.MAILER_PASSWORD, }, }); async function mailOptions(to, subject, html) { return { from: '"Endemik" <<EMAIL>>', to: to, subject: subject, html: html, }; } async function sendMail( to, subject, headerHtml, bodyHtml, footerHtml, buttonHtml ) { const filePath = path.join(__dirname, "../templateMail/index.html"); const source = fs.readFileSync(filePath, "utf-8").toString(); const template = hbs.compile(source); const replacements = { header: headerHtml, body: bodyHtml, button: buttonHtml, footer: footerHtml, }; const htmlToSend = template(replacements); transporter.sendMail( await mailOptions(to, subject, htmlToSend), function (err, info) { if (err) { console.log("Error when sending a mail: " + err); } else { console.log("Email sent: " + info.response); } } ); } var NotificationController = { async HolidayRequestStatusUpdateToEmployee(HolidayId) { Holiday = await HolidaySchema.findById(HolidayId).populate( "id_requester_employee" ); let header = `Le statut de votre demande de congé a changé`; let body = []; body.push( `Votre demande de congé du ${date.toLocaleDateString( Holiday.starting_date )} au ${date.toLocaleDateString( Holiday.ending_date )} a changé de statut : ${Holiday.status}.` ); let footer = `La Direction`; sendMail( Holiday.id_requester_employee.mail, "Votre demande de congé a changé de statut !", header, body, footer ); }, async HolidayRequestStatusUpdateToManager(HolidayId) { Holiday = await HolidaySchema.findById(HolidayId).populate({ path: "id_requester_employee", populate: { path: "id_service", populate: { path: "id_manager", }, }, }); let firstname = Holiday.id_requester_employee.firstName; firstname = firstname.charAt(0).toUpperCase() + firstname.substring(1).toLowerCase(); let header = `Le statut de la demande de congé de ${firstname} ${Holiday.id_requester_employee.lastName} a changé`; let body = []; body.push( `La demande de congé de ${firstname} ${ Holiday.id_requester_employee.lastName } du ${date.toLocaleDateString( Holiday.starting_date )} au ${date.toLocaleDateString( Holiday.ending_date )} a changé de statut : ${Holiday.status}.` ); let footer = `La Direction`; sendMail( Holiday.id_requester_employee.id_service.id_manager.mail, `Le statut de la demande de congé de ${firstname} ${Holiday.id_requester_employee.lastName} a changé`, header, body, footer ); }, async NewHolidayRequestToRh(HolidayId) { Holiday = await HolidaySchema.findById(HolidayId).populate( "id_requester_employee" ); serviceRhId = await ServiceSchema.findOne({ name: "rh" }); EmployeeServiceRH = await EmployeeSchema.find({ id_service: serviceRhId.id, }).populate("id_service"); RHMail = await EmployeeServiceRH.map((RH) => { return RH.mail; }); let firstname = Holiday.id_requester_employee.firstName; firstname = firstname.charAt(0).toUpperCase() + firstname.substring(1).toLowerCase(); let header = `Une nouvelle demande de congé de ${firstname} ${Holiday.id_requester_employee.lastName}`; let body = []; body.push( `Une nouvelle demande de congé de ${firstname} ${ Holiday.id_requester_employee.lastName } du ${date.toLocaleDateString( Holiday.starting_date )} au ${date.toLocaleDateString( Holiday.ending_date )} est en attente de validation.` ); let footer = `La Direction`; let button = []; button.push({ text: "valider", url: `${process.env.URL_MAILLER}/api/holidays/status/validée/${HolidayId}`, color: "#D5E8D4", }); button.push({ text: "refuser", url: `${process.env.URL_MAILLER}/api/holidays/status/refusée/${HolidayId}`, color: "#FF9999", }); sendMail( RHMail, `Une nouvelle demande de congé de ${firstname} ${Holiday.id_requester_employee.lastName} est en attente de validation ! `, header, body, footer, button ); }, async NewEmployeetoServiceToManager(EmployeeId) { Employee = await EmployeeSchema.findById(EmployeeId).populate({ path: "id_service", populate: { path: "id_manager", }, }); let firstname = Employee.firstName; firstname = firstname.charAt(0).toUpperCase() + firstname.substring(1).toLowerCase(); let firstnameManager = Employee.id_service.id_manager.firstName; firstnameManager = firstnameManager.charAt(0).toUpperCase() + firstnameManager.substring(1).toLowerCase(); let header = `${firstname} ${Employee.lastName} vient de rejoindre votre service`; let body = []; body.push( `${firstname} ${Employee.lastName} vient de rejoindre votre service, souhaitez lui la bienvenue !` ); let footer = `La Direction`; sendMail( Employee.id_service.id_manager.mail, `${firstname} ${Employee.lastName} vient de rejoindre votre service ! `, header, body, footer ); }, async NewEmployeeRegistedToEmployee(EmployeeId, password) { let Employee = await EmployeeSchema.findById(EmployeeId).populate({ path: "id_service", populate: { path: "id_manager", }, }); let firstname = Employee.firstName; firstname = firstname.charAt(0).toUpperCase() + firstname.substring(1).toLowerCase(); let firstnameManager = Employee.id_service.id_manager.firstName; firstnameManager = firstnameManager.charAt(0).toUpperCase() + firstnameManager.substring(1).toLowerCase(); let city = Employee.city; city = city.charAt(0).toUpperCase() + city.substring(1).toLowerCase(); let header = `Soyez la bienvenue !`; let body = []; body.push(`Voici les principales informations concernant votre compte :`); body.push(`Nom : ${Employee.lastName}`); body.push(`Prénom : ${firstname}`); body.push(`Date de naissance : ${Employee.date_birth}`); body.push(`Numéro de téléphone : ${Employee.tel_nb}`); body.push(`Adresse mail : ${Employee.mail}`); body.push(`Mot de passe : ${password}`); body.push( `Adresse postale : ${Employee.street_nb} ${Employee.street}, ${city}` ); body.push(`Numéro de sécurité social : ${Employee.social_security_number}`); body.push(`Service : ${Employee.id_service.name}`); body.push(`Manageur : ${firstnameManager}`); let footer = `La Direction`; sendMail(Employee.mail, `Votre compte a été crée !`, header, body, footer); }, async NewEmployeeRegistedToDirection(EmployeeId) { Employee = await EmployeeSchema.findById(EmployeeId).populate({ path: "id_service", populate: { path: "id_manager", }, }); let firstname = Employee.firstName; firstname = firstname.charAt(0).toUpperCase() + firstname.substring(1).toLowerCase(); let firstnameManager = Employee.id_service.id_manager.firstName; firstnameManager = firstnameManager.charAt(0).toUpperCase() + firstnameManager.substring(1).toLowerCase(); let serviceDirectionId = await ( await ServiceSchema.findOne({ name: "direction" }) ).id; let EmployeeServiceDirection = await EmployeeSchema.find({ id_service: serviceDirectionId, }); let DirectionMail = EmployeeServiceDirection.map((direction) => { return direction.mail; }); let header = `Un nouvel employé vient d'etre créé !`; let body = []; body.push( `Un nouvel employé vient d'etre créé, ${firstname} ${Employee.lastName}, il rejoint le service ${Employee.id_service.name} managé par ${firstnameManager} ${Employee.id_service.id_manager.lastName}.` ); let footer = ``; sendMail( DirectionMail, `Un nouvel employé vient d'etre créé, ${firstname} ${Employee.lastName} !`, header, body, footer ); }, async NewHolidayRequestToManager(HolidayId) { Holiday = await HolidaySchema.findById(HolidayId).populate({ path: "id_requester_employee", populate: { path: "id_service", populate: { path: "id_manager", }, }, }); let firstname = Holiday.id_requester_employee.firstName; firstname = firstname.charAt(0).toUpperCase() + firstname.substring(1).toLowerCase(); let header = `Nouvelle demande de congé de ${firstname} ${Holiday.id_requester_employee.lastName} ! `; let body = []; body.push( `Une nouvelle demande de congé de ${firstname} du ${date.toLocaleDateString( Holiday.starting_date )} au ${date.toLocaleDateString( Holiday.ending_date )} est en attente de validation.` ); let footer = `La Direction`; let button = []; button.push({ text: "valider", url: `${process.env.URL_MAILLER}/api/holidays/status/validée/${HolidayId}`, color: "#D5E8D4", }); button.push({ text: "refuser", url: `${process.env.URL_MAILLER}/api/holidays/status/refusée/${HolidayId}`, color: "#FF9999", }); sendMail( Holiday.id_requester_employee.id_service.id_manager.mail, `Une nouvelle demande de congé de ${firstname} ${Holiday.id_requester_employee.lastName} est en attente de validation !`, header, body, footer, button ); }, async ForgotPasswordToDirection(req, res) { let mail = req.params.mail; let serviceDirectionId = await ( await ServiceSchema.findOne({ name: "direction" }) ).id; let EmployeeServiceDirection = await EmployeeSchema.find({ id_service: serviceDirectionId, }); let DirectionMail = EmployeeServiceDirection.map((direction) => { return direction.mail; }); let Employee = await EmployeeSchema.findOne({ mail: mail }); if (!Employee) { res.status(400).send({ message: "Error when send ForgotPassword", error: "Invalid employee mail", }); } else { let firstname = Employee.firstName; firstname = firstname.charAt(0).toUpperCase() + firstname.substring(1).toLowerCase(); let header = `${firstname} a oublié son mot de passe, on a besoin de vous !`; let body = []; body.push( `L'employé ${firstname} ${Employee.lastName} a oublié son mot de passe` ); let footer = `La Direction`; let button = []; button.push({ text: "générer", url: `${process.env.URL_MAILLER}/api/employees/updatePassword/${mail}`, color: "#D5E8D4", }); sendMail( DirectionMail, `L'employé ${firstname} ${Employee.lastName} a oublié son mot de passe !`, header, body, footer, button ); res.send({ message: "mail has been send to direction", }); } }, async ForgotPasswordToEmployee(EmployeeId, password) { let Employee = await EmployeeSchema.findById(EmployeeId); let firstname = Employee.firstName; firstname = firstname.charAt(0).toUpperCase() + firstname.substring(1).toLowerCase(); let header = ``; let body = []; body.push(`Voici votre nouveau mot de passe : `); body.push(`${password}`); let footer = `La Direction`; sendMail( Employee.mail, `${firstname}, voici votre nouveau mot de passe !`, header, body, footer ); }, }; module.exports = NotificationController; <file_sep>/src/models/Holiday.js const mongoose = require("mongoose"); const { Schema } = mongoose; const HolidaySchema = new mongoose.Schema({ note: { type: String, trim: true, }, starting_date: { type: Date, required: true, }, ending_date: { type: Date, required: true, }, current_date: { type: Date, }, validation_date: { type: Date, default: null, }, type: { type: String, enum: ["rtt", "congés payés"], required: true, }, status: { type: String, enum: ["en attente", "prévalidé", "validé", "refusé", "annulé"], default: "en attente", required: true, }, id_requester_employee: { type: Schema.Types.ObjectId, ref: "Employee", required: true, }, }); HolidaySchema.pre("save", async function (next) { this.current_date = await Date.now(); next(); }); module.exports = mongoose.model("Holiday", HolidaySchema, "Holiday"); <file_sep>/src/controllers/ServiceController.js const ServiceSchema = require("../models/Service"); const EmployeeSchema = require("../models/Employee"); var ServiceController = { async addService(req, res) { try { if (!checkKeys(req.body, ["name", "site", "id_manager"])) { throw { err: "Invalid keys", code: "36" }; } if (req.body.name) { req.body.name = req.body.name.toLowerCase(); } employee = await EmployeeSchema.findById(req.body.id_manager); if (!employee) { throw { err: "Invalid manager id", code: "37" }; } serviceTestName = await ServiceSchema.findOne({ name: req.body.name }) if (serviceTestName) { throw { err: `This service name is already use`, code: "38" }; } serviceTest = await ServiceSchema.findOne({ id_manager: req.body.id_manager }) if (serviceTest) { throw { err: `this employee is already a manager of the service ${serviceTest.name}`, code: "39" }; } const service = new ServiceSchema(req.body); await service.save(); employee.id_service = service._id; employee.isManager = true; await employee.save(); res.send(service); } catch (err) { console.log(err) res.status(400).send({ message: "Error when adding a service", error: err.err, code: err.code }); } }, async getAllServices(req, res) { const populate = parseInt(req.query.populate); let services; try { if (populate) { services = await ServiceSchema.find(req.body).populate("id_manager"); } else { services = await ServiceSchema.find(req.body); } if (!services) { throw { err: `services not found`, code: "40" }; } res.send(services); } catch (err) { res.status(400).send({ message: "Error when geting all services", error: err.err, code: err.code }); } }, async deleteAllServices(req, res) { try { await ServiceSchema.deleteMany(); res.send({ message: `All services have been delete`, }); } catch (err) { res.status(400).send({ message: "Error when deleting all services", error: err, }); } }, async updateService(req, res) { const id = req.params.id; try { if (!checkKeys(req.body, ["name", "site", "id_manager"])) { throw { err: "Invalid keys", code: "41" }; } if (req.body.name) { req.body.name = req.body.name.toLowerCase(); } service = await ServiceSchema.findById(id); if (!service) { throw { err: "Invalid service id", code: "42" }; } employee = await EmployeeSchema.findById(req.body.id_manager); if (!employee) { throw { err: "Invalid manager id", code: "43" }; } serviceTestName = await ServiceSchema.findOne({ name: req.body.name }) if (serviceTestName && (serviceTestName.name != service.name)) { throw { err: `This service name is already use`, code: "44" }; } serviceTest = await ServiceSchema.findOne({ id_manager: req.body.id_manager }) if (serviceTest && (JSON.stringify(serviceTest.id_manager) != JSON.stringify(service.id_manager))) { throw { err: `this employee is already a manager of the service ${serviceTest.name}`, code: "45" }; } oldManager = await EmployeeSchema.findById(service.id_manager); oldManager.isManager = false; oldManager.save(); updateKeys = Object.keys(req.body); updateKeys.forEach((key) => (service[key] = req.body[key])); await service.save(); employee = await EmployeeSchema.findById(req.body.id_manager); employee.id_service = service._id; employee.isManager = true; employee.save(); res.send({ message: `Service ${id} was updated !`, }); } catch (err) { res.status(400).send({ message: "Error when updating a service", error: err.err, code: err.code }); } }, async getServiceByID(req, res) { const id = req.params.id; const populate = parseInt(req.query.populate); let service; try { if (populate) { service = await ServiceSchema.findById(id).populate("id_manager"); } else { service = await ServiceSchema.findById(id); } if (!service) { throw { err: "Invalid service id", code: "46" }; } res.send(service); } catch (err) { res.status(400).send({ message: "Error when geting a service by id", error: err.err, code: err.code }); } }, async deleteService(req, res) { const id = req.params.id; try { service = await ServiceSchema.findById(id); if (!service) { throw { err: "Invalid service id", code: "47" }; } if (service.name.toLowerCase() == "rh" || service.name.toLowerCase() == "direction") { throw { err: "Cannot delete this service", code: "48" }; } employee = await EmployeeSchema.find({ id_service: id }) if (employee) { employee.map(e => { console.log(e) if (JSON.stringify(e._id) != JSON.stringify(service.id_manager)) { throw { err: "Cannot delete the service while employee is linked", code: "49" }; } }); } service.remove(); res.send({ message: `Service deleted`, }); } catch (err) { res.status(400).send({ message: "Error when deleting a service", error: err.err, code: err.code }); } }, }; function checkKeys(body, allowedKeys) { const updatesKeys = Object.keys(body); return updatesKeys.every((key) => allowedKeys.includes(key)); } module.exports = ServiceController; <file_sep>/src/controllers/LoginController.js const bcrypt = require("bcrypt"); const EmployeeSchema = require("../models/Employee"); const jwt = require("jsonwebtoken"); const { ForgotPassword } = require("./NotificationController"); var LoginController = { async auth(req, res) { var email = req.body.email; var password = req.body.password; try { let employee = await EmployeeSchema.findOne({ mail: email, active: true }); if (!employee) { throw new Error(); } let match = bcrypt.compareSync(password, employee.password); if (!match) { throw new Error(); } token = jwt.sign( { _id: employee._id, }, process.env.SECRET_JWT, { expiresIn: 60 * 60 } ); res.send({ token: token, }); } catch (err) { res.status(401).send({ message: "error when connection", error: "Incorrect email or password", code: "34", }); } }, async logout(req, res) { var id = req.body.id; try { const token = req.body.token; token = ""; res.send({ token: token, }); } catch (error) { res.status(401).send({ message: "error when disconnection", error: "Can't logout", code: "35", }); } }, }; module.exports = LoginController; <file_sep>/src/middlewares/UploadPicture.js const slugify = require('slugify'); const bcrypt = require("bcrypt"); const multer = require('multer'); const path = require('path'); var storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, `./public/uploads/`); }, filename: async function(req, file, cb) { cb(null, slugify(bcrypt.hashSync(file.originalname, 10)) + "." + file.mimetype.split("/")[1]); } }); var UploadPicture = multer({ storage }); module.exports = UploadPicture; <file_sep>/src/controllers/HolidayController.js const HolidaySchema = require("../models/Holiday"); const EmployeeSchema = require("../models/Employee"); const NotificationController = require("../controllers/NotificationController"); var HolidayController = { async addHoliday(req, res) { try { if ( !checkKeys(req.body, [ "note", "starting_date", "ending_date", "type", "id_requester_employee", ]) ) { throw { err: "Invalid keys", code: "19" }; } let employee = await EmployeeSchema.findById( req.body.id_requester_employee ); if (!employee) { throw { err: "Invalid employee id", code: "20" }; } diff = dayDiff(req.body.starting_date, req.body.ending_date); if (diff >= 0) { if (req.body.type == "rtt") { if (employee.holiday_balance.rtt - diff < 0) { throw { err: "The employee does not have enough holidays", code: "21" }; } else { employee.holiday_balance.rtt = employee.holiday_balance.rtt - diff; } } if (req.body.type == "congés payés") { if (employee.holiday_balance.congesPayes - diff < 0) { throw { err: "The employee does not have enough holidays", code: "22" }; } else { employee.holiday_balance.congesPayes = employee.holiday_balance.congesPayes - diff; } } employee.save(); } else { throw { err: "invalid date", code: "23" }; } const holiday = new HolidaySchema(req.body); await holiday.save(); res.status(201).send(holiday); NotificationController.NewHolidayRequestToManager(holiday.id); } catch (err) { console.log(err); res.status(400).send({ message: "Error when adding a holiday", error: err.err, code: err.code }); } }, async getHolidayByID(req, res) { const id = req.params.id; const populate = parseInt(req.query.populate); let holiday; try { if (populate) { holiday = await HolidaySchema.findById(id).populate( "id_requester_employee" ); } else { holiday = await HolidaySchema.findById(id); } if (!holiday) { throw { err: "Invalid holiday id", code: "24" }; } res.send(holiday); } catch (err) { res.status(400).send({ message: "Error when geting a holiday by id", error: err.err, code: err.code }); } }, async getHolidaysByUser(req, res) { const id = req.params.id; try { employee = await EmployeeSchema.findById(id) if (!employee) { throw { err: "Invalid employee id", code: "25" }; } holidays = await HolidaySchema.find({ id_requester_employee: id }); res.send(holidays); } catch (err) { res.status(400).send({ message: "Error when geting a holiday by id", error: err.err, code: err.code }); } }, async getAllHolidays(req, res) { const populate = parseInt(req.query.populate); let holidays; try { if (populate) { holidays = await HolidaySchema.find(req.body).populate( "id_requester_employee" ); } else { holidays = await HolidaySchema.find(req.body); } if (!holidays) { throw { err: `holidays not found`, code: "26" }; } res.send(holidays); } catch (err) { res.status(400).send({ message: "Error when geting all holiday", error: err.err, code: err.code }); } }, async getHolidaysByService(req, res) { const idService = req.params.idService; console.log(idService); const populate = parseInt(req.query.populate); let holidays; try { if (populate) { holidays = await HolidaySchema.find(req.body).populate( "id_requester_employee" ); } else { holidays = await HolidaySchema.find(req.body); } let holidaysService = []; holidays.forEach((holiday) => { if (holiday.id_requester_employee.id_service == idService) { holidaysService.push(holiday); } }); if (!holidays) { throw { err: `holidays not found`, code: "27" }; } res.send(holidaysService); } catch (err) { res.status(400).send({ message: "Error when geting holiday by service", error: err.err, code: err.code }); } }, async deleteHoliday(req, res) { const id = req.params.id; try { holiday = await HolidaySchema.findById(id); if (!holiday) { throw { err: "Invalid holiday id", code: "28" }; } diff = dayDiff(holiday.starting_date, holiday.ending_date); let employee = await EmployeeSchema.findById( holiday.id_requester_employee ); if (holiday.type == "rtt") { employee.holiday_balance.rtt = parseInt(employee.holiday_balance.rtt) + parseInt(diff); } if (holiday.type == "congés payés") { employee.holiday_balance.congesPayes = parseInt(employee.holiday_balance.congesPayes) + parseInt(diff); } holiday.remove(); employee.save(); res.send({ message: `Holiday deleted`, }); } catch (err) { res.status(400).send({ message: "Error when deleting a holiday", error: err.err, code: err.code }); } }, async deleteAllHolidays(req, res) { try { await HolidaySchema.deleteMany(); res.send({ message: `All holidays have been delete`, }); } catch (error) { res.status(400).send({ message: "Error when deleting all holiday", error: err, }); } }, async updateHoliday(req, res) { const id = req.params.id; try { if ( !checkKeys(req.body, [ "validation_date", "note", "starting_date", "ending_date", "current_date", "type", ]) ) { throw { err: "Invalid keys", code: "29" }; } employeeExist = await EmployeeSchema.findById(req.body.id_requester_employee) if (!employeeExist && req.body.id_requester_employee) { throw { err: "Invalid employee id", code: "30" }; } holiday = await HolidaySchema.findById(id); if (!holiday) { throw { err: "Invalid holiday id", code: "31" }; } //rend les jours de congés diff = dayDiff(holiday.starting_date, holiday.ending_date); let employee = await EmployeeSchema.findById(holiday.id_requester_employee); if (holiday.type == "rtt") { employee.holiday_balance.rtt = parseInt(employee.holiday_balance.rtt) + parseInt(diff); } if (holiday.type == "congés payés") { employee.holiday_balance.congesPayes = parseInt(employee.holiday_balance.congesPayes) + parseInt(diff); } //retire les jours de congés par rapport a la request newdiff = dayDiff(req.body.starting_date, req.body.ending_date); if (req.body.type == "rtt") { employee.holiday_balance.rtt = parseInt(employee.holiday_balance.rtt) - parseInt(newdiff); } if (req.body.type == "congés payés") { employee.holiday_balance.congesPayes = parseInt(employee.holiday_balance.congesPayes) - parseInt(newdiff); } employee.save(); updateKeys = Object.keys(req.body); updateKeys.forEach((key) => (holiday[key] = req.body[key])); await holiday.save(); res.send({ message: `Holiday ${id} was updated !`, }); } catch (err) { res.status(400).send({ message: "Error when updating a holiday", error: err.err, code: err.code }); } }, async updateHolidayStatus(req, res) { const id = req.params.id; const status = req.params.status; try { if (!checkKeys({ status }, ["status"])) { throw { err: "Invalid keys", code: "32" }; } holiday = await HolidaySchema.findById(id); if (!holiday) { throw { err: "Invalid holiday id", code: "33" }; } statusHolidayCache = holiday.status; holiday.status = status; await holiday.save(); res.send({ message: `Holiday status ${id} was updated !`, }); if (statusHolidayCache != status) { NotificationController.HolidayRequestStatusUpdateToEmployee(id); NotificationController.HolidayRequestStatusUpdateToManager(id); if (status == "prévalidée") { NotificationController.NewHolidayRequestToRh(id); } } } catch (err) { res.status(400).send({ message: "Error when updating a holiday", error: err.err, code: err.code, }); } }, }; function checkKeys(body, allowedKeys) { const updatesKeys = Object.keys(body); return updatesKeys.every((key) => allowedKeys.includes(key)); } function dayDiff(d1, d2) { d1 = new Date(d1); d2 = new Date(d2); d1 = d1.getTime() / 86400000; d2 = d2.getTime() / 86400000; return new Number(d2 - d1).toFixed(0); } module.exports = HolidayController; <file_sep>/src/middlewares/hasAccessRole.js const EmployeeSchema = require("../models/Employee"); const hasAccessRole = (AuthorizedRole) => { return async (req, res, next) => { let matchRole = false; await AuthorizedRole.forEach(role => { if(role == req.employee.id_role.name) { matchRole = true; } }); if(matchRole == true) { next(); } else { res.status(401).send({ message: "Unauthorised role" }); } } }; module.exports = hasAccessRole;<file_sep>/index.js require("dotenv").config(); require("./src/db/mongoose"); const express = require("express"); const path = require("path"); const publicDirectoryPath = path.join(__dirname, "public"); const holidayRoutes = require("./src/routes/Holiday"); const employeeRoutes = require("./src/routes/Employee"); const loginRoutes = require("./src/routes/Login"); const serviceRoutes = require("./src/routes/Service"); const app = express(); const port = process.env.APP_PORT || 4000; app.use(express.static(publicDirectoryPath)); app.use(express.json()); app.use("/api", holidayRoutes); app.use("/api", employeeRoutes); app.use("/api", loginRoutes); app.use("/api", serviceRoutes); app.get(publicDirectoryPath + "/img"); app.listen(port, () => { console.log(`App running on port ${port}`); }); <file_sep>/src/db/mongoose.js const mongoose = require("mongoose"); mongoose.connect( "mongodb://" + process.env.DB_USERNAME + ":" + process.env.DB_PASSWORD + "@" + process.env.DB_HOST + "/" + process.env.DB_NAME + "?authSource=admin", { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false } ); const db = mongoose.connection; db.on("error", console.error.bind(console, "connection error:")); db.once("open", function () { console.log("connexion mongodb réussi"); });
ae7b4ede228a178000f37c8ba6574ddb25a33942
[ "JavaScript" ]
9
JavaScript
LoicHuart/EndemikAPI
31347b550ee723a143399793510767559a0d2e3f
6ac469c7fcc08a1e0a0c3ba8ea65e5c6ea73c8c9
refs/heads/master
<file_sep># encoding utf-8 ## SOLVED 2013/12/24 ## 443839 # Surprisingly there are only three numbers that can be written as the sum of # fourth powers of their digits: # 1634 = 1^4 + 6^4 + 3^4 + 4^4 # 8208 = 8^4 + 2^4 + 0^4 + 8^4 # 9474 = 9^4 + 4^4 + 7^4 + 4^4 # As 1 = 14 is not a sum it is not included. # The sum of these numbers is 1634 + 8208 + 9474 = 19316. # Find the sum of all the numbers that can be written as the sum of fifth powers # of their digits. POWER = 5 def euler(): accumulator = 0 for number in range(2, POWER * 9 ** POWER + 1): if is_sum_of_power_digits(number, POWER): accumulator += number return accumulator def is_sum_of_power_digits(number, power): starting_number = number accumulator = 0 while number > 0: digit = number % 10 accumulator += digit ** power number //= 10 return accumulator == starting_number <file_sep># encoding=utf-8 ## SOLVED 2014/12/01 ## 8319823 # Euler's Totient function, φ(n) [sometimes called the phi function], is used # to determine the number of positive numbers less than or equal to n which are # relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less # than nine and relatively prime to nine, φ(9)=6. # The number 1 is considered to be relatively prime to every positive number, # so φ(1)=1. # Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation # of 79180. # Find the value of n, 1 < n < 10**7, for which φ(n) is a permutation of n and # the ratio n/φ(n) produces a minimum. import helpers.sequence as sequence import helpers.prime as prime import helpers.discreet as discreet import math HIGHEST_N = 10 ** 7 def euler(): middle = math.ceil(math.sqrt(HIGHEST_N)) for p in range(middle, 0, -1): if prime.is_prime(p): for q in range(middle + 1, math.ceil((10 ** 7) / p)): if prime.is_prime(q): n = p * q t = discreet.totient(n) if sequence.is_permutation(str(n), str(t)): return n <file_sep># encoding=utf-8 ## SOLVED 2015/01/10 ## 1818 # A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a # fly, F, sits in the opposite corner. By travelling on the surfaces of the room # the shortest "straight line" distance from S to F is 10 and the path is shown # on the diagram. # [drawing of the cuboid] # However, there are up to three "shortest" path candidates for any given cuboid # and the shortest route doesn't always have integer length. # It can be shown that there are exactly 2060 distinct cuboids, ignoring # rotations, with integer dimensions, up to a maximum size of M by M by M, for # which the shortest route has integer length when M = 100. This is the least # value of M for which the number of solutions first exceeds two thousand; the # number of solutions when M = 99 is 1975. # Find the least value of M such that the number of solutions first exceeds one # million. import math # when to stop looking for more matches MAX = 1000000 def euler(): # number of matches found so far matches = 0 # size of the longest side a = 1 # for each a while True: # x = b + c, if the prism is of size a by b by c for x in range(1, 2 * a + 1): # shortest path inside the prism, L^2 = a^2 + (b + c)^2 = a^2 + x^2 L = math.sqrt(a * a + x * x) if int(L) == L: # add the number of possible (b,c) combinations that are shorter # than a, and that satisfy x = b + c matches += count_ways(x, a) # value found, return the length of the longest side of the prism if matches > MAX: return a a += 1 # return the number of (a,b) sorted integers pairs, such that a <= maximum and # b <= maximum, and a + b = n. def count_ways(n, maximum): k = n // 2 if maximum < n: k -= (n - maximum - 1) return k<file_sep>#encoding=utf-8 ## SOLVED 2014/04/10 ## 5777 # It was proposed by <NAME> that every odd composite number can be # written as the sum of a prime and twice a square. # 9 = 7 + 2×12 # 15 = 7 + 2×22 # 21 = 3 + 2×32 # 25 = 7 + 2×32 # 27 = 19 + 2×22 # 33 = 31 + 2×12 # It turns out that the conjecture was false. # What is the smallest odd composite that cannot be written as the sum of a prime # and twice a square? import math import helpers.prime as primeutils def euler(): # for each odd number starting at 3 composite = 3 while True: # 'found' will be True iff the composite can be expressed as the sum # of a prime and two times a square found = False # try all prime numbers that are less than the composite number for prime in primeutils.primes(composite): # calculate the square square = (composite - prime) // 2 # it must have an integer square root for it to be valid root = math.sqrt(square) if root == int(root): found = True break # if it cannot be expressed as the sum of blah blah... if not found: # we found the answer return composite # next odd number composite += 2 <file_sep># encoding=utf-8 ## SOLVED 2017/07/08 ## 14234 # The points P (x1, y1) and Q (x2, y2) are plotted at integer co-ordinates and # are joined to the origin, O(0,0), to form ΔOPQ. # There are exactly fourteen triangles containing a right angle that can be # formed when each co-ordinate lies between 0 and 2 inclusive; that is, 0 ≤ x1, # y1, x2, y2 ≤ 2. # Given that 0 ≤ x1, y1, x2, y2 ≤ 50, how many right triangles can be formed? from helpers.discreet import gcd N = 50 def euler(): # there are 3*N**2 triangles that have one of those 3 shapes: # o--o o o # | / /| |\ # |/ / | | \ # o o--o o--o acc = 3 * N ** 2 # The other triangles have a first point with direction vector d: # d = (a, b) = (x, y) / gcd(x, y) # # And the second line is perpendicular to d. So it has a direction vector # of either u or v, and fits within the dimensions of the grid: # u = (+b, -a) # v = (-b, +a) # # So for each point (x, y) with x!=0 and y!=0, we just count how many # multiples of u or v can fit in the grid, starting at origin point (x, y). for y in range(1, N + 1): for x in range(1, N + 1): divisor = int(gcd(x, y)) (a, b) = (x // divisor, y // divisor) left_triangles = min(y // a, (N - x) // b) right_triangles = min((N - y) // a, x // b) acc += left_triangles acc += right_triangles return acc <file_sep># encoding=utf-8 ## SOLVED 2015/01/02 ## 190569291 # It is possible to write five as a sum in exactly six different ways: # 4 + 1 # 3 + 2 # 3 + 1 + 1 # 2 + 2 + 1 # 2 + 1 + 1 + 1 # 1 + 1 + 1 + 1 + 1 # How many different ways can one hundred be written as a sum of at least two # positive integers? import helpers.discreet as discreet MAX = 100 def euler(): return discreet.partition(MAX) - 1 <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 31875000 # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. import math TARGET = 1000 def euler(): # for each (a, b) pair for a in range(1, TARGET): for b in range(1, TARGET): # calculate c c = math.sqrt(a * a + b * b) # return if the pair satisfies a+b+c=1000 and c is natural if c == int(c) and a + b + c == TARGET: return a * b * int(c) <file_sep># encoding=utf-8 ## SOLVED 2014/01/19 ## 7652413 # We shall say that an n-digit number is pandigital if it makes use of all the # digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is # also prime. # What is the largest n-digit pandigital prime that exists? import helpers.prime as prime import helpers.sequence as sequence def euler(): # highest pandigital prime found so far highest_pandigital = 0 # for number of digits from 4 to 9 for length in range(4, 9): # generate the list of digits from 1 to n digits = list(range(1, length + 1)) # for each permutation of these digits for permutation in sequence.permutations(digits): number = int(''.join(str(digit) for digit in permutation)) # check if the number is prime if prime.is_prime(number): # set the new value of the highest pandigital prime if needed highest_pandigital = max(number, highest_pandigital) # return the highest pandigital prime found return highest_pandigital <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 142913828922 # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. import helpers.prime as prime MAX = 2000000 def euler(): # calculate and return the sum of the primes return sum(prime.primes(MAX)) <file_sep># encoding=utf-8 ## SOLVED 2013/12/23 ## 983 # A unit fraction contains 1 in the numerator. The decimal representation of the # unit fractions with denominators 2 to 10 are given: # 1/2 = 0.5 # 1/3 = 0.(3) # 1/4 = 0.25 # 1/5 = 0.2 # 1/6 = 0.1(6) # 1/7 = 0.(142857) # 1/8 = 0.125 # 1/9 = 0.(1) # 1/10 = 0.1 # Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be # seen that 1/7 has a 6-digit recurring cycle. # Find the value of d < 1000 for which 1/d contains the longest recurring cycle # in its decimal fraction part. MAX = 1000 def euler(): # longest length for a cycle longest_cycle_length = 0 # divisor that generates that cycle length longest_cycle_divisor = 0 # for each divisor for divisor in range(2, MAX): # calculate the length of the fraction's cycle cycle_length = fraction_cycle_length(divisor) # if it's higher than any value seen before if cycle_length > longest_cycle_length: # keep in memory the cycle length, and which divisor generates it longest_cycle_length = cycle_length longest_cycle_divisor = divisor # return the divisor that generates the longest cycle return longest_cycle_divisor def fraction_cycle_length(denominator): """Return the number of digits in the cycle part of a fraction. For instance, in 1/3 (0.3333...), '3' is the recurring cycle. The length of that cycle is 1. In 1/7 (0.142857142857142...), '142857' is the recuring cycle. The length of the cycle is 6. """ # counter for the number of digits generated digit_count = 0 # accumulator for the current number to be divided accumulator = 1 # values encountered for the accumulator accumulators = [] # while there is a remainder to the division while accumulator != 0: # if the current accumulator can be divided by the denominator if accumulator >= denominator: # the digit to add to the number is the result of that division digit = accumulator // denominator # if we have never had that accumulator before if not accumulator in accumulators: accumulators.append(accumulator) else: # if we have already met that accumulator before, return the # number of digits between two occurences return digit_count - accumulators.index(accumulator) # subtract the result of the division from the accumulator accumulator -= digit * denominator # add a digit to the digit count digit_count += 1 else: # the current accumulator cannot be divided by the denominator, # multiply it by 10 accumulator *= 10 # divides evenly, 0 cycle length return 0 <file_sep>#encoding=utf-8 ## SOLVED 2014/04/12 ## 296962999629 # The arithmetic sequence, 1487, 4817, 8147, in which each of the terms # increases by 3330, is unusual in two ways: (i) each of the three terms are # prime, and, (ii) each of the 4-digit numbers are permutations of one another. # There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, # exhibiting this property, but there is one other 4-digit increasing sequence. # What 12-digit number do you form by concatenating the three terms in this # sequence? import helpers.prime as prime import helpers.sequence as sequence # number of digits for each prime number DIGITS = 4 # leap between two prime numbers that should also be permutations of eachother LEAP = 3330 def euler(): # for each of the two possible sets of answers for first_prime, second_prime, third_prime in prime_sets(): # reject the first set of answers if first_prime != 1487: # return the 12 digits xs = (first_prime, second_prime, third_prime) return int(''.join(map(str, xs))) def prime_sets(): """Yield all sets of possible answers for problem #49. Will 'yield' three arguments: the first, second and third prime. These three prime numbers are separated by exactly LEAP, and are permutations of each other. The three primes have exactly 4 digits.""" # for each prime number for first_prime in prime.primes(10 ** DIGITS // 3): # ensure that it has enough digits if first_prime > 10 ** (DIGITS - 1): # calculate the other two primes second_prime = first_prime + LEAP third_prime = first_prime + 2 * LEAP # invalid if they're not permutations of eachother if not is_int_permutation(first_prime, second_prime) or \ not is_int_permutation(first_prime, third_prime): continue # invalid if they're not actually primes if not prime.is_prime(second_prime) or \ not prime.is_prime(third_prime): continue # if this is reached, the three primes make up a possible answer yield first_prime, second_prime, third_prime def is_int_permutation(x, y): """Return True iff two integers are permutations of eachother's digits.""" return sequence.is_permutation(list(str(x)), list(str(y))) <file_sep># encoding=utf-8 ## SOLVED 2013/12/23 ## 669171001 # Starting with the number 1 and moving to the right in a clockwise direction a # 5 by 5 spiral is formed as follows: # 21 22 23 24 25 # 20 7 8 9 10 # 19 6 1 2 11 # 18 5 4 3 12 # 17 16 15 14 13 # It can be verified that the sum of the numbers on the diagonals is 101. # What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral # formed in the same way? SIZE = 1001 def euler(): # accumulator for the sum of the numbers on the diagonal accumulator = 1 # current number number = 1 # for each difference between numbers, from 2 to SIZE for leap in range(2, SIZE + 1, 2): # for each corner for i in range(4): number += leap # add to the accumulator accumulator += number # return the sum accumulator return accumulator <file_sep># encoding=utf-8 ## SOLVED 2013/12/24 ## 40730 # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. # Find the sum of all numbers which are equal to the sum of the factorial of # their digits. # Note: as 1! = 1 and 2! = 2 are not sums they are not included. MAX = 362881 def euler(): accumulator = 0 for number in range(3, MAX): if is_valid(number): accumulator += number return accumulator def is_valid(number): sum_of_digit_factorials = sum(factorial(int(c)) for c in str(number)) return number == sum_of_digit_factorials def factorial(n): accumulator = 1 for i in range(2, n + 1): accumulator *= i return accumulator <file_sep>#encoding=utf-8 ## SOLVED 2014/04/10 ## 134043 # The first two consecutive numbers to have two distinct prime factors are: # 14 = 2 × 7 # 15 = 3 × 5 # The first three consecutive numbers to have three distinct prime factors are: # 644 = 2² × 7 × 23 # 645 = 3 × 5 × 43 # 646 = 2 × 17 × 19. # Find the first four consecutive integers to have four distinct prime factors. # What is the first of these numbers? import helpers.prime as prime FACTOR_COUNT = 4 def euler(): # for each integer n n = 2 while True: # 'is_answer' will be True iff all FACTOR_COUNT consecutive numbers # have exactly FACTOR_COUNT distinct prime factors is_answer = True # for each of those numbers for offset in range(0, FACTOR_COUNT): # it's not the right answer if it doesn't have the right amount of # factors if prime_factor_count(n + offset) != FACTOR_COUNT: is_answer = False n += offset break # return the answer if found if is_answer: return n # increment n n += 1 def prime_factor_count(n): """Returns the number of distinct prime factors of a number.""" return len(prime.multiset_prime_factors(n)) <file_sep># encoding=utf-8 ## SOLVED 2014/11/30 ## 6531031914842725 # Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, # and each line adding to nine. # Working clockwise, and starting from the group of three with the numerically # lowest external node (4,3,2 in this example), each solution can be described # uniquely. For example, the above solution can be described by the set: 4,3,2; # 6,2,1; 5,1,3. # It is possible to complete the ring with four different totals: 9, 10, 11, # and 12. There are eight solutions in total. # Total Solution Set # 9 4,2,3; 5,3,1; 6,1,2 # 9 4,3,2; 6,2,1; 5,1,3 # 10 2,3,5; 4,5,1; 6,1,3 # 10 2,5,3; 6,3,1; 4,1,5 # 11 1,4,6; 3,6,2; 5,2,4 # 11 1,6,4; 5,4,2; 3,2,6 # 12 1,5,6; 2,6,4; 3,4,5 # 12 1,6,5; 3,5,4; 2,4,6 # By concatenating each group it is possible to form 9-digit strings; the # maximum string for a 3-gon ring is 432621513. # Using the numbers 1 to 10, and depending on arrangements, it is possible to # form 16- and 17-digit strings. What is the maximum 16-digit string for a # "magic" 5-gon ring? from helpers.sequence import n_permutations # numbers used in the magic pentagon NUMBERS = list(range(1,11)) # length of the solution's string SOLUTION_LENGTH = 16 def euler(): # return value: maximum solution string highest = "" # for every starting set of 3 numbers for start in n_permutations(NUMBERS, 3): # numbers that aren't in 'start' remaining = set(NUMBERS) - set(start) # for each of the numbers that aren't in 'start' for x in remaining: # try to chain over it for c in chain(start, remaining, x): # convert to a string s = [str(n) for l in c for n in l] s = ''.join(s) # check if it's a valid solution is_valid = len(s) == SOLUTION_LENGTH and sum(c[0]) == sum(c[-1]) # if valid, set new maximum if appropriate if is_valid and s > highest: highest = s # return maximum return highest # iterator for all solutions of the pentagon def chain(start, rem, x): for c in chain_helper(start, rem, x): # add the second number from 'start' to the end of the chain c[-1].append(start[1]) # add 'start' to the start of the chain c = [start] + c # check that the last sub-chain actually works in the chain if sum(c[0]) != sum(c[-1]): continue # sort the chain's sub-chains by their numerical value c = sorted(c) # reverse the order for the last sub-chains, to make them ascending # while keeping the first element as the lowest sub-chain c[1:] = c[-1:0:-1] # the sums must be equal, even in the last element yield c def chain_helper(start, rem, x): # no numbers remaining, pass if not rem: return # calculate y for the next sequence of 3 numbers, [y,start[2],x] y = start[0] + start[1] - x # if y is actually in the remaining numbers if y in rem and x != y: # args for recursive call new_rem = rem - {x, y} new_start = [y, start[2], x] if len(new_rem) == 1: # only 1 element remaining: complete the chain a = list(new_rem)[0] yield [new_start] + [[a, new_start[2]]] else: # try to chain recursively for new_x in new_rem: for c in chain_helper(new_start, new_rem, new_x): yield [new_start] + c <file_sep># encoding=utf-8 ## SOLVED 2014/11/30 ## 7273 # By starting at the top of the triangle below and moving to adjacent numbers # on the row below, the maximum total from top to bottom is 23. # 3 # 7 4 # 2 4 6 # 8 5 9 3 # That is, 3 + 7 + 4 + 9 = 23. # Find the maximum total from top to bottom in triangle.txt (right click and # 'Save Link/Target As...'), a 15K text file containing a triangle with # one-hundred rows. # NOTE: This is a much more difficult version of Problem 18. It is not possible # to try every route to solve this problem, as there are 299 altogether! If you # could check one trillion (1012) routes every second it would take over twenty # billion years to check them all. There is an efficient algorithm to solve it. # ;o) import helpers.file as fileutils def euler (): # read the pyramid from the file pyramid = fileutils.list_from_file ('data/067.txt') # for each row, starting at the second from the bottom and going up for y in range (len (pyramid) - 2, -1, -1): # for each element of that row for x in range (y + 1): # add to it the highest of the two directly below it pyramid [y][x] += max (pyramid [y + 1][x], pyramid [y + 1][x + 1]) # return the value at the top of the pyramid return pyramid [0][0] <file_sep># encoding=utf-8 ## SOLVED 2015/01/12 ## 1097343 # The smallest number expressible as the sum of a prime square, prime cube, and # prime fourth power is 28. In fact, there are exactly four numbers below fifty # that can be expressed in such a way: # 28 = 22 + 23 + 24 # 33 = 32 + 23 + 24 # 49 = 52 + 23 + 24 # 47 = 22 + 33 + 24 # How many numbers below fifty million can be expressed as the sum of a prime # square, prime cube, and prime fourth power? import helpers.prime as prime import math MAX = 50000000 def euler(): # set of matches found matches = set() # the primes can never exceed this value limit = math.ceil(math.sqrt(MAX)) # for each (a,b,c) triplet such that a^2+b^3+c^4 < MAX for a in prime.primes(limit): if a * a >= MAX: break for b in prime.primes(limit): if a * a + b * b * b >= MAX: break for c in prime.primes(limit): k = a * a + b * b * b + c * c * c * c if k >= MAX: break matches.add(k) # return the number of matches return len(matches) <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 4613732 # Each new term in the Fibonacci sequence is generated by adding the previous # two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. MAX = 4000000 def euler(): # previous and current fibonacci sequence numbers previous_number = 0 current_number = 1 # sum accumulator accumulator = 0 # for each fibonacci number until MAX while current_number < MAX: # add to the sum if it's an even number if current_number % 2 == 0: accumulator += current_number previous_number += current_number current_number, previous_number = previous_number, current_number # return the sum return accumulator <file_sep># encoding=utf-8 ## SOLVED 2013/12/24 ## 100 # The fraction 49/98 is a curious fraction, as an inexperienced mathematician in # attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is # correct, is obtained by cancelling the 9s. # We shall consider fractions like, 30/50 = 3/5, to be trivial examples. # There are exactly four non-trivial examples of this type of fraction, less # than one in value, and containing two digits in the numerator and denominator. # If the product of these four fractions is given in its lowest common terms, # find the value of the denominator. import fractions def euler(): accumulator = fractions.Fraction(1, 1) for digit_1 in range(1, 10): for digit_2 in range(1, 10): for digit_3 in range(1, 10): if digit_1 != digit_2 or digit_1 != digit_3: numerator = digit_1 * 10 + digit_2 denominator = digit_2 * 10 + digit_3 original_fraction = fractions.Fraction(numerator, denominator) numerator = digit_1 denominator = digit_3 reduced_fraction = fractions.Fraction(numerator, denominator) if original_fraction == reduced_fraction: accumulator *= original_fraction return accumulator.denominator <file_sep>class PokerHand: """Hand in a game of poker: an ordered list of 5 PokerCard objects.""" def __init__(self, cards): """Main constructor. Takes a list of 5 PokerCard objects.""" def get_symbol_value(card): return card.symbol_value self.cards = sorted(cards, key = get_symbol_value) def symbol_counts(self): """Return a dictionary associating each card symbol to the number of occurrences of that card in the hand.""" dictionary = {} for card in self.cards: if card.symbol in dictionary: dictionary[card.symbol] += 1 else: dictionary[card.symbol] = 1 return dictionary def is_royal_flush(self): """Return True iff this is a royal flush (a straight flush with an ace).""" if not self.is_flush(): return False return self.is_straight() and self.cards[-1].symbol == 'A' def is_straight_flush(self): """Returns True iff this is a straight flush (both a straight and a flush).""" return self.is_straight() and self.is_flush() def is_four_of_a_kind(self): """Return True iff this hand has 4 cards with the same symbol.""" counts = self.symbol_counts() return 4 in counts.values() def is_full_house(self): """Return True iff this hand has both three-of-a-kind and two-of-a-kind.""" counts = self.symbol_counts() return 3 in counts.values() and 2 in counts.values() def is_flush(self): """Return True iff all cards are of the same suit.""" for card in self.cards: if card.suit != self.cards[0].suit: return False return True def is_straight(self): """Return True iff all cards are consecutive.""" for offset,card in enumerate(self.cards): if card.symbol_value != self.cards[0].symbol_value + offset: return False return True def is_three_of_a_kind(self): """Return True iff there are exactly 3 occurrences of a card.""" counts = self.symbol_counts() return 3 in counts.values() def is_two_pairs(self): """Return True iff there are exactly 2 occurrences of two cards.""" counts = self.symbol_counts() pair_count = 0 for count in counts.values(): if count == 2: pair_count += 1 return pair_count == 2 def is_one_pair(self): """Return True iff there are exactly 2 occurrences of a card.""" counts = self.symbol_counts() return 2 in counts.values() class PokerCard: """Card from a poker game: has a symbol and a suit, both a single character.""" def __init__(self, symbol, suit): """Main constructor.""" self.symbol = symbol.upper() self.suit = suit @property def symbol_value(self): """Wrapper for `value_of_symbol' or the `symbol' field.""" return value_of_symbol(self.symbol) def value_of_symbol(symbol): """Return an integer representing the "rank" of a card's symbol. For instance, '2' maps to 2, and 'J' maps to 11. Consecutive cards have consecutive integers.""" if symbol in '23456789': return int(symbol) else: return ({ 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14 })[symbol] def read_poker_line(line_string): """Return a PokerHand object corresponding to the line from the file `poker.txt'.""" # list of all the cards card_names = line_string.split(" ") cards = list(PokerCard(card_name[:-1], card_name[-1:]) \ for card_name in card_names) # lists of hands for the players player_1_hand_list = cards[:5] player_2_hand_list = cards[5:] # hands for the players player_1_hand = PokerHand(player_1_hand_list) player_2_hand = PokerHand(player_2_hand_list) # return a tuple with the hands for the two players return (player_1_hand, player_2_hand) def is_winner_player_1(hand_1, hand_2): """Return True iff player 1 (hand_1) wins over player 2 (hand_2). hand_1 and hand_2 should be PokerHand objects.""" hands = (hand_1, hand_2) symbol_counts = (hand_1.symbol_counts(), hand_2.symbol_counts()) # royal flush if hand_1.is_royal_flush(): return True if hand_2.is_royal_flush(): return False # straight flush if hand_1.is_straight_flush(): if not hand_2.is_straight_flush(): return True elif hand_1.cards[-1].symbol_value != hand_2.cards[-1].symbol_value: return hand_1.cards[-1].symbol_value > hand_2.cards[-1].symbol_value elif hand_2.is_straight_flush(): return False # four-of-a-kind if hand_1.is_four_of_a_kind(): if not hand_2.is_four_of_a_kind(): return True elif hand_1.cards[1].symbol_value != hand_2.cards[1].symbol_value: return hand_1.cards[1].symbol_value > hand_2.cards[1].symbol_value elif hand_2.is_four_of_a_kind(): return False # full house if hand_1.is_full_house(): if not hand_2.is_full_house(): return True else: twos = [] threes = [] for counts in symbol_counts: for symbol,count in counts.items(): if count == 3: threes.append(value_of_symbol(symbol)) if count == 2: twos.append(value_of_symbol(symbol)) if threes[0] > threes[1]: return True elif threes[0] < threes[1]: return False else: if twos[0] > twos[1]: return True elif twos[1] > twos[2]: return False elif hand_2.is_full_house(): return False # flush if hand_1.is_flush(): if not hand_2.is_flush(): return True elif hand_2.is_flush(): return False # straight if hand_1.is_straight(): if not hand_2.is_straight(): return True elif hand_1.cards[-1].symbol_value != hand_2.cards[-1].symbol_value: return hand_1.cards[-1].symbol_value > hand_2.cards[-1].symbol_value elif hand_2.is_straight(): return False # three of a kind if hand_1.is_three_of_a_kind(): if not hand_2.is_three_of_a_kind(): return True else: threes = [] for counts in symbol_counts: for symbol,count in counts.items(): if count == 3: threes.append(value_of_symbol(symbol)) if threes[0] > threes[1]: return True elif threes[0] < threes[1]: return False elif hand_2.is_three_of_a_kind(): return False # two pairs if hand_1.is_two_pairs(): if not hand_2.is_two_pairs(): return True else: twos = [[], []] i = 0 for counts in symbol_counts: for symbol,count in counts.items(): if count == 2: twos[i].append(value_of_symbol(symbol)) i += 1 twos = [sorted(xs) for xs in twos] if twos[0][1] > twos[1][1]: return True elif twos[0][1] < twos[1][1]: return False elif twos[0][0] > twos[1][0]: return True elif twos[0][0] < twos[1][0]: return False elif hand_2.is_two_pairs(): return False # pair if hand_1.is_one_pair(): if not hand_2.is_one_pair(): return True else: twos = [] for counts in symbol_counts: for symbol,count in counts.items(): if count == 2: twos.append(value_of_symbol(symbol)) if twos[0] > twos[1]: return True if twos[0] < twos[1]: return False elif hand_2.is_one_pair(): return False # highest card for i in range (-1, -6, -1): if hand_1.cards[i].symbol_value > hand_2.cards[i].symbol_value: return True elif hand_1.cards[i].symbol_value < hand_2.cards[i].symbol_value: return False <file_sep># encoding=utf-8 ## SOLVED 2014/11/25 ## 1322 # All square roots are periodic when written as continued fractions. # [Examples...] # It can be seen that the sequence is repeating. For conciseness, we use the # notation √23 = [4;(1,3,1,8)], to indicate that the block (1,3,1,8) repeats # indefinitely. # The first ten continued fraction representations of (irrational) square roots # are: # √2=[1;(2)], period=1 # √3=[1;(1,2)], period=2 # √5=[2;(4)], period=1 # √6=[2;(2,4)], period=2 # √7=[2;(1,1,1,4)], period=4 # √8=[2;(1,4)], period=2 # √10=[3;(6)], period=1 # √11=[3;(3,6)], period=2 # √12= [3;(2,6)], period=2 # √13=[3;(1,1,1,1,6)], period=5 # Exactly four continued fractions, for N ≤ 13, have an odd period. # How many continued fractions for N ≤ 10000 have an odd period? from math import sqrt # highest number to check for the period HIGHEST_SQUARE = 10000 def euler(): solution_count = 0 for n in range(2, HIGHEST_SQUARE + 1): if continued_fraction(n) % 2 == 1: solution_count += 1 return solution_count # return the number of partial values in the continued fraction for the square # root of n # # use the algorithm described on this Wikipedia page: # http://en.wikipedia.org/wiki/Methods_of_computing_square_roots # in the "Continued fraction expansion" section def continued_fraction(n): if int(sqrt(n)) == sqrt(n): return 0 length = 0 m = 0 d = 1 a = int(sqrt(n)) a0 = a while a != 2 * a0: m = d * a - m d = (n - m * m) / d a = int((a0 + m) / d) length += 1 return length <file_sep># encoding=utf-8 ## SOLVED 2013/12/23 ## 2783915460 # A permutation is an ordered arrangement of objects. For example, 3124 is one # possible permutation of the digits 1, 2, 3 and 4. If all of the permutations # are listed numerically or alphabetically, we call it lexicographic order. The # lexicographic permutations of 0, 1 and 2 are: # 012 021 102 120 201 210 # What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, # 5, 6, 7, 8 and 9? import helpers.sequence as sequence ANSWER_INDEX = 1000000 def euler(): # list of digits tokens = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # current permutation counter index = 0 # for each permutation of the digits for permutation in sequence.permutations(tokens): index += 1 # if the permutation is the one we want if index == ANSWER_INDEX: # return it, as a string return ''.join(map(str, permutation)) <file_sep># encoding=utf-8 ## SOLVED 2013/12/24 ## 9183 # Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: # 22=4, 23=8, 24=16, 25=32 # 32=9, 33=27, 34=81, 35=243 # 42=16, 43=64, 44=256, 45=1024 # 52=25, 53=125, 54=625, 55=3125 # If they are then placed in numerical order, with any repeats removed, we get # the following sequence of 15 distinct terms: # 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 # How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 # and 2 ≤ b ≤ 100? MAX = 100 def euler(): cache = {} for base in range(2, MAX + 1): accumulator = base for exponent in range(2, MAX + 1): accumulator *= base cache [accumulator] = True return len(cache) <file_sep># encoding=utf-8 ## SOLVED 2021/03/20 ## 518408346 # It is easily proved that no equilateral triangle exists with integral length # sides and integral area. However, the almost equilateral triangle 5-5-6 has an # area of 12 square units. # We shall define an almost equilateral triangle to be a triangle for which two # sides are equal and the third differs by no more than one unit. # Find the sum of the perimeters of all almost equilateral triangles with # integral side lengths and area and whose perimeters do not exceed one billion # (1,000,000,000). import math MAX = 1000000000 def euler(): acc = 0 for m in range(1, math.isqrt(MAX)): # Only these 2 values of n might satisfy -1 <= 2*min(a,b)-c <= 1. n1 = round(math.sqrt((m * m + 1) / 3)) n2 = 2*m-round(math.sqrt(12*m*m))//2 for n in set([n1, n2]): # Euclid's formula for generating pythagorean triples. a = m * m - n * n b = 2 * m * n c = m * m + n * n a, b = min(a, b), max(a, b) p = a * 2 + c * 2 if p > MAX: continue if abs(2 * a - c) > 1: continue acc += p return acc <file_sep># encoding=utf-8 ## SOLVED 2014/11/29 ## 661 # Consider quadratic Diophantine equations of the form: # x^2 – Dy^2 = 1 # For example, when D=13, the minimal solution in x is 649^2 – 13×180^2 = 1. # It can be assumed that there are no solutions in positive integers when D is # square. # By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the # following: # 3^2 – 2×2^2 = 1 # 2^2 – 3×1^2 = 1 # 9^2 – 5×4^2 = 1 # 5^2 – 6×2^2 = 1 # 8^2 – 7×3^2 = 1 # Hence, by considering minimal solutions in x for D ≤ 7, the largest x is # obtained when D=5. # Find the value of D ≤ 1000 in minimal solutions of x for which the largest # value of x is obtained. from math import sqrt LIMIT = 1000 # see http://mathworld.wolfram.com/PellEquation.html def euler(): highest_x = 0 highest_D = 0 for D in range(2, LIMIT + 1): fract = continued_fraction(D) if fract[1]: # if not a square # length of the repeating partials r = len(fract[1]) # list for int(sqrt(D)), followed by partials a = [fract[0]] + fract[1] # p[n]/q[n] is the nth convergent fraction for sqrt(D) ps = [a[0], a[0] * a[1] + 1] qs = [1, a[1]] for n in range(1, 2 * r + 2): a_n = a[1 + (n % r)] ps.append(a_n * ps[n] + ps[n-1]) qs.append(a_n * qs[n] + qs[n-1]) # the solution x/y will always be a convergent for sqrt(D) x = ps[n + 1] y = qs[n + 1] if x * x - D * y * y == 1: if x > highest_x: highest_x = x highest_D = D break return highest_D def continued_fraction(S): if is_square(S): return (int(sqrt(S)), []) xs = [] m = m0 = 0 d = d0 = 1 a = a0 = int(sqrt(S)) while a != 2 * a0: m = d * a - m d = (S - m * m) / d a = int((a0 + m) / d) xs.append(a) return (a0, xs) def is_square(n): return int(sqrt(n)) == sqrt(n) <file_sep># encoding=utf-8 ## SOLVED 2013/12/25 ## 748317 # The number 3797 has an interesting property. Being prime itself, it is # possible to continuously remove digits from left to right, and remain prime at # each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: # 3797, 379, 37, and 3. # Find the sum of the only eleven primes that are both truncatable from left to # right and right to left. # NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. import helpers.prime as primeutils import helpers.sequence as sequence def euler(): accumulator = 0 primes_found = 0 cache = {} for prime in primeutils.all_primes(): if prime not in cache and is_truncatable(prime): primes_found += 1 accumulator += prime cache [prime] = True if primes_found == 11: break return accumulator def is_truncatable(number): if number < 10: return False for truncation in sequence.left_truncations(str(number)): if not primeutils.is_prime(int(truncation)): return False for truncation in sequence.right_truncations(str(number)): if not primeutils.is_prime(int(truncation)): return False return True <file_sep># encoding=utf-8 ## SOLVED 2013/12/21 ## 648 # n! means n x (n - 1) x ... x 3 x 2 x 1 # For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800, # and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. # Find the sum of the digits in the number 100! NUMBER = 100 def euler(): # return the sum of the digits of 100! return sum(map(int, str(factorial(NUMBER)))) def factorial(number): """Return the factorial of a number.""" accumulator = 1 for n in range(1, number + 1): accumulator *= n return accumulator <file_sep>#encoding=utf-8 ## SOLVED 2014/04/10 ## 16695334890 # The number, 1406357289, is a 0 to 9 pandigital number because it is made up of # each of the digits 0 to 9 in some order, but it also has a rather interesting # sub-string divisibility property. # Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note # the following: # d2d3d4=406 is divisible by 2 # d3d4d5=063 is divisible by 3 # d4d5d6=635 is divisible by 5 # d5d6d7=357 is divisible by 7 # d6d7d8=572 is divisible by 11 # d7d8d9=728 is divisible by 13 # d8d9d10=289 is divisible by 17 # Find the sum of all 0 to 9 pandigital numbers with this property. def euler(): # accumulator for the sum of these special pandigitals, final answer accumulator = 0 for pandigital in generate_valid_pandigitals(): accumulator += list_to_int(pandigital) return accumulator def list_to_int(digits): """Converts a list of integers corresponding to digits to a number. e.g.: list_to_int([4, 9, 2]) == 492. Args: digits: list of integers, which are the digits of the number.""" # start at 0 accumulator = 0 for digit in digits: # move the previous digits to the left accumulator *= 10 # append this digit accumulator += int(digit) # return the number return accumulator def generate_valid_pandigitals(): """Yields all the pandigitals that fit the criterion in the question.""" # set of available digits (each from 0 to 9) digits = set(range(0, 10)) # for each possibility for first, second, and third digit for first_digit in digits: first_available_digits = set(digits) first_available_digits.remove(first_digit) for second_digit in first_available_digits: second_available_digits = set(first_available_digits) second_available_digits.remove(second_digit) for third_digit in second_available_digits: third_available_digits = set(second_available_digits) third_available_digits.remove(third_digit) # for each pandigital with those starting digits for pandigital in pandigitals_helper( [second_digit, third_digit], # last 2 digits [2, 3, 5, 7, 11, 13, 17], # divisions to use, in order third_available_digits): # yield the whole pandigital 'list' to the main function yield [first_digit, second_digit, third_digit] + pandigital def pandigitals_helper(pair, divisors, available): """Used as a helper for generate_valid_pandigitals(), do not use directly. Selects the next possible digit that validates the next division and 'yields' it recursively. Args: pair: 2-element list containing the previous two digits. divisors: list containing the divisors that should be satisfied for the rest of the digits, in order. available: set containing the available digits for generating a number that is still pandigital.""" # the current divisor to use divisor = divisors[0] # for each possible digit combination for last_digit in available: # if that combination is a multiple of the divisor, recurse if (pair[0] * 100 + pair[1] * 10 + last_digit) % divisor == 0: # if this is the last digit if len(divisors) == 1: # yield a list of the last digit only yield [last_digit] else: # for each possible combination for the rest of the digits for pandigital in pandigitals_helper( [pair[1], last_digit], # last 2 digits divisors[1:], # divisions to use, in order available - {last_digit} # digits still available ): # yield the last digit followed by the rest yield [last_digit] + pandigital <file_sep># encoding=utf-8 ## SOLVED 2015/01/03 ## 55374 # Let p(n) represent the number of different ways in which n coins can be # separated into piles. For example, five coins can separated into piles in # exactly seven different ways, so p(5)=7. # OOOOO # OOOO O # OOO OO # OOO O O # OO OO O # OO O O O # O O O O O # Find the least value of n for which p(n) is divisible by one million. DIVISOR = 1000000 def euler(): n = 2 # this is valid since partition(n) returns a value with a modulo applied while partition(n) != 0: n += 1 return n # list of partitions, used by partition(), and indirectly by next_p ps = [0, 1] # partition function; see Euler's pentagonal number theorem # # N.B.: all calculations are made with modulo DIVISOR def partition(n): n += 1 i = len(ps) while i <= n: ps.append(next_p(i, ps) % DIVISOR) i += 1 return ps[n] # helper function for partition(): calculate the next partition # # N.B.: all calculations are made with modulo DIVISOR def next_p(n, ps): acc = 0 for dk in (-1, 1): k = dk q = pentagonal(k) while q < n: acc += int(((-1) ** (k - 1)) * ps[n - q]) k += dk q = pentagonal(k) return acc % DIVISOR # helper function for partition(): calculate the k-th pentagonal number # # N.B.: all calculations are made with modulo DIVISOR def pentagonal(k): return int(k * (3 * k - 1) / 2) % DIVISOR <file_sep># encoding=utf-8 ## SOLVED 2015/01/03 ## 73162890 # A common security method used for online banking is to ask the user for three # random characters from a passcode. For example, if the passcode was <PASSWORD>, # they may ask for the 2nd, 3rd, and 5th characters; the expected reply would # be: 317. # The text file, keylog.txt, contains fifty successful login attempts. # Given that the three characters are always asked for in order, analyse the # file so as to determine the shortest possible secret passcode of unknown # length. from helpers.file import * def euler(): # list of 3-char passwords attempts attempts = flattened_list_from_file("data/079.txt") attempts = [str(n) for n in attempts] # final password, will be concatenated into a string password = [] # characters that are present in the password, but whose position is unknown char_pool = set() for n in attempts: for d in n: char_pool.add(d) # while there is a character whose position is unknown while char_pool: # set of all probable "first" character for the password (or simply next # character) probable_first = set(char_pool) # when a character is present as the 2nd or 3rd character in an attempt, it # means it cannot possibly be the first character (as there is one before # it) for n in attempts: for d in n[1:]: if d in probable_first: probable_first.remove(d) # next digit in the password (first, ) = probable_first # add it to the password password.append(first) # we now know its position, so remove it from the char pool char_pool.remove(first) # remove the character from each 3-char attempt, preparing for the next # iteration for i,n in enumerate(attempts): if n and n[0] == first: attempts[i] = n[1:] # return the password, as a string return ''.join(password) <file_sep>#encoding=utf-8 ## SOLVED 2014/05/07 ## 376 # [...] # The file, poker.txt, contains one-thousand random hands dealt to two players. # Each line of the file contains ten cards (separated by a single space): the # first five are Player 1's cards and the last five are Player 2's cards. You # can assume that all hands are valid (no invalid characters or repeated # cards), each player's hand is in no specific order, and in each hand there is # a clear winner. # How many hands does Player 1 win? import helpers.poker as poker def euler(): # number of games player 1 wins win_count = 0 # for each line in the file with open('data/054.txt') as data_file: for line_string in data_file: # remove whitespace at the end line_string = line_string.rstrip() # make two PokerHand objects (wrappers for lists of PokerCard objects) hand1, hand2 = poker.read_poker_line(line_string) # if player 1 wins this game if poker.is_winner_player_1(hand1, hand2): win_count += 1 # return the number of games won by player 1 return win_count <file_sep># encoding=utf-8 ## SOLVED 2015/01/10 ## 2772 # By counting carefully it can be seen that a rectangular grid measuring 3 by 2 # contains eighteen rectangles: # [example] # Although there exists no rectangular grid that contains exactly two million # rectangles, find the area of the grid with the nearest solution. # maximum possible size for a rectangle MAX = 2000 # the "target" we are trying to reach TARGET = 2000000 def euler(): # (area, difference) tuple for the best match best_match = (0, 2000000) # for each possible width/height for height in range(1, MAX + 1): for width in range(1, height + 1): # the number of sub-rectangles is t(w)*t(h) rectangles = triangular(height) * triangular(width) # if it is closer to TARGET than previous best match, this is the # new best match if abs(TARGET - rectangles) < best_match[1]: best_match = (height * width, abs(TARGET - rectangles)) # return the area for the best match return best_match[0] # return the nth triangular number def triangular(n): return n * (n + 1) // 2<file_sep># encoding=utf-8 ## SOLVED 2014/10/20 # 26241 # Starting with 1 and spiralling anticlockwise in the following way, a square # spiral with side length 7 is formed. # 37 36 35 34 33 32 31 # 38 17 16 15 14 13 30 # 39 18 5 4 3 12 29 # 40 19 6 1 2 11 28 # 41 20 7 8 9 10 27 # 42 21 22 23 24 25 26 # 43 44 45 46 47 48 49 # It is interesting to note that the odd squares lie along the bottom right # diagonal, but what is more interesting is that 8 out of the 13 numbers lying # along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. # If one complete new layer is wrapped around the spiral above, a square spiral # with side length 9 will be formed. If this process is continued, what is the # side length of the square spiral for which the ratio of primes along both # diagonals first falls below 10%? import helpers.prime as prime def euler(): side_length = 2 accumulator = 1 prime_count = 0 number_count = 1 while side_length <= 8 or float(prime_count) / number_count >= 0.1: for i in range(4): accumulator += side_length number_count += 1 if prime.is_prime(accumulator): prime_count += 1 side_length += 2 return (side_length - 1) <file_sep># encoding=utf-8 ## SOLVED 2015/01/04 ## 260324 # NOTE: This problem is a more challenging version of Problem 81. # The minimal path sum in the 5 by 5 matrix below, by starting in any cell in # the left column and finishing in any cell in the right column, and only moving # up, down, and right, is indicated in red and bold; the sum is equal to 994. # [example...] # Find the minimal path sum, in matrix.txt (right click and "Save Link/Target # As..."), a 31K text file containing a 80 by 80 matrix, from the left column to # the right column. from helpers.file import * def euler(): # original matrix, read from the file original = list_from_file("data/082.txt", separator = ',') # dimensions of the matrix height = len(original) width = len(original[0]) # another matrix with the same dimensions, filled with 0. # each element will be the length of the shortest path from the left border to # the corresponding tile. costs = [[0 for x in range(width)] for y in range(height)] # the left border is the same as in the original for y in range(height): costs[y][0] = original[y][0] # for each column for x in range(1, width): # fill the column with the value that it takes to reach each cell from the # one immediately to its left for y in range(height): costs[y][x] = costs[y][x - 1] + original[y][x] # for each tile in the column, check if there is actually another, shorter # way to reach it (moving up and down from another tile in the same column) for y in range(height): # for each other starting tile in the same column, calculate the cost for # moving from that tile to the "current" tile `y` for start in range(height): acc = costs[start][x - 1] + original[y][x] for i in range(start, y, sg(y - start)): acc += original[i][x] # if the path is shorter by moving up/down than by coming from the # tile immediately to the left, then do that immediately if acc < costs[y][x]: costs[y][x] = acc # return the lowest value in the right border (the shortest path to reach the # right border) return min(costs[y][width - 1] for y in range(height)) # return the sign of x (1 if positive, -1 if negative). # sg(0) returns 1. def sg(x): return (1 if x >= 0 else -1) <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 233168 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we # get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. MAX = 1000 def euler(): # construct the list of relevant numbers numbers = (n for n in range(MAX) if n % 5 == 0 or n % 3 == 0) # return the sum return sum(numbers) <file_sep># encoding=utf-8 ## SOLVED 2014/12/01 ## 303963552391 # Consider the fraction, n/d, where n and d are positive integers. If n<d and # HCF(n,d)=1, it is called a reduced proper fraction. # If we list the set of reduced proper fractions for d ≤ 8 in ascending order # of size, we get: # 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, # 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 # It can be seen that there are 21 elements in this set. # How many elements would be contained in the set of reduced proper fractions # for d ≤ 1,000,000? def euler(): MAX = 10 ** 6 # at the end, this table will contain all the values for totients table = list(range(MAX + 1)) match_count = 0 # there are totient(p) reduced fracions for each denominator p for p in range(2, MAX + 1): if table[p] == p: # this number is prime: multiply each of is multiples by (1 - 1 / p) for q in range(p, MAX + 1, p): table[q] *= 1 - 1 / p # add totient(p) to the number of matches match_count += table[p] # return the number of matches, as an integer return round(match_count) <file_sep># encoding=utf-8 ## SOLVED 2013/12/23 ## 4179871 # A perfect number is a number for which the sum of its proper divisors is # exactly equal to the number. For example, the sum of the proper divisors of 28 # would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. # A number n is called deficient if the sum of its proper divisors is less than # n and it is called abundant if this sum exceeds n. # As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest # number that can be written as the sum of two abundant numbers is 24. By # mathematical analysis, it can be shown that all integers greater than 28123 # can be written as the sum of two abundant numbers. However, this upper limit # cannot be reduced any further by analysis even though it is known that the # greatest number that cannot be expressed as the sum of two abundant numbers is # less than this limit. # Find the sum of all the positive integers which cannot be written as the sum # of two abundant numbers. MAX = 28123 def euler(): abundants = {} for number in range(1, MAX): if is_abundant(number): abundants [number] = True accumulator = 0 for number in range(1, MAX): is_a_sum = False for abundant in abundants: if (number - abundant) in abundants: is_a_sum = True break if not is_a_sum: accumulator += number return accumulator def list_of_abundants(highest_value): """Return the list of abundant numbers from 1 to the given number.""" abundant_list = [] for number in range(1, highest_value): if is_abundant(number): abundant_list.append(number) return abundant_list def sum_of_divisors(number): """Return the sum of the divisors of a given number.""" product = 1 divisor = 2 while divisor * divisor <= number: multiplicand = 1 while number % divisor == 0: multiplicand = multiplicand * divisor + 1 number //= divisor product *= multiplicand divisor += 1 if number > 1: product *= 1 + number return product def is_abundant(number): """Return True iff the given number is abundant. A number is abundant iff the sum of its divisors is higher than itself. """ return sum_of_divisors(number) > number + number <file_sep># encoding=utf-8 ## SOLVED 2013/12/23 ## 871198282 # Using names.txt (right click and 'Save Link/Target As...'), a 46K text file # containing over five-thousand first names, begin by sorting it into # alphabetical order. Then working out the alphabetical value for each name, # multiply this value by its alphabetical position in the list to obtain a name # score. # For example, when the list is sorted into alphabetical order, COLIN, which is # worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN # would obtain a score of 938 × 53 = 49714. # What is the total of all the name scores in the file? import helpers.file as fileutils def euler(): # read the names from the file names = fileutils.flattened_list_from_file('data/022.txt', separator = ',', convert_to = str) # remove the quotes surrounding the name names = [name.replace('"', '') for name in names] # sort the names alphabetically names.sort() # accumulator for the total of the name scores accumulator = 0 for index, name in enumerate(names): # calculate the name score score = sum(ord(letter) - ord('A') + 1 for letter in name) score *= (index + 1) # add the score to the accumulator accumulator += score # return the accumulator return accumulator <file_sep># encoding=utf-8 ## SOLVED 2014/01/17 ## 210 # An irrational decimal fraction is created by concatenating the positive # integers: # 0.123456789101112131415161718192021... # It can be seen that the 12th digit of the fractional part is 1. # If dn represents the nth digit of the fractional part, find the value of the # following expression. # d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 import math MAX = 1000000 def euler(): # calculate what the last needed number is last_number = 0 size = 0 while size < MAX: last_number += 1 size += int(math.log(MAX, 10)) # construct the string string = ''.join(str(number) for number in range(1, MAX + 1)) # get the characters needed for calculations digits = [string [i] for i in [0, 9, 99, 999, 9999, 99999, 999999]] # calculate product of these digits accumulator = 1 for digit in digits: accumulator *= int(digit) # return the product return accumulator <file_sep># encoding=utf-8 ## SOLVED 2015/01/04 ## 425185 # In the 5 by 5 matrix below, the minimal path sum from the top left to the # bottom right, by moving left, right, up, and down, is indicated in bold red # and is equal to 2297. # [example...] # Find the minimal path sum, in matrix.txt (right click and "Save Link/Target # As..."), a 31K text file containing a 80 by 80 matrix, from the top left to # the bottom right by moving left, right, up, and down. from helpers.file import * from collections import deque def euler(): # original matrix, read from the file original = list_from_file("data/083.txt", separator = ',') # dimensions of the matrix height = len(original) width = len(original[0]) # another matrix with the same dimensions, filled with 0s. # each element will be the length of the shortest path from the upper left # corner to the corresponding tile. shortest = [[0 for x in range(width)] for y in range(height)] # the top left corner has the same value as in the original matrix shortest[0][0] = original[0][0] # queue for (y,x) pairs for the tiles to check queue = deque([(0, 0)]) # while there are tiles to check while queue: (y, x) = queue.popleft() # for each neighboring tile (v,u) inside the boundaries for (v, u) in neighbors(y, x, height, width): # if the shortest path to point (v,u) is unknown, or longer than the # length that would be obtained by going through (y,x) if shortest[v][u] == 0 or \ shortest[v][u] > shortest[y][x] + original[v][u]: # the new shortest path is the path going through (y,x) shortest[v][u] = shortest[y][x] + original[v][u] # make a new (or first) check on tile (v,u) at some point queue.append((v, u)) # return the shortest path to the bottom right corner return shortest[height - 1][width - 1] # `yield` for each tile that is directly adjacent to the tile at (y,x). # tiles outside the boundaries with width `w` and height `h` are not `yield`ed. # # the value `yield`ed is a (y,x) pair. def neighbors(y, x, h, w): for d in (-1, 1): v = y u = x + d if in_bounds(u, v, h, w): yield (v, u) v = y + d u = x if in_bounds(u, v, h, w): yield (v, u) def in_bounds(y, x, h, w): return y >= 0 and x >= 0 and y < h and x < w <file_sep># encoding=utf-8 ## SOLVED 2015/01/04 ## 427337 # In the 5 by 5 matrix below, the minimal path sum from the top left to the # bottom right, by only moving to the right and down, is indicated in bold red # and is equal to 2427. # [example...] # Find the minimal path sum, in matrix.txt (right click and "Save Link/Target # As..."), a 31K text file containing a 80 by 80 matrix, from the top left to # the bottom right by only moving right and down. from helpers.file import * def euler(): # original matrix, read from the file original = list_from_file("data/081.txt", separator = ',') # dimensions of the matrix height = len(original) width = len(original[0]) # another matrix with the same dimensions, filled with 0s. # each element will be the length of the shortest path from the upper left # corner to the corresponding tile. shortest = [[0 for x in range(width)] for y in range(height)] # the top left corner has the same value as in the original matrix shortest[0][0] = original[0][0] # fill the top and left borders, as there is only one path to get to them for y in range(1, height): shortest[y][0] = shortest[y - 1][0] + original[y][0] for x in range(1, width): shortest[0][x] = shortest[0][x - 1] + original[0][x] # fill the rest of the grid for y in range(1, height): for x in range(1, width): shortest[y][x] = min(shortest[y - 1][x], shortest[y][x - 1]) shortest[y][x] += original[y][x] # return the length of the shortest path to get to the bottom right corner return shortest[height - 1][width - 1] <file_sep># encoding=utf-8 ## SOLVED 26/12/14 ## 161667 # It turns out that 12 cm is the smallest length of wire that can be bent to # form an integer sided right angle triangle in exactly one way, but there are # many more examples. # 12 cm: (3,4,5) # 24 cm: (6,8,10) # 30 cm: (5,12,13) # 36 cm: (9,12,15) # 40 cm: (8,15,17) # 48 cm: (12,16,20) # In contrast, some lengths of wire, like 20 cm, cannot be bent to form an # integer sided right angle triangle, and other lengths allow more than one # solution to be found; for example, using 120 cm it is possible to form # exactly three different integer sided right angle triangles. # 120 cm: (30,40,50), (20,48,52), (24,45,51) # Given that L is the length of the wire, for how many values of L ≤ 1,500,000 # can exactly one integer sided right angle triangle be formed? import helpers.discreet as discreet LIMIT = 1500000 def euler(): table = {} m = 2 while 2 * m * m < LIMIT: for n in range(1, m): if (m - n) % 2 == 1 and discreet.gcd(m, n) == 1: a = m * m - n * n b = 2 * m * n c = m * m + n * n l = a + b + c for L in range(l, LIMIT, l): if L in table: table[L] += 1 else: table[L] = 1 m += 1 match_count = 0 for k in table: if table[k] == 1: match_count += 1 return match_count <file_sep># encoding=utf-8 ## SOLVED 2017/07/08 ## 1258 # By using each of the digits from the set, {1, 2, 3, 4}, exactly once, and # making use of the four arithmetic operations (+, −, *, /) and # brackets/parentheses, it is possible to form different positive integer # targets. # For example, # 8 = (4 * (1 + 3)) / 2 # 14 = 4 * (3 + 1 / 2) # 19 = 4 * (2 + 3) − 1 # 36 = 3 * 4 * (2 + 1) # Note that concatenations of the digits, like 12 + 34, are not allowed. # Using the set, {1, 2, 3, 4}, it is possible to obtain thirty-one different # target numbers of which 36 is the maximum, and each of the numbers 1 to 28 can # be obtained before encountering the first non-expressible number. # Find the set of four distinct digits, a < b < c < d, for which the longest set # of consecutive positive integers, 1 to n, can be obtained, giving your answer # as a string: abcd. from collections import defaultdict from helpers.sequence import take_n def apply_operator(left, op, right): if op == '+': return left + right if op == '-': return left - right if op == '*': return left * right if op == '/': return left / right raise Exception('Invalid operator.') def add_obtainable_values(obtainable_values, tokens, token_count): operators = '+-*/' for xs in take_n(tokens, token_count): for i, right in enumerate(xs): other_operands = tuple(xs[:i] + xs[i + 1:]) for left in obtainable_values[other_operands]: k = tuple(sorted(list(other_operands) + [right])) for op in operators: result = apply_operator(left, op, right) if result: obtainable_values[k].add(result) result = apply_operator(right, op, left) if result: obtainable_values[k].add(result) def euler(): tokens = [1, 2, 3, 4, 5, 6, 7, 8, 9] obtainable_values = defaultdict(lambda: set()) for i in range(10): obtainable_values[(i,)] = set([i]) for i in range(2, 5): add_obtainable_values(obtainable_values, tokens, i) sequence_lengths = dict() for xs in take_n(tokens, 4): i = 1 key = tuple(xs) while i in obtainable_values[key]: i += 1 sequence_lengths[key] = i - 1 max_index, max_value = max(sequence_lengths.items(), key = lambda x: x[1]) return int(''.join(str(i) for i in max_index)) <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 906609 # A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 x 99. # Find the largest palindrome made from the product of two 3-digit numbers def euler(): # accumulator for the highest palindrome found so far highest_palindrome = 0 # for each(a,b) pair for a in range(100, 1000): for b in range(a, 1000): product = a * b # if the product is a palindromic number if str(product) == str(product) [::-1]: # set the highest found so far to the higher of the two highest_palindrome = max(highest_palindrome, product) # return the highest palindrome found return highest_palindrome <file_sep>## Module for prime number mathematics. import math import collections # list of primes generated so far prime_list = [2, 3] def _generate_primes (highest_value): """Generates the list of primes prime_list which contains all prime numbers lower than a given number.""" number = prime_list [-1] + 2 highest_test_prime = math.ceil (math.sqrt (highest_value)) test_primes = [] i = 0 while i < len (prime_list) and prime_list [i] <= highest_test_prime: test_primes.append (prime_list [i]) i += 1 while number <= highest_value: if all (number % prime != 0 for prime in test_primes): prime_list.append (number) if number <= highest_test_prime: test_primes.append (number) number += 2 return prime_list def _generate_n_primes (number_of_primes): """Generates the list of primes prime_list which contains all the first n prime numbers.""" number = prime_list [-1] + 2 prime_count = len (prime_list) while prime_count < number_of_primes: is_a_prime = True highest_test_prime = math.ceil (math.sqrt (number)) i = 0 while i < len (prime_list) and prime_list [i] <= highest_test_prime: is_a_prime = is_a_prime and number % prime_list [i] != 0 i += 1 if is_a_prime: prime_list.append (number) prime_count += 1 number += 2 return prime_list def all_primes (leap = 100000): """Used as an iteartor for all prime numbers.""" highest_prime = prime_list [-1] iterator = 0 while True: highest_prime += leap _generate_primes (highest_prime) while iterator < len (prime_list): yield prime_list [iterator] iterator += 1 def primes (highest_value): """Used as an iterator for all primes up to a maximum value.""" _generate_primes (highest_value) i = 0 while i < len (prime_list) and prime_list [i] <= highest_value: yield prime_list [i] i += 1 def n_primes (number_of_primes): """Used as an iterator for the first n primes.""" _generate_n_primes (number_of_primes) for i in range (number_of_primes): yield prime_list [i] def is_prime (number): """Returns True if a given integer is a prime number.""" if number == 1: return False highest_divisor = math.floor (math.sqrt (number)) _generate_primes(highest_divisor) return all (number % prime != 0 for prime in primes (highest_divisor)) prime_factors_cache = {1: []} def prime_factors (number, use_cache = True): """Returns a list of all primes that are divisors of a given integer number. The list contains only prime numbers, whose product is equal to the original number""" if is_prime (number): return [number] if number in prime_factors_cache: return prime_factors_cache [number] factors = [] highest_divisor = math.floor (math.sqrt (number)) for prime in primes (highest_divisor): if number % prime == 0: factors = prime_factors (prime) + prime_factors (number // prime) if use_cache: prime_factors_cache [number] = factors return factors def multiset_prime_factors (number, use_cache = True): """Returns the same list of prime factors as the prime_factors() function, but reduces as a dictionary mapping each factor to its number of occurences. For instance, [2,2,2, 3, 5,5] becomes {2:3, 3:1, 5:2}.""" factors = prime_factors (number, use_cache) unique_factors = list (set (factors)) bag = collections.Counter() for factor in unique_factors: bag [factor] = factors.count (factor) return bag def divisor_count (number, use_cache = True): """Returns the number of integers that can evenly divide a given number.""" dictionary = dictionary_prime_factors (number, use_cache) divisors = 1 for power in dictionary.values (): divisors *= (power + 1) return divisors divisors_cache = {} def divisors (number, use_cache = True): """Returns a list of the divisors of a given number.""" if number in divisors_cache: return divisors_cache [number] prime_divisors = prime_factors (number, use_cache) divisors_dictionary = {} for prime in prime_divisors: divisors_dictionary [prime] = True factor = number // prime divisors_dictionary [factor] = True if not factor in prime_divisors: xs = list (divisors_dictionary.items ()) xs += [(divisor, True) for divisor in divisors (factor)] divisors_dictionary = dict (xs) result = list (divisors_dictionary.keys ()) if not 1 in result: result.append (1) if not number in result: result.append (number) if use_cache: divisors_cache [number] = result return result <file_sep># encoding=utf-8 ## SOLVED 2013/12/21 ## 21124 # If the numbers 1 to 5 are written out in words: one, two, three, four, five, # then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in # words, how many letters would be used? # NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and # forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 # letters. The use of "and" when writing out numbers is in compliance with # British usage. import re MAX = 1000 def euler(): # accumulator for the number of letters used accumulator = 0 # for each number in the given range for number in range(1, MAX + 1): # get the number's name name = number_name(number) # remove the whitespace and dashes name = re.sub('\\s|-', '', name) # add the length of the anme to the number of letters used accumulator += len(name) # return the number of letters used return accumulator # used for direct access to some number names number_name_dictionary = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 15: 'fifteen', 18: 'eighteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 80: 'eighty', 1000: 'one thousand' } def number_name(number): """Return the full name, in letters, of a given number. Args: number: number whose name should be returned. Returns: the full name of that number (twenty-three, one hundred and two...), as a string. Raises: ValueError: if number is not between 0 and 1000. """ if not isinstance(number, int): raise TypeError("number is not an integer") elif number < 0 or number > 1000: raise ValueError("number out of range (must be between 0 and 1000)") elif number in number_name_dictionary: # return directly if it's simply a dictionary lookup -- used for # exceptions and small numbers return number_name_dictionary [number] elif number > 10 and number < 20: # sixteen, nineteen... return number_name_dictionary [number - 10] + 'teen' elif number >= 20 and number < 100: # twenty-three, forty-nine... if number // 10 * 10 in number_name_dictionary: # exceptions for the tens: twenty, forty, fifty... name = number_name_dictionary [number // 10 * 10] else: # regular tens: sixty, seventy... name = number_name(number // 10) + 'ty' if number % 10: # if has a non-zero unit, add a dash, then the name of the units # (twenty-three, ninety-eight...) name += '-' + number_name(number % 10) return name elif number >= 100 and number < 1000: # nine hundred, two hundred... name = number_name(number // 100) + ' hundred' # if has tens or units if number % 100: # add 'and ...', as in four hundred and ninety-eight name += ' and ' + number_name(number % 100) return name <file_sep># encoding=utf-8 ## SOLVED 2014/11/30 ## 510510 # Euler's Totient function, φ(n) [sometimes called the phi function], is used # to determine the number of numbers less than n which are relatively prime to # n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and # relatively prime to nine, φ(9)=6. # n Relatively Prime φ(n) n/φ(n) # 2 1 1 2 # 3 1,2 2 1.5 # 4 1,3 2 2 # 5 1,2,3,4 4 1.25 # 6 1,5 2 3 # 7 1,2,3,4,5,6 6 1.1666... # 8 1,3,5,7 4 2 # 9 1,2,4,5,7,8 6 1.5 # 10 1,3,7,9 4 2.5 # It can be seen that n=6 produces a maximum n/φ(n) for n ≤ 10. # Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum. from helpers.prime import primes # maximum value for n HIGHEST_N = 1000000 def euler(): # return value, result best_match = 1 # the answer will be the integer <= HIGHEST_N, which has the most prime # factors. # so just multiply primes together, until the product exceeds the limit. for p in primes(HIGHEST_N): if best_match * p > HIGHEST_N: break best_match *= p # return the answer return best_match <file_sep>#encoding=utf-8 ## SOLVED 2014/04/10 ## 162 # The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so # the first ten triangle numbers are: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # By converting each letter in a word to a number corresponding to its # alphabetical position and adding these values we form a word value. For # example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word # value is a triangle number then we shall call the word a triangle word. # Using words.txt (right click and 'Save Link/Target As...'), a 16K text file # containing nearly two-thousand common English words, how many are triangle # words? import helpers.file as fileutils # arbitrary value for the highest reachable triangle number MAX = 1000 def euler(): # set of the triangle numbers until an arbitrary maximum number triangles = set() # generate triangle numbers n = 1 highest_triangle = 0 while highest_triangle < MAX: highest_triangle = n * (n + 1) // 2 triangles.add(highest_triangle) n += 1 # read the words and put them into a list of strings words = fileutils.flattened_list_from_file('data/042.txt', separator = ',', convert_to = str) # strip the quote-sign from the strings, leaving only the word words = [word.replace('"', '') for word in words] # accumulator for the final answer, the number of triangle words triangle_word_count = 0 # count the number of triangle words for word in words: if word_to_int(word) in triangles: triangle_word_count += 1 # return it return triangle_word_count def word_to_int(word): """Returns the sum of the 'letter value' of each letter in the word. ('a' = 1, 'b' = 2, 'c' = 3, ...)""" return sum(ord(letter) - ord('a') + 1 for letter in word.lower()) <file_sep># encoding=utf-8 ## SOLVED 2015/01/09 ## 101524 # In the game, Monopoly, the standard board is set up in the following way: # [drawing of a monopoly board] # A player starts on the GO square and adds the scores on two 6-sided dice to # determine the number of squares they advance in a clockwise direction. # Without any further rules we would expect to visit each square with equal # probability: 2.5%. However, landing on G2J (Go To Jail), CC (community # chest), and CH (chance) changes this distribution. # In addition to G2J, and one card from each of CC and CH, that orders the # player to go directly to jail, if a player rolls three consecutive doubles, # they do not advance the result of their 3rd roll. Instead they proceed # directly to jail. # At the beginning of the game, the CC and CH cards are shuffled. When a player # lands on CC or CH they take a card from the top of the respective pile and, # after following the instructions, it is returned to the bottom of the pile. # There are sixteen cards in each pile, but for the purpose of this problem we # are only concerned with cards that order a movement; any instruction not # concerned with movement will be ignored and the player will remain on the # CC/CH square. # Community Chest (2/16 cards): # Advance to GO # Go to JAIL # Chance (10/16 cards): # Advance to GO # Go to JAIL # Go to C1 # Go to E3 # Go to H2 # Go to R1 # Go to next R (railway company) # Go to next R # Go to next U (utility company) # Go back 3 squares. # The heart of this problem concerns the likelihood of visiting a particular # square. That is, the probability of finishing at that square after a roll. # For this reason it should be clear that, with the exception of G2J for which # the probability of finishing on it is zero, the CH squares will have the # lowest probabilities, as 5/8 request a movement to another square, and it is # the final square that the player finishes at on each roll that we are # interested in. We shall make no distinction between "Just Visiting" and being # sent to JAIL, and we shall also ignore the rule about requiring a double to # "get out of jail", assuming that they pay to get out on their next turn. # By starting at GO and numbering the squares sequentially from 00 to 39 we can # concatenate these two-digit numbers to produce strings that correspond with # sets of squares. # Statistically it can be shown that the three most popular squares, in order, # are JAIL (6.24%) = Square 10, E3 (3.18%) = Square 24, and GO (3.09%) = Square # 00. So these three most popular squares can be listed with the six-digit # modal string: 102400. # If, instead of using two 6-sided dice, two 4-sided dice are used, find the # six-digit modal string. # number of tiles on the grid GRID_SIZE = 40 # number of sides on the die DICE = 4 def euler(): # probability for each tile grid = [(1 / GRID_SIZE) for i in range(GRID_SIZE)] for n in range(100): # copy of the grid, for next iteration offgrid = [0 for i in range(GRID_SIZE)] # weigh each tile into the new probability for i in range(GRID_SIZE): weigh(i, offgrid, grid) # next grid is the current offgrid grid = offgrid # sort and reverse the tiles, and put them in a list of # (probability, index) pairs sorted_tiles = list(reversed(sorted(zip(grid, range(GRID_SIZE))))) # return the 6-digit signature signature = ''.join('{:02d}'.format(i) for (prob, i) in sorted_tiles[:3]) return signature # weigh the tiles that can be reached from tile i, and add some probabilities # to reach each target tile in offgrid def weigh(src, offgrid, grid): # for each first dice value for d1 in range(1, DICE + 1): # for each second dice value for d2 in range(1, DICE + 1): # destination tile dst = (src + d1 + d2) % GRID_SIZE # regular tile, weigh it normally if dst not in special_cases: offgrid[dst] += grid[src] * (1 / DICE / DICE) # special tile (CC, CH, G2J), use the information from the hashtable else: case = special_cases[dst] # weigh each new destination tile (that you can "warp" to) for warp in case: offgrid[warp] += grid[src] * case[warp] * (1 / DICE / DICE) # list of special cases that might make the character jump to another tile than # the one they landed on special_cases = dict() # add the Go To Jail tile to the special cases special_cases[30] = {10: 1} # list of community chest card tiles (by index) cc_sources = [2, 17, 33] # add the community chest tiles to the special cases for src in cc_sources: pairs = { src: 14 / 16, # no-teleport 0: 1 / 16, # GO 10: 1 / 16 # JAIL } special_cases[src] = pairs # list of chance card tiles (by index) ch_sources = [7, 22, 36] # railroad company tiles railroads = [5, 15, 25, 35] # utility company tiles utilities = [12, 28] # add the chance tiles to the special cases for src in ch_sources: pairs = { src: 6 / 16, # no-teleport 0: 1 / 16, # GO 10: 1 / 16, # JAIL 11: 1 / 16, # C1 24: 1 / 16, # E3 39: 1 / 16, # H2 5: 1 / 16, # R1 ((src - 3) % GRID_SIZE): 1 / 16 # back 3 squares } # railroad company dst = src + 1 while dst not in railroads: dst = (dst + 1) % GRID_SIZE if dst in pairs: pairs[dst] += 2 / 16 else: pairs[dst] = 2 / 16 # utility company dst = src + 1 while dst not in utilities: dst = (dst + 1) % GRID_SIZE pairs[dst] = 1 / 16 special_cases[src] = pairs <file_sep># encoding=utf-8 ## SOLVED 2013/12/23 ## -59231 # Euler discovered the remarkable quadratic formula: # n² + n + 41 # It turns out that the formula will produce 40 primes for the consecutive # values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is # divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible # by 41. # The incredible formula n² − 79n + 1601 was discovered, which produces 80 # primes for the consecutive values n = 0 to 79. The product of the # coefficients, −79 and 1601, is −126479. # Considering quadratics of the form: # n² + an + b, where |a| < 1000 and |b| < 1000 # where |n| is the modulus/absolute value of n # e.g. |11| = 11 and |−4| = 4 # Find the product of the coefficients, a and b, for the quadratic expression # that produces the maximum number of primes for consecutive values of n, # starting with n = 0. import helpers.prime as prime def euler(): longest_sequence = 0 product = 0 for a in range(-1000, 1000): for b in range(-1000, 1000): length = sequence_length(a, b) if length > longest_sequence: longest_sequence = length product = a * b return product def sequence_length(a, b): def f(): return n ** 2 + a * n + b n = 0 while f() > 1 and prime.is_prime(f()): n += 1 return n <file_sep>#encoding=utf-8 ## SOLVED 2020/04/1014 ## 5482660 # Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten # pentagonal numbers are: # # 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... # # It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 # − 22 = 48, is not pentagonal. # # Find the pair of pentagonal numbers, Pj and Pk, for which their sum and # difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of # D? import math MAX = 2500 def euler(): # for each pentagon for i in range(1, MAX): first_pentagon = p(i) # for each pentagon above this one for j in range(i, MAX): second_pentagon = p(j) pentagon_sum = first_pentagon + second_pentagon pentagon_difference = second_pentagon - first_pentagon # check if it's our answer if is_pentagon(pentagon_sum) and is_pentagon(pentagon_difference): return pentagon_difference def p(n): """Return the nth pentagonal number.""" return n * (3 * n - 1) // 2 def is_pentagon(n): """Return true iff n is a pentagonal number.""" x = (1 + math.sqrt(1 + 24 * n)) / 6 return x == int(x) <file_sep># encoding=utf-8 ## SOLVED 2013/12/23 ## 4782 # The Fibonacci sequence is defined by the recurrence relation: # Fn = F_n−1 + F_n−2, where F_1 = 1 and F_2 = 1. # The 12th term, F_12 = 144, is the first term to contain three digits. # What is the first term in the Fibonacci sequence to contain 1000 digits? import math DIGITS = 1000 def euler(): # used to calculate fibonacci numbers previous_number = 0 current_number = 1 # number of fibonacci numbers generated index = 0 while True: index += 1 # return the index if the current number has 1000 digits at least if math.log(current_number, 10) >= DIGITS - 1: return index # generate the next fibonacci number previous_number += current_number current_number, previous_number = previous_number, current_number <file_sep># encoding=utf-8 ## SOLVED 2013/12/24 ## 73682 # In England the currency is made up of pound, £, and pence, p, and there are # eight coins in general circulation: # 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). # It is possible to make £2 in the following way: # 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p # How many different ways can £2 be made using any number of coins? COINS = [200, 100, 50, 20, 10, 5, 2, 1] AMOUNT = 200 def euler(): return coin_combination_count(AMOUNT, COINS) def coin_combination_count(amount, coins): if amount == 0: return 1 combination_count = 0 for coin_index, coin in enumerate(coins): for coin_count in range(1, amount // coin + 1): new_amount = amount - coin_count * coin new_coins = coins [coin_index + 1:] combination_count += coin_combination_count(new_amount, new_coins) return combination_count <file_sep># encoding=utf-8 ## SOLVED 2014/12/01 ## 428570 # Consider the fraction, n/d, where n and d are positive integers. If n<d and # HCF(n,d)=1, it is called a reduced proper fraction. # If we list the set of reduced proper fractions for d ≤ 8 in ascending order # of size, we get: # 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, # 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 # It can be seen that 2/5 is the fraction immediately to the left of 3/7. # By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending # order of size, find the numerator of the fraction immediately to the left of # 3/7. HIGHEST_D = 10 ** 6 def euler(): m = 0 best_match = (2 / 7, None) for d in range(2, HIGHEST_D): if d % 7 != 0: m += 1 n = m // 2 if n / d > best_match[0]: best_match = (n / d, n) return best_match[1] <file_sep># encoding=utf-8 ## SOLVED 2014/10/20 ## 153 # It is possible to show that the square root of two can be expressed as an # infinite continued fraction. # √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... # By expanding this for the first four iterations, we get: # 1 + 1/2 = 3/2 = 1.5 # 1 + 1/(2 + 1/2) = 7/5 = 1.4 # 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... # 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... # The next three expansions are 99/70, 239/169, and 577/408, but the eighth # expansion, 1393/985, is the first example where the number of digits in the # numerator exceeds the number of digits in the denominator. # In the first one-thousand expansions, how many fractions contain a numerator # with more digits than denominator? import fractions import math def euler(): acc = fractions.Fraction(2) count = 0 for i in range(1000): acc = fractions.Fraction(2) + 1 / acc x = fractions.Fraction(1) + 1 / acc numerator_digit_count = int(math.log(x.numerator, 10)) + 1 denominator_digit_count = int(math.log(x.denominator, 10)) + 1 if numerator_digit_count > denominator_digit_count: count += 1 return count <file_sep>#!/usr/bin/python3 import sys import importlib import timeit def main(): if len(sys.argv) <= 1: print_help() return try: problem = int(sys.argv [1]) except ValueError: print(sys.argv [1] + ' is not a valid integer.') return if int(sys.argv [1]) <= 0: print(sys.argv [1] + ' is not greater than or equal to one.') try: module = importlib.import_module('problems.{:03d}'.format(problem)) except ImportError as error: print('No solution for problem #' + sys.argv [1] + '.') return if not module.euler: print('Solution for problem #' + sys.argv [1] + ' is invalid.') return title = "(problem title missing)" if problem in problem_descriptions: title = problem_descriptions[problem] print('Solving problem #{0}: {1}.'.format(problem, title)) print('Calculating (this may take some time)...') before = timeit.default_timer() result = module.euler() after = timeit.default_timer() print('The answer for problem #{0} is {1}.'.format(problem, result)) print('Calculation took {0:.3f} seconds.'.format(after - before)) def print_help(): """Prints a message to show what arguments this program takes.""" print("Usage: {} PROBLEM".format(sys.argv[0])) print("Solves the given problem from projecteuler.net,", "supplied by problem number.") # TODO: move these to their own problems' files problem_descriptions = { 1 : "multiples of 3 and 5", 2 : "even Fibonacci numbers", 3 : "largest prime factor", 4 : "largest palindrome product", 5 : "smallest multiple", 6 : "sum square difference", 7 : "10001st prime", 8 : "largest product in a series", 9 : "special pythagorean triplet", 10: "summation of primes", 11: "largest product in a grid", 12: "highly divisible triangular number", 13: "large sum", 14: "longest Collatz sequence", 15: "lattice paths", 16: "power digit sum", 17: "number letter counts", 18: "maximum path sum I", 19: "counting sundays", 20: "factorial digit sum", 21: "amicable numbers", 22: "names scores", 23: "non-abundant sums", 24: "lexicographic permutations", 25: "1000-digit Fibonacci number", 26: "reciprocal cycles", 27: "quadratic primes", 28: "number spiral diagonals", 29: "distinct powers", 30: "digit fifth power", 31: "coin sums", 32: "pandigital products", 33: "digit cancelling fractions", 34: "digit factorials", 35: "circular primes", 36: "double-base palindromes", 37: "truncatable primes", 38: "pandigital primes", 39: "integer right triangles", 40: "champernowne's constant", 41: "pandigital primes", 42: "coded triangle numbers", 43: "sub-string divisibility", 44: "pentagon numbers", 45: "triangular, pentagonal, and hexagonal", 46: "goldbach's other conjecture", 47: "distinct prime factors", 48: "self powers", 49: "prime permutations", 50: "consecutive prime sum", 51: "prime digit replacements", 52: "permuted multiples", 53: "combinatoric selections", 54: "poker hands", 55: "lychrel numbers", 56: "powerful digit sum", 57: "square root convergents", 58: "spiral primes", 59: "XOR decryption", 60: "prime pair sets", 61: "cyclical figurate numbers", 62: "cubic permutations", 63: "powerful digit counts", 64: "odd period square roots", 65: "convergents of e", 66: "diophantine equation", 67: "maximum path sum II", 68: "magic 5-gon ring", 69: "totient maximum", 70: "totient permutation", 71: "ordered fractions", 72: "counting fractions", 73: "counting fractions in a range", 74: "digit factorial chains", 75: "singular integer right triangles", 76: "counting summations", 77: "prime summations", 78: "coin partitions", 79: "passcode derivation", 80: "square root digital expansion", 81: "path sum: two ways", 82: "path sum: three ways", 83: "path sum: four ways", 84: "monopoly odds", 85: "counting rectangles", 86: "cuboid route", 87: "prime power triples", 88: "product-sum numbers", 89: "roman numerals", 90: "cube digit pairs", 91: "right triangles with integer coordinates", 92: "square digit chains", 93: "arithmetic expressions", 94: "almost equilateral triangles", 95: "amicable chains", } if __name__ == '__main__': main() <file_sep>#encoding=utf-8 ## SOLVED 2014/04/10 ## 1533776805 # Triangle, pentagonal, and hexagonal numbers are generated by the following # formulae: # Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... # Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ... # Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ... # It can be verified that T285 = P165 = H143 = 40755. # Find the next triangle number that is also pentagonal and hexagonal. import math def euler(): n = 144 while True: hexagon = n * (2 * n - 1) if is_triangle(hexagon) and is_pentagon(hexagon): return hexagon n += 1 def is_triangle(n): """Return True iff n is a triangle number.""" x = (-1 + math.sqrt(1 + 8 * n)) / 2 return x == int(x) def is_pentagon(n): """Return True iff n is a pentagon number.""" x = (1 + math.sqrt(1 + 24 * n)) / 6 return x == int(x) def is_hexagon(n): """Return True iff n is a hexagon number.""" x = (1 + math.sqrt(8 * n)) / 4 return x == int(x) <file_sep># encoding=utf-8 ## SOLVED 2021/03/23 ## 14316 # The proper divisors of a number are all the divisors excluding the number # itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the # sum of these divisors is equal to 28, we call it a perfect number. # Interestingly the sum of the proper divisors of 220 is 284 and the sum of the # proper divisors of 284 is 220, forming a chain of two numbers. For this # reason, 220 and 284 are called an amicable pair. # Perhaps less well known are longer chains. For example, starting with 12496, # we form a chain of five numbers: # 12496 → 14288 → 15472 → 14536 → 14264 (→ 12496 → ...) # Since this chain returns to its starting point, it is called an amicable # chain. # Find the smallest member of the longest amicable chain with no element # exceeding one million. import math MAX = 1000000 # Maps each number to the sum of their divisors. sieve = [1] * (MAX + 1) def euler(): # This sieve is faster than computing the divisors of each number. for d in range(2, math.ceil(math.sqrt(MAX)) + 1): for i in range(d * d, MAX + 1, d): if i // d == d: sieve[i] += d else: sieve[i] += d + i // d longest = 0 smallest = MAX for n in range(10, MAX): chain = generate_chain(n) if chain and len(chain) > longest: longest = len(chain) smallest = min(chain) return smallest # Avoid re-visiting the same number twice. seen = set() def generate_chain(n): chain = [] while n not in chain: if n > MAX or n <= 0: return None if n in seen: return None seen.add(n) chain.append(n) n = sieve[n] return chain[chain.index(n):] <file_sep># encoding=utf-8 ## SOLVED 2014/11/17 ## 26033 # The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes # and concatenating them in any order the result will always be prime. For # example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these # four primes, 792, represents the lowest sum for a set of four primes with # this property. # Find the lowest sum for a set of five primes for which any two primes # concatenate to produce another prime. from helpers.prime import * # max prime to use for testing things HIGHEST_VALUE = 10000 # target length of the chain to look for CHAIN_LENGTH = 5 def euler(): # calculate the list of all prime numbers up to HIGHEST_VALUE ps = list(primes(HIGHEST_VALUE)) # make a dictionary that associates each prime number to other primes with # which it is_concat_prime() concats = dict() for p in ps: concats[p] = set() for q in ps: if q > p and is_concat_prime(p, q): concats[p].add(q) # for each possible starting number, try to make a chain for p in ps: c = make_chain(CHAIN_LENGTH - 1, concats, p, concats[p]) # if the chain actually worked, return its sum if c: return sum(c) return None def make_chain(length, concats, p, remaining): if length == 0: # return if the chain is completed return [p] # for each prime that works for is_concat_prime() with p for q in remaining: # intersection of primes that work for is_concat_prime() with p, and # those that work with q inter = remaining & concats[q] # try to continue the chain chain = make_chain(length - 1, concats, q, inter) # return if it worked if chain: return [p] + chain return None # returns True iff "${p}${q}" and "${q}${p}" are both prime numbers def is_concat_prime(p, q): left = int(str(p) + str(q)) right = int (str(q) + str(p)) return is_prime(left) and is_prime(right) <file_sep>#encoding=utf-8 ## SOLVED 2014/05/07 ## 249 # If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. # Not all numbers produce palindromes so quickly. For example, # 349 + 943 = 1292, # 1292 + 2921 = 4213 # 4213 + 3124 = 7337 # That is, 349 took three iterations to arrive at a palindrome. # Although no one has proved it yet, it is thought that some numbers, like 196, # never produce a palindrome. A number that never forms a palindrome through # the reverse and add process is called a Lychrel number. Due to the # theoretical nature of these numbers, and for the purpose of this problem, we # shall assume that a number is Lychrel until proven otherwise. In addition you # are given that for every number below ten-thousand, it will either (i) become # a palindrome in less than fifty iterations, or, (ii) no one, with all the # computing power that exists, has managed so far to map it to a palindrome. In # fact, 10677 is the first number to be shown to require over fifty iterations # before producing a palindrome: 4668731596684224866951378664 (53 iterations, # 28-digits). # Surprisingly, there are palindromic numbers that are themselves Lychrel # numbers; the first example is 4994. # How many Lychrel numbers are there below ten-thousand? # NOTE: Wording was modified slightly on 24 April 2007 to emphasise the # theoretical nature of Lychrel numbers. HIGHEST_VALUE = 10000 HIGHEST_ITERATION_COUNT = 50 def euler(): # number of lychrel numbers fount lychrel_count = 0 # check every integer in a given range for n in range(1, HIGHEST_VALUE): if is_lychrel(n): lychrel_count += 1 # return the number of lychrel numbers found return lychrel_count def is_lychrel(n): """Return True iff the given integer is a (supposed) Lychrel number.""" # try a given number of iterations for i in range(HIGHEST_ITERATION_COUNT): # add the reverse number n += int("".join(reversed(str(n)))) # if the result is palindromic, it's not a lychrel number if is_palindromic(n): return False return True def is_palindromic(n): """Return True iff the given integer is palindromic.""" xs = str(n) return xs == "".join(reversed(xs)) <file_sep># encoding=utf-8 ## SOLVED 2013/12/25 ## 872187 # The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. # Find the sum of all numbers, less than one million, which are palindromic in # base 10 and base 2. # (Please note that the palindromic number, in either base, may not include # leading zeros.) def euler(): accumulator = 0 for number in range(1, 1000000): is_valid = is_palindromic(str(number)) is_valid = is_valid and is_palindromic(to_binary(number)) if is_valid: accumulator += number return accumulator def to_binary(number): accumulator = [] while number > 0: accumulator.append(number % 2) number //= 2 return ''.join(map(str, accumulator [::-1])) def is_palindromic(sequence): return sequence == sequence [::-1] <file_sep># encoding=utf-8 ## SOLVED 2013/12/20 ## 171 # How many Sundays fell on the first of the month during the twentieth century # (1 Jan 1901 to 31 Dec 2000)? def euler(): # array of lengths of months month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # values to add to day-of-the-week accumulator for each month index month_offsets = [] # accumulator for month offsets accumulator = 0 for month in range(12): month_offsets.append(accumulator % 7) accumulator += month_lengths [month] def day_of_week(day, month, year): # accumulator for day-of-the-week # 6 is Sunday, 0 is Monday, 1 is Tuesday... accumulator = day - 1 # account for the month accumulator += month_offsets [month - 1] # account for the year accumulator += year + year // 4 - year // 100 + year // 400 + 6 # adjust if the year is leap, and the month is January of February if is_leap(year): accumulator -=1 if month > 2: accumulator += 1 # return the day of the week between 0 and 6, with 0 being Monday return accumulator % 7 # number of Sundays on the first of the month sunday_count = 0 # for each year from 1901 to 2000 for year in range(1901, 2001): # for each month in that year for month in range(1, 13): # if the first of the month is a Sunday if day_of_week(1, month, year) == 6: # add a Sunday sunday_count += 1 # return the number of Sundays on the first of the month return sunday_count def is_leap(year): """Returns True iff the given year number represents a leap year.""" return year % 400 == 0 or(year % 4 == 0 and year % 400 != 0) <file_sep># encoding=utf-8 ## SOLVED 2013/10/20 ## 972 # A googol (10100) is a massive number: one followed by one-hundred zeros; # 100100 is almost unimaginably large: one followed by two-hundred zeros. # Despite their size, the sum of the digits in each number is only 1. # Considering natural numbers of the form, ab, where a, b < 100, what is the # maximum digital sum? MAX = 100 def euler(): highest_sum = 0 for a in range(1, MAX): for b in range(1, MAX): highest_sum = max(highest_sum, sum([int(c) for c in str(a ** b)])) return highest_sum <file_sep>#encoding=utf-8 ## SOLVED 2014/04/10 ## 9110846700 # The series, 11 + 22 + 33 + ... + 1010 = 10405071317. # Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000. MAX = 1000 def euler(): # accumulator for the sum accumulator = 0 # for each number from 1 to 1000 for n in range(1, MAX + 1): # add the exponent to the accumulator accumulator += quick_exponent_with_mod(n, n, 10 ** 10) accumulator %= 10 ** 10 # return the accumulator return accumulator def quick_exponent_with_mod(base, power, modulo): """Compute quickly the exponent within a given modulo range. Will apply a modulo with the specified base at every iteration of the exponentiation algorithm, making sure the result is in the given range.""" # 'powers' will be a list of the base with powers of two applied, i.e.: # with base==3, powers==[3, 3^2, 3^4, 3^8, 3^16, ...] powers = [base] # for each power of two i = 2 while i <= power: # compute base^(2^i) and add it to the list powers.append((powers[-1] * powers[-1]) % modulo) # next power of two i *= 2 # list of booleans corresponding to which powers of two to include to make # up the whole exponent powers_to_include = list(bool(int(digit)) for digit in bin(power)[2:][::-1]) # accumulator for the product accumulator = 1 # for each factor==base^(2^index) for index, factor in enumerate(powers): # if this power should be included if powers_to_include[index]: # multiply and apply modulo accumulator *= factor accumulator %= modulo # return the product accumulator return accumulator <file_sep># encoding=utf-8 ## SOLVED 2013/12/20 ## 837799 # The following iterative sequence is defined for the set of positive integers: # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # Using the rule above and starting with 13, we generate the following sequence: # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains # 10 terms. Although it has not been proved yet (Collatz Problem), it is thought # that all starting numbers finish at 1. # Which starting number, under one million, produces the longest chain? # NOTE: Once the chain starts the terms are allowed to go above one million. import helpers.prime as prime MAX = 1000000 def euler(): # return the number that generates the longest collatz sequence return max((collatz(n), n) for n in range(1, MAX)) [1] # use a dictionary to optimize the collatz sequence collatz_cache = {1: 1} def collatz(number): """Return the length of the collatz sequence starting at a given number.""" # use cache if possible if number in collatz_cache: return collatz_cache [number] # compute the result using recursion if number % 2 == 0: result = 1 + collatz(number // 2) else: result = 1 + collatz(number * 3 + 1) # set it in the cache collatz_cache [number] = result # return the result return result <file_sep># encoding=utf-8 ## SOLVED 2013/12/20 ## 5537376230 # Work out the first ten digits of the sum of the following one-hundred 50-digit # numbers. import helpers.file as fileutils def euler(): # read the file numbers = fileutils.flattened_list_from_file('data/013.txt') # return the first ten digits of the sum of the numbers return str(sum(numbers)) [:10] <file_sep># Project Euler Solutions [projecteuler.net](https://projecteuler.net/) is a website that offers several problems related to various fields of mathematics and algorithmics. Some are very simple, and some are much more complex. This repository contains solutions to some of the problems listed on the Project Euler website. ## Running In order to calculate the solution to a specific problem, simply use the run script in the project's root directory, and give it the problem number. For instance, if you want to calculate the answer for problem #42: ./run 42 For some problems, it may take some time before the answer is calculated. For most problems, the answer is given within 5 seconds; but it can take a lot more time, with one problem reaching 90 seconds of calculation. ## Directory Structure The `data/` directory contains the data files used by a few of the problems, which are used for calculations or parsing. The `problems/` directory contains the solutions for each problem I have solved. Each file corresponds to a problem, and is named after the problem number. The heading of the file contains the date it was solved, the computed answer, and the original problem description from the Project Euler website. The `helpers/` directory contains helper functions and module. Most notably, there are functions for reading files, and handling prime numbers. Since many problems on the Project Euler website use prime numbers, I have developed a library for detecting prime numbers, decomposing a number into its prime factors, iterating over primes, etc. I have deliberately chosen to duplicate code that would be available in Python's standard library, because that is part of the fun of working on this project. Coding these algorithms myself also gives me a deeper understanding of how they work. <file_sep># encoding=utf-8 ## SOLVED 2013/12/21 ## 1074 # By starting at the top of the triangle below and moving to adjacent numbers on # the row below, the maximum total from top to bottom is 23. # 3 # 7 4 # 2 4 6 # 8 5 9 3 # That is, 3 + 7 + 4 + 9 = 23. # Find the maximum total from top to bottom of the triangle below [018.txt] import helpers.file as fileutils def euler(): # read the pyramid from the file pyramid = fileutils.list_from_file('data/018.txt') # for each row, starting at the second from the bottom and going up for y in range(len(pyramid) - 2, -1, -1): # for each element of that row for x in range(y + 1): # add to it the highest of the two directly below it pyramid [y][x] += max(pyramid [y + 1][x], pyramid [y + 1][x + 1]) # return the value at the top of the pyramid return pyramid [0][0] <file_sep># encoding=utf-8 ## SOLVED 2016/02/15 ## 7587457 # A natural number, N, that can be written as the sum and product of a given set # of at least two natural numbers, {a1, a2, ... , ak} is called a product-sum # number: N = a1 + a2 + ... + ak = a1 × a2 × ... × ak. # For example, 6 = 1 + 2 + 3 = 1 × 2 × 3. # For a given set of size, k, we shall call the smallest N with this property a # minimal product-sum number. The minimal product-sum numbers for sets of size, # k = 2, 3, 4, 5, and 6 are as follows. # k=2: 4 = 2 × 2 = 2 + 2 # k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3 # k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4 # k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2 # k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6 # Hence for 2≤k≤6, the sum of all the minimal product-sum numbers is # 4+6+8+12 = 30; note that 8 is only counted once in the sum. # In fact, as the complete set of minimal product-sum numbers for 2≤k≤12 is # {4, 6, 8, 12, 15, 16}, the sum is 61. # What is the sum of all the minimal product-sum numbers for 2≤k≤12000? import helpers.prime as prime import math import collections BIG_NUMBER = 999 def euler(): product_sum_numbers = {} for k in range(2, 12001): product_sum_numbers[k] = 15000 for i in range(4, 15000): for factors in factorizations(i, 2): k = i - sum(factors) + len(factors) if k in product_sum_numbers: product_sum_numbers[k] = min(product_sum_numbers[k], i) numbers = set() for k in range(2, 12001): numbers.add(product_sum_numbers[k]) return sum(numbers) def factorizations(n, smallest): if n == 1: return [[]] m = math.floor(math.sqrt(n)) fs = [] for i in range (smallest, m + 1): if n % i == 0: fs.extend([i] + p for p in factorizations(n // i, i)) fs.append([n]) return fs <file_sep># encoding=utf-8 ## SOLVED 2013/12/25 ## 55 # The number, 197, is called a circular prime because all rotations of the # digits: 197, 971, and 719, are themselves prime. # There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, # 73, 79, and 97. # How many circular primes are there below one million? import helpers.prime as primeutils import helpers.sequence as sequence MAX = 1000000 def euler(): accumulator = 0 for prime in primeutils.primes(MAX): if is_circular(prime): accumulator += 1 return accumulator circular_cache = {} def is_circular(prime): if prime in circular_cache: return circular_cache [prime] for rotation in sequence.rotations(str(prime)): if not primeutils.is_prime(int(''.join(rotation))): return False for rotation in sequence.rotations(str(prime)): circular_cache [int(''.join(rotation))] = True return True <file_sep># encoding=utf-8 ## SOLVED 2013/12/21 ## 1366 # 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # What is the sum of the digits of the number 2^1000? def euler(): # return the sum of the digits of 2^1000 return sum(int(char) for char in str(2 ** 1000)) <file_sep># encoding=utf-8 ## SOLVED 2013/12/20 ## 70600674 # In the 20x20 grid below, four numbers along a diagonal line have been marked # in red. # [11.txt] # The product of these numbers is 26 x 63 x 78 x 14 = 1788696. # What is the greatest product of four adjacent numbers in the same direction # (up, down, left, right, or diagonally) in the 20x20 grid? import helpers.file as fileutils def euler(): # highest product of four adjacent numbers in the same direction highest_product = 0 # read the file to get the grid grid = fileutils.list_from_file('data/011.txt') # horizontal products for row in grid: for x in range(len(grid [0]) - 3): highest_product = max(highest_product, product(row [x : x + 4])) # vertical products for x in range(len(grid [0])): column = [row [x] for row in grid] for y in range(len(grid) - 3): highest_product = max(highest_product, product(column [y : y + 4])) # diagonal products from top-left to bottom-right for y in range(len(grid) - 3): for x in range(len(grid [0]) - 3): elements = [grid [y + i][x + i] for i in range(4)] highest_product = max(highest_product, product(elements)) # highest products from bottom-left to top-right for y in range(len(grid) - 3): for x in range(3, len(grid [0])): elements = [grid [y + i][x - i] for i in range(4)] highest_product = max(highest_product, product(elements)) # return the highest product return highest_product def product(xs): """Return the product of the elements in an iterable.""" accumulator = 1 for x in xs: accumulator *= x return accumulator <file_sep># encoding=utf-8 ## SOLVED 2013/12/25 ## 932718654 # Take the number 192 and multiply it by each of 1, 2, and 3: # 192 × 1 = 192 # 192 × 2 = 384 # 192 × 3 = 576 # By concatenating each product we get the 1 to 9 pandigital, 192384576. We will # call 192384576 the concatenated product of 192 and (1,2,3) # The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and # 5, giving the pandigital, 918273645, which is the concatenated product of 9 # and (1,2,3,4,5). # What is the largest 1 to 9 pandigital 9-digit number that can be formed as the # concatenated product of an integer with (1,2, ... , n) where n > 1? def euler(): highest = 0 for number in range(1, 100000): string = str(number) for n in range(2, 8): if len(string) > 9: break string += str(number * n) if is_pandigital(string): if int(string) > highest: highest = int(string) return highest def is_pandigital(sequence): return len(sequence) == 9 and \ set(map(int, sequence)) == set(range(1, 10)) <file_sep># encoding=utf-8 ## SOLVED 2014/11/18 ## 28684 # Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers # are all figurate (polygonal) numbers and are generated by the following # formulae: # Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... # Square P4,n=n2 1, 4, 9, 16, 25, ... # Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ... # Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ... # Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ... # Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ... # The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three # interesting properties. # The set is cyclic, in that the last two digits of each number is the first # two digits of the next number (including the last number with the first). # Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and # pentagonal (P5,44=2882), is represented by a different number in the set. # This is the only set of 4-digit numbers with this property. # Find the sum of the only ordered set of six cyclic 4-digit numbers for which # each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and # octagonal, is represented by a different number in the set. from math import sqrt def euler(): # functions used to check the type of a number predicates = [is_triangle, is_square, is_pentagonal, is_hexagonal, is_heptagonal, is_octagonal] for left in range(10, 100): # try to construct a chain from this initial left-part for the number c = chain([], left, predicates) # if it worked, return the sum if c: return sum(c) def chain(xs, left, predicates): # `xs` is the constructed list # `left` is the left part of the current number # `predicates` is the list of predicates that aren't already verified by # numbers in `xs` if predicates == []: # `xs` has the right number of elements, return it return xs rights = range(10, 100) if len(predicates) == 1: # if there is only one number left to guess, the right part of this # number must be the left part of the first number rights = [int(xs[0] / 100)] for right in rights: # construct the current number as "${left}${right}" n = left * 100 + right # no duplicates in `xs` if n in xs: continue # check each predicate on the constructed number (n) for predicate in predicates: if predicate(n): # remove the verified predicate from the list of predicates new_predicates = list(predicates) new_predicates.remove(predicate) # try to advance recursively c = chain(xs + [n], right, new_predicates) # if it worked, return the returned value if c: return c # failed to construct it return None def is_triangle(k): n1 = (-1 + sqrt(1 + 8 * k)) / 2 return int(n1) == n1# or int(n2) == n2 def is_square(k): return int(sqrt(k)) == sqrt(k) def is_pentagonal(k): n1 = (1 + sqrt(1 + 24 * k)) / 6 return int(n1) == n1# or int(n2) == n2 def is_hexagonal(k): n1 = (0.5 + sqrt(0.25 + 2 * k)) / 2 return int(n1) == n1# or int(n2) == n2 def is_heptagonal(k): n1 = (3 + sqrt(9 + 40 * k)) / 10 return int(n1) == n1# or int(n2) == n2 def is_octagonal(k): n1 = (2 + sqrt(4 + 12 * k)) / 6 return int(n1) == n1# or int(n2) == n2 <file_sep># encoding=utf-8 ## SOLVED 2016/02/17 ## 1217 # Each of the six faces on a cube has a different digit (0 to 9) written on it; # the same is done to a second cube. By placing the two cubes side-by-side in # different positions we can form a variety of 2-digit numbers. # For example, the square number 64 could be formed: # (6)(4) # In fact, by carefully choosing the digits on both cubes it is possible to # display all of the square numbers below one-hundred: 01, 04, 09, 16, 25, 36, # 49, 64, and 81. # For example, one way this can be achieved is by placing {0, 5, 6, 7, 8, 9} on # one cube and {1, 2, 3, 4, 8, 9} on the other cube. # However, for this problem we shall allow the 6 or 9 to be turned upside-down # so that an arrangement like {0, 5, 6, 7, 8, 9} and {1, 2, 3, 4, 6, 7} allows # for all nine square numbers to be displayed; otherwise it would be impossible # to obtain 09. # In determining a distinct arrangement we are interested in the digits on each # cube, not the order. # {1, 2, 3, 4, 5, 6} is equivalent to {3, 6, 4, 1, 2, 5} # {1, 2, 3, 4, 5, 6} is distinct from {1, 2, 3, 4, 5, 9} # But because we are allowing 6 and 9 to be reversed, the two distinct sets in # the last example both represent the extended set {1, 2, 3, 4, 5, 6, 9} for the # purpose of forming 2-digit numbers. # How many distinct arrangements of the two cubes allow for all of the square # numbers to be displayed? def euler(): digits = list(range(0, 10)) acc = 0 for d1 in choose(digits, 6): for d2 in choose(digits, 6): if check_pair(d1, d2): acc += 1 return acc // 2 # square the number, and return a tuple with each element being a digit from the # square. # 9 is replaced with 6. def square_tuple(i): s = "%02d" % (i * i) return tuple(map(lambda c: int(c) if c != '9' else 6, s)) # checks if a pair of die can write the squares of all numbers from 1 to 9 def check_pair(d1, d2): for i in range(1, 10): (a, b) = square_tuple(i) works = False for c, d in ((a, b),(b,a)): if c in d1 and d in d2: works = True if not works: return False return True # generate all the choices of `k` elements from the list `xs`, as sets. def choose(xs, k): if k <= 0: yield set() return if k > len(xs): return for c in choose(xs[1:], k - 1): if xs[0] != 9: c.add(xs[0]) else: # treat 9 as if it were 6 c.add(6) yield c for c in choose(xs[1:], k): yield c <file_sep># encoding=utf-8 ## SOLVED 2014/11/18 ## 49 # The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit # number, 134217728=89, is a ninth power. # How many n-digit positive integers exist which are also an nth power? from math import log def euler(): # don't count duplicates, so use a set to keep track of numbers found found = set() # b has to be between 1 and 10 for b in range(1, 11): for n in range(1, 50): if (b ** n) not in found and int(n * log(b, 10)) == n - 1: found.add(b ** n) # return the number of items found return len(found) <file_sep># encoding=utf-8 ## SOLVED 2014/12/07 ## 402 # The number 145 is well known for the property that the sum of the factorial # of its digits is equal to 145: # 1! + 4! + 5! = 1 + 24 + 120 = 145 # Perhaps less well known is 169, in that it produces the longest chain of # numbers that link back to 169; it turns out that there are only three such # loops that exist: # 169 → 363601 → 1454 → 169 # 871 → 45361 → 871 # 872 → 45362 → 872 # It is not difficult to prove that EVERY starting number will eventually get # stuck in a loop. For example, # 69 → 363600 → 1454 → 169 → 363601 (→ 1454) # 78 → 45360 → 871 → 45361 (→ 871) # 540 → 145 (→ 145) # Starting with 69 produces a chain of five non-repeating terms, but the # longest non-repeating chain with a starting number below one million is sixty # terms. # How many chains, with a starting number below one million, contain exactly # sixty non-repeating terms? MAX = 1000000 def euler(): match_count = 0 for n in range(1, MAX): if chain_length(n) == 60: match_count += 1 return match_count # cache for the chain_length() function chain_cache = dict() def chain_length(n): # set, and ordered list, for encountered numbers in the chain encountered = set() ordered = [] # used to save data to cache before returning from thi sfunction def save(length): for i, k in enumerate(ordered): chain_cache[k] = length - i # repeat this until 'n' is saved in the cache, or until 'n' was encountered # before while True: if n in chain_cache: # save data to cache, and return based on what was found in cache save(len(encountered) + chain_cache[n]) return len(encountered) + chain_cache[n] if n in encountered: break # save 'n' to the list of encountered numbers in the chain encountered.add(n) ordered.append(n) # calculate the next term in the chain digits = [int(c) for c in str(n)] acc = 0 for d in digits: acc += factorial(d) n = acc # save data to cache save(len(encountered)) # return the length of the chain return len(encountered) # dictionary used for calculating factorials quickly for integers from 0 to 9 factorial_table = dict() n = 1 for i in range(10): factorial_table[i] = n n *= i + 1 def factorial(n): return factorial_table[n] <file_sep># encoding=utf-8 ## SOLVED 2014/11/25 ## 272 # The square root of 2 can be written as an infinite continued fraction. # The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates # that 2 repeats ad infinitum. In a similar way, √23 = [4;(1,3,1,8)]. # It turns out that the sequence of partial values of continued fractions for # square roots provide the best rational approximations. Let us consider the # convergents for √2. # Hence the sequence of the first ten convergents for √2 are: 1, 3/2, 7/5, # 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ... # What is most surprising is that the important mathematical constant, # e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...]. # The first ten terms in the sequence of convergents for e are: # 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ... # The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17. # Find the sum of digits in the numerator of the 100th convergent of the # continued fraction for e. # index for the convergent of e that we want to obtain NTH_CONVERGENT = 100 def euler(): # numerator and denominator for the continued fraction numerator = 0 denominator = 1 # for each partial value, starting from the last, until the first for i in range(NTH_CONVERGENT - 2, -1, -1): # a is the current partial value (either 1, or 2k) a = 2 * (i // 3 + 1) if i % 3 == 1 else 1 # calculate the next fraction using # 1 / (a + 1 / d) = d / (ad + n) (numerator, denominator) = (denominator, numerator + a * denominator) # add the integer 2 to the number (add 2 * denominator to the numerator) numerator += 2 * denominator return sum(int(c) for c in str(numerator)) <file_sep># encoding=utf-8 ## SOLVED 2013/12/24 ## 45228 # We shall say that an n-digit number is pandigital if it makes use of all the # digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 # through 5 pandigital. # The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing # multiplicand, multiplier, and product is 1 through 9 pandigital. # Find the sum of all products whose multiplicand/multiplier/product identity # can be written as a 1 through 9 pandigital. # HINT: Some products can be obtained in more than one way so be sure to only # include it once in your sum. import helpers.sequence as sequence def euler(): products_cache = {} accumulator = 0 for permutation in sequence.permutations('123456789'): permutation = ''.join(permutation) products = valid_products(permutation) for product in products: if not product in products_cache: accumulator += product products_cache [product] = True return accumulator def valid_products(permutation): products = [] for split_1 in range(1, 5): for split_2 in(5 - split_1, 4 - split_1): if split_2 > 0: split_2 += split_1 multiplicand = int(permutation [: split_1]) multiplier = int(permutation [split_1 : split_2]) product = int(permutation [split_2 :]) if multiplicand * multiplier == product: products.append(product) return products <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 25164150 # The sum of the squares of the first ten natural numbers is, # 1^2 + 2^2 + ... + 10^2 = 385 # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)^2 = 55^2 = 3025 # Hence the difference between the sum of the squares of the first ten natural # numbers and the square of the sum is 3025 - 385 = 2640. # Find the difference between the sum of the squares of the first one hundred # natural numbers and the square of the sum. MAX = 100 def euler(): # list of numbers to use numbers = range(1, MAX + 1) # sum of the squares of each number sum_of_squares = sum(x * x for x in numbers) # square of the sum of those numbers square_of_sum = sum(numbers) ** 2 # return the difference of the two return square_of_sum - sum_of_squares <file_sep># encoding=utf-8 ## SOLVED 2017/07/08 ## 8581146 # A number chain is created by continuously adding the square of the digits in a # number to form a new number until it has been seen before. # For example, # 44 → 32 → 13 → 10 → 1 → 1 # 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 # Therefore any chain that arrives at 1 or 89 will become stuck in an endless # loop. What is most amazing is that EVERY starting number will eventually # arrive at 1 or 89. # How many starting numbers below ten million will arrive at 89? from collections import defaultdict def factorial(n): """Return the `n!`.""" acc = 1 for i in range(2, n + 1): acc *= i return acc def digit_sequences(tokens, n): """Iterator for sequences of `n` digits in sorted order, taken from the list of `tokens`. Sequences may contain the same digit more than once.""" if not tokens or n == 0: yield [] return for index, first in enumerate(tokens): if n == 1: yield [first] else: for seq in digit_sequences(tokens[index:], n - 1): if seq: yield [first] + seq def permutation_count(xs): """Return the number of permutations of the sequence `xs`, taking into account duplicate elements.""" lookup = defaultdict(lambda: 0) for x in xs: lookup[x] += 1 base = factorial(len(xs)) for i in lookup.values(): base //= factorial(i) return base def euler(): acc = 0 for i in range(1, 1000): arrives_at(i) for seq in digit_sequences(range(10), 7): m = sum(c * c for c in seq) if arrives_at(m) == 89: acc += permutation_count(seq) return acc arrives_at_cache = { 0: 0, 1: 1, 89: 89 } def arrives_at(n): """Determine which value the number `n` arrives at in the chain: 1 or 89.""" if n in arrives_at_cache: return arrives_at_cache[n] m = sum(int(c) * int(c) for c in str(n)) result = arrives_at(m) arrives_at_cache[n] = result return result <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 6857 # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? import helpers.prime as prime BIG_NUMBER = 600851475143 def euler(): # compute the prime factors of the big number factors = prime.prime_factors(BIG_NUMBER) # return the highest of the prime factors return max(factors) <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 232792560 # 2520 is the smallest number that can be divided by each of the numbers from 1 # to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the # numbers from 1 to 20? import helpers.prime as prime HIGHEST_DIVISOR = 20 def euler(): # dictionary containing the highest power of each prime factor zipped_factors = {} # for each number in the desired range for number in range(2, HIGHEST_DIVISOR + 1): # calculate its prime factors factors = prime.multiset_prime_factors(number) # for each of those factors, and its power for factor, power in factors.items(): # if that factor's power is higher than the one we had before if (not factor in zipped_factors or zipped_factors [factor] < power): # set the factor's power to this power zipped_factors [factor] = power # calculate the product of the prime factors elevated to the given powers accumulator = 1 for factor, power in zipped_factors.items(): accumulator *= factor ** power # return that product return accumulator <file_sep># encoding=utf-8 ## SOLVED 2013/12/21 ## 31626 # Let d(n) be defined as the sum of proper divisors of n (numbers less than n # which divide evenly into n). # If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and # each of a and b are called amicable numbers. # For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 # and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 # and 142; so d(284) = 220. # Evaluate the sum of all the amicable numbers under 10000. import helpers.prime as prime MAX = 10000 def euler(): # accumulator for the sum accumulator = 0 # for each value of a in the given range for a in range(1, MAX): # calculate the b b = d(a) # if a and b are amicable if b != 0 and d(b) == a and a < b: # add them to the sum accumulator += b + a # return the sum accumulator return accumulator def d(number): """Return the sum of the divisors of a given number. Divisors exclude the number itself, i.e.: d(2) = 1 = 1 d(4) = 1 + 2 = 3 d(6) = 1 + 2 + 3 = 6 """ return sum(prime.divisors(number)) - number <file_sep># encoding=utf-8 ## SOLVED 2014/12/07 ## 7295372 # Consider the fraction, n/d, where n and d are positive integers. If n<d and # HCF(n,d)=1, it is called a reduced proper fraction. # If we list the set of reduced proper fractions for d ≤ 8 in ascending order # of size, we get: # 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, # 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 # It can be seen that there are 3 fractions between 1/3 and 1/2. # How many fractions lie between 1/3 and 1/2 in the sorted set of reduced # proper fractions for d ≤ 12,000? import helpers.prime as prime import math DELTA = 0.0001 MAX = 12000 def euler(): # number of fractions found match_count = 0 # for each possible numerator n for n in range(2, math.ceil(MAX / 2) + 1): # lowest possible denominator for a fraction in the wanted range start = math.ceil(2 * n + DELTA) # highest possible denominator for a fraction in the wanted range end = min(MAX, int(3 * n - DELTA)) # construct a dictionary whose keys are all the denominators that # do *not* make a reduced fraction with the numerator n table = dict() for p in prime.prime_factors(n): for q in range(p, end + 1, p): table[q] = True # for each denominator d for d in range(start, end + 1): # if n / d is a reduced fraction if not d in table: match_count += 1 # return the number of fractions found return match_count <file_sep># encoding=utf-8 ## SOLVED ## 743 # For a number written in Roman numerals to be considered valid there are basic # rules which must be followed. Even though the rules allow some numbers to be # expressed in more than one way there is always a "best" way of writing a # particular number. # For example, it would appear that there are at least six ways of writing the # number sixteen: # IIIIIIIIIIIIIIII # VIIIIIIIIIII # VVIIIIII # XIIIIII # VVVI # XVI # However, according to the rules only XIIIIII and XVI are valid, and the last # example is considered to be the most efficient, as it uses the least number of # numerals. # The 11K text file, roman.txt (right click and 'Save Link/Target As...'), # contains one thousand numbers written in valid, but not necessarily minimal, # Roman numerals; see About... Roman Numerals for the definitive rules for this # problem. # Find the number of characters saved by writing each of these in their minimal form. # Note: You can assume that all the Roman numerals in the file contain no more # than four consecutive identical units. import re def euler(): acc = 0 with open('data/089.txt') as f: for roman in f: roman = roman.rstrip() decimal = roman_to_decimal(roman) converted = decimal_to_roman(decimal) acc += len(roman) - len(converted) return acc rx = re.compile('(.)\\1*') def roman_to_decimal(s): numerals = { 'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1 } def numeral(i): return numerals[groups[i][0]] def group_length(i): return groups[i][1] groups = [] for match in re.finditer(rx, s): groups.append((match.group(1), len(match.group(0)))) acc = 0 last_group = numeral(0) * group_length(0) for i in range(1, len(groups)): if numeral(i - 1) < numeral(i): acc -= last_group else: acc += last_group last_group = numeral(i) * group_length(i) acc += last_group return acc def decimal_to_roman(n): acc = '' numerals = [('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)] for numeral, value in numerals: while n >= value: acc += numeral n -= value return acc <file_sep># encoding=utf-8 ## SOLVED 2015/01/03 ## 71 # It is possible to write ten as the sum of primes in exactly five different # ways: # 7 + 3 # 5 + 5 # 5 + 3 + 2 # 3 + 3 + 2 + 2 # 2 + 2 + 2 + 2 + 2 # What is the first value which can be written as the sum of primes in over five # thousand different ways? from helpers.prime import * MAX = 100 def euler(): n = 10 while chain(n, n) < 5000: n += 1 return n # returns the number of possible ways to write `n` as a sum of primes, where # each prime is less than or equal to `l` def chain(n, l): # 0 means the previous number was a prime if n == 0: return 1 # 1 or a negative value, no way to write it as a prime if n < 2: return 0 # otherwise, chain through each possibility: for each prime q, see how many # ways there are to write `n-q` as a sum of primes, where all the other # primes are less than or equal to `q` acc = 0 for q in primes(l): acc += chain(n - q, q) return acc <file_sep># encoding=utf-8 ## SOLVED 2014/10/20 ## 107359 # Each character on a computer is assigned a unique code and the preferred # standard is ASCII (American Standard Code for Information Interchange). For # example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. # A modern encryption method is to take a text file, convert the bytes to # ASCII, then XOR each byte with a given value, taken from a secret key. The # advantage with the XOR function is that using the same encryption key on the # cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 # XOR 42 = 65. # For unbreakable encryption, the key is the same length as the plain text # message, and the key is made up of random bytes. The user would keep the # encrypted message and the encryption key in different locations, and without # both "halves", it is impossible to decrypt the message. # Unfortunately, this method is impractical for most users, so the modified # method is to use a password as a key. If the password is shorter than the # message, which is likely, the key is repeated cyclically throughout the # message. The balance for this method is using a sufficiently long password # key for security, but short enough to be memorable. # Your task has been made easy, as the encryption key consists of three lower # case characters. Using cipher.txt (right click and 'Save Link/Target As...'), # a file containing the encrypted ASCII codes, and the knowledge that the plain # text must contain common English words, decrypt the message and find the sum # of the ASCII values in the original text. from helpers.file import flattened_list_from_file import re def euler(): xs = flattened_list_from_file("data/059.txt", separator = ",") letter_range = range(ord('a'), ord('z') + 1) common_chars_rx = re.compile("[ a-zA-Z.,']") the_rx = re.compile("\\bthe\\b") for a in letter_range: for b in letter_range: for c in letter_range: key = [a, b, c] decrypted = "".join(chr(x ^ key[i % len(key)]) for i,x in enumerate(xs)) chars = len(decrypted) common_chars = len(common_chars_rx.findall(decrypted)) thes = len(the_rx.findall(decrypted)) if common_chars >= 0.95 * chars and thes >= 3: return sum(ord(c) for c in decrypted) return None <file_sep>#encoding=utf-8 ## SOLVED 2014/04/18 ## 121313 # By replacing the 1st digit of the 2-digit number *3, it turns out that six of # the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime. # By replacing the 3rd and 4th digits of 56**3 with the same digit, this # 5-digit number is the first example having seven primes among the ten # generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, # 56773, and 56993. Consequently 56003, being the first member of this family, # is the smallest prime with this property. # Find the smallest prime which, by replacing part of the number (not # necessarily adjacent digits) with the same digit, is part of an eight prime # value family. import helpers.prime as prime # number of replacements of digits that have to work FAMILY_SIZE = 8 def euler(): # for each "starting" prime number for prime_number in prime.primes(200000): # list of integers for each digit prime_number_digits = list(int(digit) for digit in str(prime_number)) # set (without duplicates) of the digits in the prime number prime_number_digit_set = set(prime_number_digits) # for each digit that could be replaced in the prime number for base_digit in prime_number_digit_set: # number of digit replacements that are actual prime numbers prime_count = 0 # never replace the first digit with a zero replacements = range(10) if prime_number_digits[0] != base_digit \ else range(1, 10) # for each possible digit replacement for replacement_digit in replacements: # replace the digit base_digit with replacement_digit modified_digits = replace(prime_number_digits, base_digit, replacement_digit) # convert that list to a number modified_number = int(''.join(str(digit) \ for digit in modified_digits)) # if it's a prime, increment the prime count (duh) if prime.is_prime(modified_number): prime_count += 1 # return if the answer if we found it if prime_count == FAMILY_SIZE: return prime_number def replace(xs, base, replacement): """Replaces every 'base' in 'xs' with 'replacement'. Non destructive. Args: xs: Initial list of elements. base: Element to be replaced in the new list. replacement: Element to replace that value with. Returns: A new list with the replacement applied.""" return [x if x != base else replacement for x in xs] <file_sep>import re def list_from_file (file_name, separator = '\\s+', convert_to = int): """Returns a 2-D list which contains the content of a file, with lines corresponding to sublists and elements being converted with function convert_to. separator is used (as a regexp) as a separator for each element.""" array = [] with open (file_name) as data_file: for line in data_file: line = line.strip () tokens = re.split (separator, line) tokens = [convert_to (token) for token in tokens] array.append (tokens) return array def flattened_list_from_file (file_name, separator = '\\s+', convert_to = int): """Returns list_from_file as a 1-D list instead of a 2-D list (useful when each row has only 1 element anyways).""" array = list_from_file (file_name, separator, convert_to) array = [element for row in array for element in row] return array <file_sep>#encoding=utf-8 ## SOLVED 2014/04/18 ## 142857 # It can be seen that the number, 125874, and its double, 251748, contain # exactly the same digits, but in a different order. # Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, # contain the same digits. import helpers.sequence as sequence # list of factors for the multiplications that have to be checked FACTORS = [2, 3, 4, 5, 6] def euler(): # set of the digits to use for generating numbers: all the digits except # '1', see related hack digits = list(set(range(10)) - {1}) # number of matches found, only take the second one matches_count = 0 # for each permutation of the digits for digit_permutation in sequence.permutations(digits): # for each truncation in that permutation for base_digits in sequence.right_truncations(digit_permutation): # add '1' at the beginning of the number, because the number # must start with a '1' in order to have the same number of digits # when multiplied by 6 base_digits = [1] + base_digits # the base number which will be multiplied base = int(''.join(str(digit) for digit in base_digits)) # found will stay True if all the multiplications by the FACTORS # have the same digits found = True # for each factor, check if it yields the same digits for factor in FACTORS: found = found and set(str(base)) == set(str(base * factor)) # if it's a valid answer if found: # return the second valid answer found matches_count += 1 if matches_count == 2: return base <file_sep># encoding=utf-8 ## SOLVED 2013/12/25 ## 840 # If p is the perimeter of a right angle triangle with integral length sides, # {a,b,c}, there are exactly three solutions for p = 120. # {20,48,52}, {24,45,51}, {30,40,50} # For which value of p ≤ 1000, is the number of solutions maximised? import math MAX = 1000 def euler(): triangle_counts = [0 for i in range(1, MAX)] for a in range(1, MAX): for b in range(1, MAX): c = math.sqrt(a * a + b * b) if int(c) == c and a + b + c < MAX: triangle_counts [int(a + b + c)] += 1 return triangle_counts.index(max(triangle_counts)) <file_sep>def permutations (tokens): """Used as an iterator for all the permutations of a sequence.""" if not tokens: yield [] return encountered = set () for index, first in enumerate (tokens): if first not in encountered: rest = tokens [: index] + tokens [index + 1:] encountered.add(first) for permutation in permutations (rest): yield [first] + permutation def n_permutations(tokens, n): """Used as an iterator for all n-permutations of a sequence.""" if not tokens: yield [] return if n == 0: yield [] return encountered = set() for index, first in enumerate(tokens): if first not in encountered: rest = tokens[: index] + tokens[index + 1 :] encountered.add(first) for perm in n_permutations(rest, n - 1): yield [first] + perm def take_n(tokens, n): """Used as an iterator for all possible combinations of n elements from tokens.""" if not tokens: yield [] return if n == 0: yield [] return encountered = set() for index, first in enumerate(tokens): if first not in encountered: rest = tokens[index + 1 :] encountered.add(first) if n == 1: yield [first] else: for perm in take_n(rest, n - 1): if perm: yield [first] + perm def is_permutation(xs, ys): """Returns True iff the two lists are permutations of eachother.""" return sorted(xs) == sorted(ys) def left_truncations (tokens): """Used as an iterator for all truncations of a sequence, from the left. For instance, left_truncations('123') yields '123', '12', and '1'.""" while tokens: yield tokens tokens = tokens [: -1] def right_truncations (tokens): """Used as an iterator for all truncations of a sequence, from the right. For instance, right_truncations('123' yields '123', '23', and '3'.""" while tokens: yield tokens tokens = tokens [1 :] def rotate (tokens): """Returns a rotated sequence from the given sequence. All elements are moved one position to the right, and the last element is placed at the beginning.""" return tokens [-1 :] + tokens [: -1] def rotations (tokens): """Used as an iterator for all rotations of a sequence, as per the rotate() function.""" rotation = tokens for iterator in range (len (tokens)): yield rotation rotation = rotate (rotation) <file_sep>#encoding=utf-8 ## SOLVED 2014/04/17 ## 997651 # The prime 41, can be written as the sum of six consecutive primes: # 41 = 2 + 3 + 5 + 7 + 11 + 13 # This is the longest sum of consecutive primes that adds to a prime below # one-hundred. # The longest sum of consecutive primes below one-thousand that adds to a # prime, contains 21 terms, and is equal to 953. # Which prime, below one-million, can be written as the sum of the most # consecutive primes? import helpers.prime as prime # highest value for the resulting prime MAX = 1000000 def euler(): # highest number of consecutive primes that add up to a prime highest_chain_length = 1 # highest resulting sum that was found highest_chain = 2 # for each prime for prime_number in prime.primes(MAX): # exit when it can't possibly be the start of a new chain if prime_number > MAX // highest_chain_length: break # start a chain from this prime number accumulator = prime_number # length of the current chain chain_length = 1 # for each prime starting from here for chain_prime in prime.primes(MAX): # exit when outside the bounds if accumulator > MAX: break # skip the primes below the "prime_number" start if chain_prime > prime_number: # if it's a prime and the chain length is longer than the # longest chain so far if prime.is_prime(accumulator) and \ chain_length > highest_chain_length: highest_chain_length = chain_length highest_chain = accumulator # increase chain length and add the next prime chain_length += 1 accumulator += chain_prime return highest_chain <file_sep>#encoding=utf-8 ## SOLVED 2014/04/18 ## 4075 # There are exactly ten ways of selecting three from five, 12345: # 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 # In combinatorics, we use the notation, 5_C_3 = 10. # In general, # n_C_r = n! / (r! * (n - r)!) # It is not until n = 23, that a value exceeds one-million: 23_C_10 = 1144066. # How many, not necessarily distinct, values of n_C_r, for 1 ≤ n ≤ 100, are # greater than one-million? # highest value for 'n' HIGHEST_N = 100 # the minimum value for an answer to be valid THRESHOLD = 1000000 def euler(): # number of values above one million answer_count = 0 # for each value of n for n in range(1, HIGHEST_N + 1): # for each value of r, from 1 to n - 1 for r in range(1, n): # if the number of possibilities is higher than one million if factorial(n) / (factorial(r) * factorial(n - r)) > THRESHOLD: # increment the number of answers answer_count += 1 # return the number of answers return answer_count # optimizes the factorial() function through memoization factorial_cache = {0: 1} def factorial(n): """Returns the factorial of n.""" # use cache if possible if n in factorial_cache: return factorial_cache[n] # otherwise, fill cache recursively, and *then* use it else: factorial_cache[n] = n * factorial(n - 1) return n * factorial(n - 1) <file_sep># encoding=utf-8 ## SOLVED 2013/12/20 ## 137846528820 # Starting in the top left corner of a 2x2 grid, and only being able to move to # the right and down, there are exactly 6 routes to the bottom right corner. # How many such routes are there through a 20x20 grid? GRID_SIZE = 21 def euler(): # construct the 21x21 grid, whose elements are the number of possible paths # to reach that cell grid = [[0 for y in range(GRID_SIZE)] for x in range(GRID_SIZE)] # initialize the top and left borders with 1 everywhere for i in range(GRID_SIZE): grid [i][0] = 1 grid [0][i] = 1 # for each grid cell for y in range(1, GRID_SIZE): for x in range(1, GRID_SIZE): # this grid is equal to the sum of the one above it, and the one to # its left grid [y][x] = grid [y - 1][x] + grid [y][x - 1] # return the value of the last grid return grid [GRID_SIZE - 1][GRID_SIZE - 1] <file_sep># encoding=utf-8 ## SOLVED 2014/11/18 ## 127035954683 # The cube, 41063625 (3453), can be permuted to produce two other cubes: # 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube # which has exactly three permutations of its digits which are also cube. # Find the smallest cube for which exactly five permutations of its digits are # cube. from helpers.sequence import is_permutation from math import ceil def euler(): for n in range(346, 6000): # number of cubes that are permutations of n^3 cube_permutations = 0 digits = str(n * n * n) maximum = maximum_for(digits) # for each number from n to maximum (see maximum_for()), check if its # cube is a permutation of n for m in range(n, maximum): cube = m * m * m if is_permutation(str(cube), digits): cube_permutations += 1 # return it if it has the right number of permutations if cube_permutations == 5: return n ** 3 # calculate the highest possible value for the cube root of a permutation of # the given digits def maximum_for(digits): xs = reversed(sorted(digits)) return ceil(int("".join(xs)) ** (1 / 3)) <file_sep>## Module for various functions related to discreet mathematics. import helpers.prime as prime def totient(n): """Return the number of integers <= n that are relatively prime with n.""" t = n for p in set(prime.prime_factors(n)): t *= 1 - 1 / p return round(t) # list of partitions, used by partition(), and indirectly by next_p ps = [0, 1] def partition(n): """Return the partition of n. See Euler's pentagonal number theorem.""" n += 1 i = len(ps) while i <= n: ps.append(_next_p(i, ps)) i += 1 return ps[n] # helper function for partition(): calculate the next partition def _next_p(n, ps): acc = 0 for dk in (-1, 1): k = dk q = pentagonal(k) while q < n: acc += int(((-1) ** (k - 1)) * ps[n - q]) k += dk q = pentagonal(k) return acc # helper function for partition(): calculate the k-th pentagonal number def pentagonal(k): return int(k * (3 * k - 1) / 2) def gcd(a, b): """Return the greatest common divisor for the two integers.""" if a == b: return a if a == 0: return b if b == 0: return a if a % 2 == 0: if b % 2 == 1: return gcd(a / 2, b) else: return gcd(a / 2, b / 2) * 2 if b % 2 == 0: return gcd(a, b / 2) if a > b: return gcd((a - b) / 2, b) return gcd((b - a) / 2, a) <file_sep># encoding=utf-8 ## SOLVED 2013/12/19 ## 104743 # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see # that the 6th prime is 13. # What is the 10 001st prime number? import helpers.prime as prime INDEX = 10000 def euler(): # generate 10001 prime numbers prime._generate_n_primes(INDEX + 1) # return the 10001st prime number return prime.prime_list [INDEX]
7cb2cf86d40aa2153404eb621c69d553600f20e7
[ "Markdown", "Python" ]
99
Python
6112/project-euler
b7478d14aa6defe347ab12178c7ffe90efdcb867
c21934a27f628acda284def9e0e9db814d909f2d
refs/heads/main
<file_sep>const express = require('express') const app = express() const port = 9000; const cors = require('cors') app.use(cors()) app.use(express.urlencoded({ extended: true })); app.use(express.json()) // To parse the incoming requests with JSON payloads const jwt = require('./jwt') app.get('/test', (req, res) => { // res.send('Hello World!') // res.send(md5("123456")) }) app.post('/api/oauth/token', (req, res)=>{ }) app.post('/va/bills', (req, res)=>{ }) app.post('/va/payments', (req, res)=>{ }) // conn.end() app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
3a36a942b79357ad7e1d8d9cb934a066cee34619
[ "JavaScript" ]
1
JavaScript
alsocodes/rest-va-bca
21bc4a0f7485b9da849b9ffe34eb5713ad2a6410
0b56917a5d3f1260b968d303d532bd516c3fb7af
refs/heads/master
<repo_name>arvind1234/cpp<file_sep>/endian.c #include<stdio.h> int main() { int x = 1; char *p; p = (char *) &x; if (*p) printf("little endian"); else printf("big endian"); } <file_sep>/recursiveReverse.cpp #include <iostream> using namespace std; typedef struct node { int data; struct node *next; } Node; void recursiveReverse(Node** headRef); Node * newNode(int data) { Node *newNode = new Node; newNode->data = data; newNode->next = NULL; return newNode; } void insertAtFront(Node** headRef, int data) { Node *_newNode = newNode(data); if (!*headRef) { // cout << "\n Inserting first node:" << data; *headRef = _newNode; } else { // cout << "\n Inserting middle node:" << data; _newNode->next = *headRef; *headRef = _newNode; } } void printList(Node *head) { cout << endl; while(head) { cout << head->data; head = head->next; if (head) { cout << "->"; } } cout << endl; } void reverse(Node **headRef) { Node *curr = *headRef; if (!curr || !curr->next) { return; } Node *tempNext, *tail = NULL; while(curr) { tempNext = curr->next; curr->next = tail; tail = curr; curr = tempNext; } *headRef = tail; } void recursiveReverse(Node** headRef) { if (!*headRef || !(*headRef)->next) { return; } Node *curr = *headRef; Node *rest = (*headRef)->next; recursiveReverse(&rest); curr->next->next = curr; curr->next = NULL; *headRef = rest; // cout << "curr:" << curr->data << "rest:" << rest->data; } void insertNth(Node **headRef, int n, int data) { if (n == 0) { insertAtFront(headRef, data); return; } int i = 0; Node *curr = *headRef; while(curr) { if (i == n - 1) break; i++; curr = curr->next; } // && i <= n - 1 if (!curr) { cout << "index too far" << endl; } else { // cout << ((curr == NULL) ? "curr is null" : "curr is not null") << endl; Node *_newNode = newNode(data); _newNode->next = curr->next; curr->next = _newNode; } } int main() { int count = 5; // cout << "\nEnter number of nodes:"; // cin >> count; Node *head = NULL; while(count > 0) { insertAtFront(&head, count); count--; } printList(head); recursiveReverse(&head); printList(head); reverse(&head); printList(head); cout << "\nInserting -1 at 0:"; insertNth(&head, 0, -1); printList(head); cout << "\nInserting 6 at 6:"; insertNth(&head, 6, 6); printList(head); cout << "\nInserting 7 at 7:"; insertNth(&head, 7, 7); printList(head); cout << "\nInserting 8 at 8:"; insertNth(&head, 8, 8); printList(head); cout << "\nInserting 10 at 10:"; insertNth(&head, 10, 10); }
cac84b4212f530da8468ff740c367e01dbabc03e
[ "C", "C++" ]
2
C
arvind1234/cpp
092dda3f4062ebbcb44113a1930f987df6aaadc3
5b6f5499138385fd29f23b33f6d71d9e57e5958a
refs/heads/master
<repo_name>vedantpuri/Scapegoat-Tree<file_sep>/src/structures/ScapegoatTree.java package structures; public class ScapegoatTree<T extends Comparable<T>> extends BinarySearchTree<T> { private int upperBound=0; /** * Adds an element to the tree. * * The modified tree must still obey the BST rule, though it might not be * balanced. * * In addition to obeying the BST rule, the resulting tree must also obey * the scapegoat rule. * * This method must only perform rebalancing of subtrees when indicated * by the scapegoat rule; do not unconditionally call balance() * after adding, or you will receive no credit. * See the project writeup for details. * * @param element * @throws NullPointerException if element is null */ @Override public void add(T element) { // TODO if (element == null) throw new NullPointerException(); upperBound ++; root = this.addToSubtree(element,root); if (this.height() > (Math.log(upperBound) / Math.log(1.5))) { BSTNode<T> scapegoat = this.recGet(element, root); while (scapegoat.getParent() != null) { if (((double)subtreeSize(scapegoat)/subtreeSize(scapegoat.getParent()))>0.67) break; else scapegoat=scapegoat.getParent(); } BinarySearchTree<T> subtree = new BinarySearchTree<T>(); subtree.root = scapegoat.getParent(); BSTNode<T> join = scapegoat.getParent().getParent(); subtree.balance(); if (join != null) { if (subtree.root.getData().compareTo(join.getData()) <= 0) join.setLeft(subtree.root); else join.setRight(subtree.root); } root = this.getRoot(); } } /** * Attempts to remove one copy of an element from the tree, returning true * if and only if such a copy was found and removed. * * The modified tree must still obey the BST rule, though it might not be * balanced. * * In addition to obeying the BST rule, the resulting tree must also obey * the scapegoat rule. * * This method must only perform rebalancing of subtrees when indicated * by the scapegoat rule; do not unconditionally call balance() * after removing, or you will receive no credit. * See the project writeup for details. * @param element * @return true if and only if an element removed * @throws NullPointerException if element is null */ @Override public boolean remove(T element) { // TODO if (element == null) throw new NullPointerException(); BSTNode<T> toRemove = this.recGet(element,root); if (toRemove == null) return false; else { this.root = this.removeFromSubtree(root, toRemove.getData()); if (upperBound > (2 * this.size())) { this.balance(); upperBound = this.size(); } return true; } } } <file_sep>/src/structures/BinarySearchTree.java package structures; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class BinarySearchTree<T extends Comparable<T>> implements BSTInterface<T> { protected BSTNode<T> root; public boolean isEmpty() { return root == null; } public int size() { return subtreeSize(root); } protected int subtreeSize(BSTNode<T> node) { if (node == null) { return 0; } else { return 1 + subtreeSize(node.getLeft()) + subtreeSize(node.getRight()); } } public boolean contains(T t) { // TODO if (t == null) throw new NullPointerException(); if (get(t) == null ) return false; else return true; } public boolean remove(T t) { if (t == null) throw new NullPointerException(); boolean result = contains(t); if (result) { root = removeFromSubtree(root, t); } return result; } protected BSTNode<T> removeFromSubtree(BSTNode<T> node, T t) { // node must not be null int result = t.compareTo(node.getData()); if (result < 0) { node.setLeft(removeFromSubtree(node.getLeft(), t)); return node; } else if (result > 0) { node.setRight(removeFromSubtree(node.getRight(), t)); return node; } else { if (node.getLeft() == null) return node.getRight(); else if (node.getRight() == null) return node.getLeft(); else { // neither child is null T predecessorValue = getHighestValue(node.getLeft()); node.setLeft(removeRightmost(node.getLeft())); node.setData(predecessorValue); return node; } } } private T getHighestValue(BSTNode<T> node) { // node must not be null if (node == null) throw new NullPointerException(); if (node.getRight() == null) return node.getData(); else return getHighestValue(node.getRight()); } private BSTNode<T> removeRightmost(BSTNode<T> node) { // node must not be null if (node == null) throw new NullPointerException(); if (node.getRight() == null) return node.getLeft(); else { node.setRight(removeRightmost(node.getRight())); return node; } } public T get(T t) { // TODO if (t == null) throw new NullPointerException(); BSTNode<T> val=recGet(t,root); if (val == null) return null; return val.getData(); } protected BSTNode<T> recGet(T element,BSTNode<T> tree) { if(tree == null) return null; else if(element.compareTo(tree.getData()) < 0) return recGet(element,tree.getLeft()); else if(element.compareTo(tree.getData()) > 0) return recGet(element,tree.getRight()); else return tree; } public void add(T t) { if (t == null) throw new NullPointerException(); root = addToSubtree(t, root); } protected BSTNode<T> addToSubtree(T t, BSTNode<T> node) { if (node == null) return new BSTNode<T>(t, null, null); if (t.compareTo(node.getData()) <= 0) node.setLeft(addToSubtree(t, node.getLeft())); else node.setRight(addToSubtree(t, node.getRight())); return node; } @Override public T getMinimum() { // TODO BSTNode<T> x = root; if (isEmpty()) return null; else while(x.getLeft() != null) x = x.getLeft(); return x.getData(); } @Override public T getMaximum() { // TODO BSTNode<T> x = root; if (isEmpty()) return null; else while(x.getRight() != null) x = x.getRight(); return x.getData(); } @Override public int height() { // TODO if(isEmpty()) return -1; if (this.size() == 1) return 0; else return recHeight(root) - 1; } private int recHeight(BSTNode<T> tree) { if (tree == null)return 0; int hl = 0,hr = 0; hl = 1 + recHeight(tree.getLeft()); hr = 1 + recHeight(tree.getRight()); return ((hl > hr) ? hl : hr ); } @Override public Iterator<T> preorderIterator() { // TODO Queue<T> queue = new LinkedList<T>(); preorderTraverse(queue, root); return queue.iterator(); } private void preorderTraverse(Queue<T> queue, BSTNode<T> node) { if (node != null) { queue.add(node.getData()); preorderTraverse(queue, node.getLeft()); preorderTraverse(queue, node.getRight()); } } @Override public Iterator<T> inorderIterator() { Queue<T> queue = new LinkedList<T>(); inorderTraverse(queue, root); return queue.iterator(); } private void inorderTraverse(Queue<T> queue, BSTNode<T> node) { if (node != null) { inorderTraverse(queue, node.getLeft()); queue.add(node.getData()); inorderTraverse(queue, node.getRight()); } } @Override public Iterator<T> postorderIterator() { // TODO Queue<T> queue = new LinkedList<T>(); postorderTraverse(queue, root); return queue.iterator(); } private void postorderTraverse(Queue<T> queue, BSTNode<T> node) { if (node != null) { postorderTraverse(queue, node.getLeft()); postorderTraverse(queue, node.getRight()); queue.add(node.getData()); } } @Override public boolean equals(BSTInterface<T> other) { // TODO if (other == null) throw new NullPointerException(); if(this.size() != other.size()) return false; return recEquals(this.getRoot(),other.getRoot()); } private boolean recEquals(BSTNode<T> thisNode,BSTNode<T> otherNode) { if (thisNode == null && otherNode == null) return true; if ((thisNode == null && otherNode != null) || (thisNode != null && otherNode == null)) return false; else{ if (thisNode.getData().equals(otherNode.getData())) { if(recEquals(thisNode.getLeft(),otherNode.getLeft()) && recEquals(thisNode.getRight(),otherNode.getRight())) return true; } } return false; } @Override public boolean sameValues(BSTInterface<T> other) { // TODO if (other == null) throw new NullPointerException(); Iterator<T> otheriter = other.inorderIterator(); if (this.size() != other.size()) return false; while(otheriter.hasNext()) { if(!this.contains(otheriter.next())) return false; } return true; } @Override public boolean isBalanced() { // TODO if (isEmpty()) return true; return (Math.pow(2, this.height()) <= this.size() && this.size() < Math.pow(2, this.height() + 1)); } @Override public void balance() { // TODO Iterator<T> balan = this.inorderIterator(); @SuppressWarnings("unchecked") T[] array = (T[]) new Comparable[this.size()]; int index = 0; while (balan.hasNext()) { array[index] = balan.next(); index ++; } root = null; root = this.insertTree(0, array.length-1,array); } private BSTNode<T> insertTree (int low, int high, T[] arr) { if (low > high) return null; int mid = (low + high) / 2; BSTNode<T> newRoot= new BSTNode<T>(arr[mid],null,null); newRoot.setLeft(insertTree(low,mid - 1,arr)); newRoot.setRight(insertTree(mid + 1,high,arr)); return newRoot; } @Override public BSTNode<T> getRoot() { // DO NOT MODIFY return root; } public static <T extends Comparable<T>> String toDotFormat(BSTNode<T> root) { // DO NOT MODIFY // see project description for explanation // header int count = 0; String dot = "digraph G { \n"; dot += "graph [ordering=\"out\"]; \n"; // iterative traversal Queue<BSTNode<T>> queue = new LinkedList<BSTNode<T>>(); queue.add(root); BSTNode<T> cursor; while (!queue.isEmpty()) { cursor = queue.remove(); if (cursor.getLeft() != null) { // add edge from cursor to left child dot += cursor.getData().toString() + " -> " + cursor.getLeft().getData().toString() + ";\n"; queue.add(cursor.getLeft()); } else { // add dummy node dot += "node" + count + " [shape=point];\n"; dot += cursor.getData().toString() + " -> " + "node" + count + ";\n"; count++; } if (cursor.getRight() != null) { // add edge from cursor to right child dot += cursor.getData().toString() + " -> " + cursor.getRight().getData().toString() + ";\n"; queue.add(cursor.getRight()); } else { // add dummy node dot += "node" + count + " [shape=point];\n"; dot += cursor.getData().toString() + " -> " + "node" + count + ";\n"; count++; } } dot += "};"; return dot; } }
2c9c9df8d44639ff866fe4cf76cdc7eb5424aaa2
[ "Java" ]
2
Java
vedantpuri/Scapegoat-Tree
0550b6c58c8c96334b218c5ff2e145e22c5d483c
d9b6ed6f5a21a4abdb934739924d3fc99f965b98
refs/heads/master
<repo_name>paulamisen12/hello<file_sep>/tuitionProject/src/test/java/Base/TestBase.java package Base; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.*; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import Utilities.ExtentManager; public class TestBase { public static Logger log = Logger.getLogger("rootLogger"); public ExtentReports rep = ExtentManager.getInstance(); public static ExtentTest test; public static XSSFWorkbook workbook; public static XSSFSheet worksheet; public static DataFormatter formatter= new DataFormatter(); public static String file_location = System.getProperty("user.dir")+"//Data.xlsx"; public static String SheetName="TestCase1"; public static Properties p = new Properties(); public static FileReader reader; public static WebDriver driver; @BeforeSuite(description="Before suite Setup") public void BeforeClass(){ log.debug("Log Initialized"); log.debug("Before Suite Run Set up begins"); try{ reader=new FileReader(System.getProperty("user.dir")+"\\src\\main\\resources\\Config.properties"); p.load(reader); log.debug("Properties File Initialized"); } catch(Exception e){ log.error("Properties File NOT Initialized"); } } @BeforeMethod public void BeforeMethod(){ System.out.println(p.getProperty("browser")); if(p.getProperty("browser").equalsIgnoreCase("firefox")){ System.setProperty("webdriver.gecko.driver", "C:\\Users\\dipra\\Desktop\\Driver\\geckodriver.exe"); driver = new FirefoxDriver(); log.debug("Firefox Driver File Initialized"); } driver.get(p.getProperty("url")); } @AfterMethod(description="After Method") public void AfterMethod(){ driver.quit(); log.debug("Driver Quit"); } @DataProvider public static Object[][] ReadVariant() throws IOException{ FileInputStream fileInputStream= new FileInputStream(file_location); //Excel sheet file location get mentioned here workbook = new XSSFWorkbook (fileInputStream); //get my workbook worksheet=workbook.getSheet(SheetName);// get my sheet from workbook XSSFRow Row=worksheet.getRow(0); //get my Row which start from 0 int RowNum = worksheet.getPhysicalNumberOfRows();// count my number of Rows int ColNum= Row.getLastCellNum(); // get last ColNum Object Data[][]= new Object[RowNum-1][ColNum]; // pass my count data in array for(int i=0; i<RowNum-1; i++) //Loop work for Rows { XSSFRow row= worksheet.getRow(i+1); for (int j=0; j<ColNum; j++) //Loop work for colNu\m { String value=formatter.formatCellValue(row.getCell(j)); Data[i][j]=value; //This formatter get my all values as string i.e integer, float all type data value } } log.debug("Data Provider Returned data"); return Data; } } <file_sep>/tuitionProject/src/test/java/Tests/Test1.java package Tests; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import Base.TestBase; import Pages.*; public class Test1 extends TestBase{ HomePage homePage; @Test(dataProvider="ReadVariant") //It get values from ReadVariant function method public void HomePage(String to, String from) throws InterruptedException{ //Create Page object System.out.println(to); System.out.println(from); homePage = new HomePage(driver); homePage.selectlocation(homePage.locationFrom, to); homePage.selectlocation(homePage.locationTo, from); homePage.searchButton.click(); Thread.sleep(3000); Assert.assertEquals(driver.getTitle(), "Flight Search"); } }
b36ce286904230859f80b29625b77f4a98744160
[ "Java" ]
2
Java
paulamisen12/hello
077950dffad2b8ca53345cdc0e99161b888444e2
7ab276f17b8c81cafd0ea741adeb83fe9264306f
refs/heads/master
<repo_name>Srivatsava6/imad-2016-app<file_sep>/server.js var express = require('express'); var morgan = require('morgan'); var path = require('path'); var app = express(); app.use(morgan('combined')); var webpages={ 'newpage-one': { title: 'article 1: srivatsavas first blog ', heading:'Article1', date: '7 october 2016', content:` <p> This is my first html page in hasura </p>` }, 'newpage-two': { title: 'article 2: srivatsavas second blog ', heading:'Article2', date: '8 october 2016', content:` <p> This is my second html page in hasura. This is my second html page in hasura. This is my second html page in hasura. </p> <p> This is my second html page in hasura. This is my second html page in hasura. This is my second html page in hasura. </p>` }, 'newpage-three': { title: 'article 2: srivatsavas second blog ', heading:'Article2', date: '8 october 2016', content:` <p> This is my third html page in hasura. This is my third html page in hasura. This is my third html page in hasura. </p> <p> This is my third html page in hasura. This is my third html page in hasura. This is my third html page in hasura. </p> <p> This is my third html page in hasura. This is my third html page in hasura. This is my third html page in hasura. </p>` } }; function createTemplate(data){ var title=data.title; var heading=data.heading; var date= data.date; var content= data.content; var newTemplate= ` <html> <head> <title> ${title} </title> <link href="/ui/style.css" rel="stylesheet" /> <meta name="viewport" content="width=device-width , initial-scale=1"/> </head> <body> <div class="container"> <div> <a href="/">HOME</a> </div> <hr/> <h3> ${heading}</h3> <div> ${date} </div> <div> ${content} </div> </div> </body> </html>` ; return newTemplate; } app.get('/', function (req, res) { res.sendFile(path.join(__dirname, 'ui', 'index.html')); }); app.get('/:articleNam',function(req,res){ var articleNam=req.params.articleNam; res.send(createTemplate(webpages[articleNam])); }); app.get('/ui/style.css', function (req, res) { res.sendFile(path.join(__dirname, 'ui', 'style.css')); }); app.get('/ui/main.js', function (req, res) { res.sendFile(path.join(__dirname, 'ui', 'main.js')); }); app.get('/ui/madi.png', function (req, res) { res.sendFile(path.join(__dirname, 'ui', 'madi.png')); }); var port = 8080; // Use 8080 for local development because you might already have apache running on 80 app.listen(8080, function () { console.log(`IMAD course app listening on port ${port}!`); }); <file_sep>/ui/main.js console.log('Loaded!'); alert("hi the page got loaded"); var element=document.getElementById('firstid'); element.innerHTML="new value"; var image=document.getElementById('img'); var marginLeft=0; function moveRight() { marginLeft=marginLeft+10; image.style.marginLeft=marginLeft+'px'; } image.onclick= function() { var interval=setInterval(moveRight,40); };
77ddb92d79a14da2b898d45f051ade0d9166f69d
[ "JavaScript" ]
2
JavaScript
Srivatsava6/imad-2016-app
7946ff99cc818f47509901190e9aac0b3cd71d56
56012b16b7a6c152ecc199b600c0e5155ae6d755
refs/heads/master
<file_sep># AzureTablePurger A command line utility to delete old data (eg logging data) from an Azure Storage Table. ## Note This relies on the target table having its `PartitionKey` formatted in a specific way, namely ascending ticks with a leading 0, eg `0636738338530008778`. This is the default format for Serilog, Windows Azure Diagnostic Logs (eg `WADDiagnosticsInfrastructureLogsTable`, `WADLogsTable`, `WADPerformanceCountersTable`, `WADWindowsEventLogsTable`) and other logging packages. ## Background For more info on the background of this tools, see: [How to Delete Old Data From An Azure Storage Table: Part 1](https://brentonwebster.com/blog/deleting-stuff-from-an-azure-table-part-1) and [Part 2](https://brentonwebster.com/blog/how-to-delete-old-data-from-an-azure-storage-table-part-2). ## Usage Example: `.\AzureTablePurger.App.exe -account "[YourStorageAccountConnectionString]" -table "[YourTableName]" -days 365` This will delete all records in `[YourTableName]` under the storage account identified by `[YourStorageAccountConnectionString]` that are older than `365` days. You can interrupt this process at any time and restart it. The process is reentrant, so it will pick up where it left off and keep going. ### Configuration You can specify configuration in 3 ways: 1. Via the command line: - `-account [storage account connection string]`: the connection string for the account you want to target - `-table [name of table]`: the name of the table inside the storage account - `-days [number of days]`: delete all records that are older than this amount of days. Defaults to `365` 2. Via config in your `appsettings.json` file 3. Via config in your local user `secrets.json` file If you're storing your storage account connection string, you're better off storing it in your user secrets file instead of your `appsettings.json` file. ## Performance While you can run this from your local machine, for best performance, run this from a VM that is deployed in the same region as your Azure storage account. As an example, I was getting deletion throughput of around 80-90 entities per second when running from my local machine, vs 2000+ entities per second when running from a VM deploying in the same region as my Azure Storage account. <file_sep>using System; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AzureTablePurger.Services.Tests { [TestClass] public class TicksAscendingWithLeadingZeroPartitionKeyHandlerTest { private TicksAscendingWithLeadingZeroPartitionKeyHandler _target; [TestInitialize] public void Initialize() { _target = new TicksAscendingWithLeadingZeroPartitionKeyHandler(new NullLogger<TicksAscendingWithLeadingZeroPartitionKeyHandler>()); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ConvertPartitionKeyToDateTime_FailsWithGuid() { // Arrange // Act _target.ConvertPartitionKeyToDateTime(Guid.NewGuid().ToString()); // Assert - handled by method attribute } [TestMethod] public void GetTableQuery_WorksWithNullLowerBound() { // Arrange string upperBound = DateTime.Now.Ticks.ToString("D19"); // Act var query = _target.GetTableQuery(null, upperBound); // Assert Assert.AreEqual($"(PartitionKey ge '0') and (PartitionKey lt '{upperBound}')", query.FilterString); StandardSelectColumnAsserts(query); } [TestMethod] public void GetTableQuery_WorksWithNotNullLowerBound() { // Arrange string lowerBound = DateTime.Now.Ticks.ToString("D19"); string upperBound = DateTime.Now.Ticks.ToString("D19"); // Act var query = _target.GetTableQuery(lowerBound, upperBound); // Assert Assert.AreEqual($"(PartitionKey ge '{lowerBound}') and (PartitionKey lt '{upperBound}')", query.FilterString); StandardSelectColumnAsserts(query); } [TestMethod] public void GetTableQuery_PurgeEntitiesOlderThanDays_Works() { // Arrange int days = 100; // the timestamp here will be different to what the method generates. Take only the first portion of the timestamp for comparison string approxUpperBound = DateTime.Now.AddDays(-1 * days).Ticks.ToString("D19"); string firstPortionOfUpperBound = approxUpperBound.Substring(0, 6); // Act var query = _target.GetTableQuery(days); // Assert Assert.IsTrue(query.FilterString.Contains($"(PartitionKey ge '0') and (PartitionKey lt '{firstPortionOfUpperBound}")); StandardSelectColumnAsserts(query); } private void StandardSelectColumnAsserts(TableQuery query) { Assert.AreEqual(2, query.SelectColumns.Count); Assert.AreEqual("PartitionKey", query.SelectColumns[0]); Assert.AreEqual("RowKey", query.SelectColumns[1]); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using AzureTablePurger.Common.Extensions; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.Logging; namespace AzureTablePurger.Services { public class SimpleTablePurger : ITablePurger { public const int MaxBatchSize = 100; public const int ConnectionLimit = 32; private readonly IAzureStorageClientFactory _storageClientFactory; private readonly ILogger<SimpleTablePurger> _logger; private readonly IPartitionKeyHandler _partitionKeyHandler; public SimpleTablePurger(IAzureStorageClientFactory storageClientFactory, IPartitionKeyHandler partitionKeyHandler, ILogger<SimpleTablePurger> logger) { _storageClientFactory = storageClientFactory; _partitionKeyHandler = partitionKeyHandler; _logger = logger; ServicePointManager.DefaultConnectionLimit = ConnectionLimit; } public async Task<Tuple<int, int>> PurgeEntitiesAsync(PurgeEntitiesOptions options, CancellationToken cancellationToken) { var sw = new Stopwatch(); sw.Start(); _logger.LogInformation($"Starting PurgeEntitiesAsync"); var tableClient = _storageClientFactory.GetCloudTableClient(options.TargetAccountConnectionString); var table = tableClient.GetTableReference(options.TargetTableName); _logger.LogInformation($"TargetAccount={tableClient.StorageUri.PrimaryUri}, Table={table.Name}, PurgeRecordsOlderThanDays={options.PurgeRecordsOlderThanDays}"); var query = _partitionKeyHandler.GetTableQuery(options.PurgeRecordsOlderThanDays); var continuationToken = new TableContinuationToken(); int numPagesProcessed = 0; int numEntitiesDeleted = 0; do { var page = await table.ExecuteQuerySegmentedAsync(query, continuationToken, cancellationToken); var pageNumber = numPagesProcessed + 1; if (page.Results.Count == 0) { if (numPagesProcessed == 0) { _logger.LogDebug($"No entities were available for purging"); } break; } var firstResultTimestamp = _partitionKeyHandler.ConvertPartitionKeyToDateTime(page.Results.First().PartitionKey); _logger.LogInformation($"Page {pageNumber}: processing {page.Count()} results starting at timestamp {firstResultTimestamp}"); var partitionsFromPage = GetPartitionsFromPage(page.Results); _logger.LogDebug($"Page {pageNumber}: number of partitions grouped by PartitionKey: {partitionsFromPage.Count}"); var tasks = new List<Task<int>>(); foreach (var partition in partitionsFromPage) { cancellationToken.ThrowIfCancellationRequested(); var chunkedPartition = partition.Chunk(MaxBatchSize).ToList(); foreach (var batch in chunkedPartition) { cancellationToken.ThrowIfCancellationRequested(); // Implementation 1: one at a time //var recordsDeleted = await DeleteRecordsAsync(table, batch.ToList()); //numEntitiesDeleted += recordsDeleted; // Implementation 2: all deletes asynchronously tasks.Add(DeleteRecordsAsync(table, batch.ToList())); } } // Implementation 2: all deletes asynchronously // Wait for and consolidate results await Task.WhenAll(tasks); var numEntitiesDeletedInThisPage = tasks.Sum(t => t.Result); numEntitiesDeleted += numEntitiesDeletedInThisPage; _logger.LogDebug($"Page {pageNumber}: processing complete, {numEntitiesDeletedInThisPage} entities deleted"); continuationToken = page.ContinuationToken; numPagesProcessed++; } while (continuationToken != null); var entitiesPerSecond = numEntitiesDeleted > 0 ? (int)(numEntitiesDeleted / sw.Elapsed.TotalSeconds) : 0; var msPerEntity = numEntitiesDeleted > 0 ? (int)(sw.Elapsed.TotalMilliseconds / numEntitiesDeleted) : 0; _logger.LogInformation($"Finished PurgeEntitiesAsync, processed {numPagesProcessed} pages and deleted {numEntitiesDeleted} entities in {sw.Elapsed} ({entitiesPerSecond} entities per second, or {msPerEntity} ms per entity)"); return new Tuple<int, int>(numPagesProcessed, numEntitiesDeleted); } /// <summary> /// Executes a batch delete /// </summary> private async Task<int> DeleteRecordsAsync(CloudTable table, IList<DynamicTableEntity> batch) { if (batch.Count > MaxBatchSize) { throw new ArgumentException($"Batch size of {batch.Count} is larger than the maximum allowed size of {MaxBatchSize}"); } var partitionKey = batch.First().PartitionKey; if (batch.Any(entity => entity.PartitionKey != partitionKey)) { throw new ArgumentException($"Not all entities in the batch contain the same partitionKey"); } _logger.LogTrace($"Deleting {batch.Count} rows from partitionKey={partitionKey}"); var batchOperation = new TableBatchOperation(); foreach (var entity in batch) { batchOperation.Delete(entity); } try { await table.ExecuteBatchAsync(batchOperation); return batch.Count; } catch (StorageException ex) { if (ex.RequestInformation.HttpStatusCode == 404 && ex.RequestInformation.ExtendedErrorInformation.ErrorCode == "ResourceNotFound") { _logger.LogWarning($"Failed to delete rows from partitionKey={partitionKey}. Data has already been deleted, ex.Message={ex.Message}, HttpStatusCode={ex.RequestInformation.HttpStatusCode}, ErrorCode={ex.RequestInformation.ExtendedErrorInformation.ErrorCode}, ErrorMessage={ex.RequestInformation.ExtendedErrorInformation.ErrorMessage}"); return 0; } _logger.LogError($"Failed to delete rows from partitionKey={partitionKey}. Unknown error. ex.Message={ex.Message}, HttpStatusCode={ex.RequestInformation.HttpStatusCode}, ErrorCode={ex.RequestInformation.ExtendedErrorInformation.ErrorCode}, ErrorMessage={ex.RequestInformation.ExtendedErrorInformation.ErrorMessage}"); throw; } } /// <summary> /// Breaks up a result page into partitions grouped by PartitionKey /// </summary> private IList<IList<DynamicTableEntity>> GetPartitionsFromPage(IList<DynamicTableEntity> page) { var result = new List<IList<DynamicTableEntity>>(); var groupByResult = page.GroupBy(x => x.PartitionKey); foreach (var partition in groupByResult.ToList()) { var partitionAsList = partition.ToList(); result.Add(partitionAsList); } return result; } } }<file_sep>using System.Collections.Concurrent; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.Logging; namespace AzureTablePurger.Services { /// <summary> /// Used to create clients for Azure Storage accounts. A single instance of a specific client is created and cached. /// </summary> public class AzureStorageClientFactory : IAzureStorageClientFactory { private static readonly ConcurrentDictionary<string, CloudTableClient> CloudTableClientCache = new ConcurrentDictionary<string, CloudTableClient>(); private readonly ILogger<AzureStorageClientFactory> _logger; public AzureStorageClientFactory(ILogger<AzureStorageClientFactory> logger) { _logger = logger; } public CloudTableClient GetCloudTableClient(string connectionString) { if (CloudTableClientCache.ContainsKey(connectionString)) { return CloudTableClientCache[connectionString]; } _logger.LogDebug("CloudTableClient not found in cache. Creating new one and adding to cache"); var account = CloudStorageAccount.Parse(connectionString); var newTableClient = account.CreateCloudTableClient(); bool resultOfAdd = CloudTableClientCache.TryAdd(connectionString, newTableClient); if (!resultOfAdd) { _logger.LogDebug("Adding CloudTableClient to cache failed. Another thread must have beat us to it. Obtaining and returning the one in cache"); return CloudTableClientCache[connectionString]; } return newTableClient; } } } <file_sep>using Microsoft.Azure.Cosmos.Table; namespace AzureTablePurger.Services { public interface IAzureStorageClientFactory { CloudTableClient GetCloudTableClient(string connectionString); } }<file_sep>using System.Collections.Generic; using System.Linq; namespace AzureTablePurger.Common.Extensions { public static class EnumerableExtensions { public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> listOfItems, int chunkSize) { while (listOfItems.Any()) { yield return listOfItems.Take(chunkSize); listOfItems = listOfItems.Skip(chunkSize); } } } } <file_sep>using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using AzureTablePurger.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; namespace AzureTablePurger.App { class Program { private const string ConfigKeyTargetStorageAccountConnectionString = "TargetStorageAccountConnectionString"; private const string ConfigKeyTargetTableName = "TargetTableName"; private const string ConfigKeyPurgeRecordsOlderThanDays = "PurgeRecordsOlderThanDays"; private static ServiceProvider _serviceProvider; private static IConfigurationRoot _config; static async Task Main(string[] args) { BuildConfig(args); var serviceCollection = RegisterServices(); ConfigureLogging(serviceCollection); _serviceProvider = serviceCollection.BuildServiceProvider(); await using (_serviceProvider) { var logger = _serviceProvider.GetService<ILogger<Program>>(); logger.LogInformation("Starting..."); var tablePurger = _serviceProvider.GetService<ITablePurger>(); var options = new PurgeEntitiesOptions { TargetAccountConnectionString = _config[ConfigKeyTargetStorageAccountConnectionString], TargetTableName = _config[ConfigKeyTargetTableName], PurgeRecordsOlderThanDays = int.Parse(_config[ConfigKeyPurgeRecordsOlderThanDays]) }; var cts = new CancellationTokenSource(); await tablePurger.PurgeEntitiesAsync(options, cts.Token); logger.LogInformation($"Finished"); } } private static void BuildConfig(string[] commandLineArgs) { var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddUserSecrets<Program>(); // Command line config var switchMapping = new Dictionary<string, string> { { "-account", ConfigKeyTargetStorageAccountConnectionString }, { "-table", ConfigKeyTargetTableName }, { "-days", ConfigKeyPurgeRecordsOlderThanDays } }; configBuilder.AddCommandLine(commandLineArgs, switchMapping); _config = configBuilder.Build(); } private static ServiceCollection RegisterServices() { var serviceCollection = new ServiceCollection(); // Core logic serviceCollection.AddScoped<ITablePurger, SimpleTablePurger>(); serviceCollection.AddScoped<IAzureStorageClientFactory, AzureStorageClientFactory>(); serviceCollection.AddScoped<IPartitionKeyHandler, TicksAscendingWithLeadingZeroPartitionKeyHandler>(); return serviceCollection; } private static void ConfigureLogging(ServiceCollection serviceCollection) { serviceCollection.AddLogging(configure => configure.AddSimpleConsole(options => { options.SingleLine = true; options.ColorBehavior = LoggerColorBehavior.Default; options.IncludeScopes = false; options.TimestampFormat = "[yyyy-MM-dd HH:mm:ss:fffff tt] "; })) .Configure<LoggerFilterOptions>(options => options.MinLevel = LogLevel.Debug); } } }<file_sep>using System; using Microsoft.Azure.Cosmos.Table; namespace AzureTablePurger.Services { public interface IPartitionKeyHandler { TableQuery GetTableQuery(int purgeEntitiesOlderThanDays); DateTime ConvertPartitionKeyToDateTime(string partitionKey); string GetPartitionKeyForDate(DateTime date); TableQuery GetTableQuery(string lowerBoundPartitionKey, string upperBoundPartitionKey); } } <file_sep>using System; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.Logging; namespace AzureTablePurger.Services { public class TicksAscendingWithLeadingZeroPartitionKeyHandler : IPartitionKeyHandler { private readonly ILogger<TicksAscendingWithLeadingZeroPartitionKeyHandler> _logger; public TicksAscendingWithLeadingZeroPartitionKeyHandler(ILogger<TicksAscendingWithLeadingZeroPartitionKeyHandler> logger) { _logger = logger; } public TableQuery GetTableQuery(int purgeEntitiesOlderThanDays) { var maximumPartitionKeyToDelete = GetMaximumPartitionKeyToDelete(purgeEntitiesOlderThanDays); return GetTableQuery(null, maximumPartitionKeyToDelete); } public TableQuery GetTableQuery(string lowerBoundPartitionKey, string upperBoundPartitionKey) { if (string.IsNullOrEmpty(lowerBoundPartitionKey)) { lowerBoundPartitionKey = "0"; } var lowerBoundDateTime = ConvertPartitionKeyToDateTime(lowerBoundPartitionKey); var upperBoundDateTime = ConvertPartitionKeyToDateTime(upperBoundPartitionKey); _logger.LogDebug($"Generating table query: lowerBound partitionKey={lowerBoundPartitionKey} ({lowerBoundDateTime}), upperBound partitionKey={upperBoundPartitionKey} ({upperBoundDateTime})"); var lowerBound = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThanOrEqual, lowerBoundPartitionKey); var upperBound = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.LessThan, upperBoundPartitionKey); var combinedFilter = TableQuery.CombineFilters(lowerBound, TableOperators.And, upperBound); var query = new TableQuery() .Where(combinedFilter) .Select(new[] { "PartitionKey", "RowKey" }); return query; } public DateTime ConvertPartitionKeyToDateTime(string partitionKey) { var result = long.TryParse(partitionKey, out long ticks); if (!result) { throw new ArgumentException($"PartitionKey is not in the expected format: {partitionKey}", nameof(partitionKey)); } return new DateTime(ticks); } public string GetPartitionKeyForDate(DateTime date) { return date.Ticks.ToString("D19"); } private string GetMaximumPartitionKeyToDelete(int purgeRecordsOlderThanDays) { return GetPartitionKeyForDate(DateTime.UtcNow.AddDays(-1 * purgeRecordsOlderThanDays)); } } }<file_sep>namespace AzureTablePurger.Services { public class PurgeEntitiesOptions { public string TargetAccountConnectionString { get; set; } public string TargetTableName { get; set; } public int PurgeRecordsOlderThanDays { get; set; } } }<file_sep>using System; using System.Threading; using System.Threading.Tasks; namespace AzureTablePurger.Services { public interface ITablePurger { Task<Tuple<int, int>> PurgeEntitiesAsync(PurgeEntitiesOptions options, CancellationToken cancellationToken); } }
afbab3df6482c9e9f733ad62e14a2facbde80dd9
[ "Markdown", "C#" ]
11
Markdown
JohanPlate/AzureTablePurger
0e7c7f6c527e23a8b22ccdbe3a1385ded4161454
c4911acf583479c9084b49b9b92d21493dcad17e
refs/heads/main
<file_sep>const fs = require("fs"); const matchers = { "phpunit-failure": { regexp: "##teamcity\\[testFailed.+message='(.+)'.+details='(?:\\s|\\|n\\s)*(?:.+\\|n[^'])?{{GITHUB_WORKSPACE}}/([^:]+):(\\d+)[^']+'", defaultSeverity: "error", message: 1, file: 2, line: 3, }, }; function run() { const workspaceRoot = process.env.INPUT_BASE_PATH || process.env.GITHUB_WORKSPACE || ""; const matchers = { "phpunit-failure": { regexp: "##teamcity\\[testFailed.+message='(.+)'.+details='(?:\\s|\\|n\\s)*(?:.+\\|n[^'])?{{GITHUB_WORKSPACE}}/([^:]+):(\\d+)[^']+'", defaultSeverity: "error", message: 1, file: 2, line: 3, }, }; for (let matcher in matchers) { const details = matchers[matcher]; const problemMatcher = { problemMatcher: [ { owner: matcher, severity: details.defaultSeverity, pattern: [ { regexp: details.regexp.replace( "{{GITHUB_WORKSPACE}}", workspaceRoot ), message: details.message, file: details.file, line: details.line, }, ], }, ], }; if (!fs.existsSync(".github")) { fs.mkdirSync(".github"); } fs.writeFileSync(`.github/${matcher}.json`, JSON.stringify(problemMatcher)); console.log(`::add-matcher::.github/${matcher}.json`); } } if (require.main === module) { run(); } module.exports = { matchers, run, }; <file_sep># phpunit-matcher-action This action uses the built in PHPUnit `--teamcity` formatter to add annotations to your Github Actions builds. ![PHPUnit Action Matcher Logs Example](https://raw.githubusercontent.com/mheap/phpunit-matcher-action/main/phpunit-matcher-logs.png) ![PHPUnit Action Matcher Context Example](https://raw.githubusercontent.com/mheap/phpunit-matcher-action/main/phpunit-matcher-context.png) ## Usage To configure these matchers, add the following step to your workflow YAML file before running PHPUnit with the `--teamcity` flag. ```yaml - name: Configure matchers uses: mheap/phpunit-matcher-action@v1 ``` Here's a complete workflow example (located at `.github/workflows/phpunit.yml`) that runs your tests and adds annotations for failures ```yaml name: PHPUnit on: [pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Composer dependencies run: composer install --no-ansi --no-interaction --no-scripts --no-suggest --no-progress --prefer-dist - name: Configure matchers uses: mheap/phpunit-matcher-action@v1 - name: Run Tests run: ./vendor/bin/phpunit --teamcity test ``` If you run your tests in a container and the Teamcity output will have a different base path, you can specify it using the `base_path` input: ```yaml - name: Configure matchers uses: mheap/phpunit-matcher-action@v1 with: base_path: /path/to/other/folder ``` ## How this works [Problem matchers](https://github.com/actions/toolkit/blob/master/docs/problem-matchers.md) work by defining a regular expression to extract information such as the file, line number and severity from any output logs. Each matcher has to be registered with Github Actions by adding `::add-matcher::/path/to/matcher.json` to the output. This action generates regular expressions based on the Github workspace, writes out matcher files and then registers them with the Action runner. It uses the Teamcity output as it contains all of the required information (file path, failure message and line number).
370597d6663414195dafe8a1d7790cee5f7cebec
[ "JavaScript", "Markdown" ]
2
JavaScript
mheap/phpunit-matcher-action
88a67fde4efa72b81e43c8e444deb3f146e687f8
a7ede2e68cae1b8def3e6bc6fa643e6e58c8fa32
refs/heads/master
<repo_name>padrededios/cours_python<file_sep>/learn_python3/tuto_tkinter.py from tkinter import * from random import randrange # definition des fonctions gestionnaires d'evenements def drawline(): """ Trace d'une ligne dans le canvas """ print("trace d'une nouvelle ligne") global x1, y1, x2, y2, couleur can1.create_oval(x1, y1, x2, y2, width=2, fill=couleur) # modification des coordonnées pour la ligne suivante y2, y1 = y2+10, y1-10 def drawline2(): """ Trace un viseur """ can1.create_line(200, 325, 300, 325, width=2, fill='red') can1.create_line(250, 275, 250, 375, width=2, fill='red') def changecolor(): """ Changement aleatoire de la couleur du trace """ global couleur pal = ['purple', 'cyan', 'maroon', 'green', 'blue', 'orange', 'yellow'] c = randrange(len(pal)) couleur = pal[c] print("la nouvelle couleur est:", couleur) # Programme principal """ variable globale """ x1, y1, x2, y2 = 0, 650, 500, 0 couleur = 'dark green' # Creation widget principal fen1 = Tk() # Creation du widget esclave can1 = Canvas(fen1, bg='dark grey', height=650, width=500) can1.pack(side=LEFT) bout1 = Button(fen1, text='Quitter', command=fen1.quit) bout1.pack(side=BOTTOM) bout2 = Button(fen1, text='Tracer une ligne', command=drawline) bout2.pack() bout3 = Button(fen1, text='Autre couleur', command=changecolor) bout3.pack() bout4 = Button(fen1, text='Viseur', command=drawline2) bout4.pack() # demarrage du receptionnaire d'evenement fen1.mainloop() # fermeture de la fenetre fen1.destroy() <file_sep>/README.md # tutorials about python
dfffe5be669ca71c6ffac9f4cc828d760e0d611c
[ "Markdown", "Python" ]
2
Python
padrededios/cours_python
24f4431013b0750fb3e75593429b4e8dfe8020c3
276bb382b1f84d0decac772c91effa0ab9821a40
refs/heads/master
<file_sep>package com.capgemini.bus_booking.services; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utilities { public static boolean emailValidator(String email) { //*********************email validation**************************** if (email != "" && email != null) { final Pattern EMAIL_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); Matcher matcher = EMAIL_REGEX.matcher(email); return matcher.find(); } else { System.out.println("Email id is mandatory"); return false; } } public static boolean nameValidator(String name) { //*********************name validation**************************** if(name!="" && name != null) { Pattern p =Pattern.compile("[A-Z]{0}[a-z]{1-10}"); Matcher m =p.matcher(name); return m.find(); } else { System.out.println("Enter ur name"); return false; } } public static boolean contact_noValidator(String contact_no) { //*********************contact validation**************************** if (contact_no !="" && contact_no!= null) { Pattern p = Pattern.compile("[789]{1}[0-9]{1-9}"); Matcher m = p.matcher(contact_no); return m.find(); } else { System.out.println("Contact no is mandatory"); return false; } } public static boolean passwordValidator(String password) { //*********************password validation**************************** if (password !="" && password!= null) { Pattern p = Pattern.compile("\"((?=.*\\\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})\";\r\n" + ""); Matcher m = p.matcher(password); return m.find(); } else { System.out.println("Enter a strong password"); return false; } } }<file_sep>package com.capgemini.bus_booking; import static org.junit.Assert.*; import org.junit.Test; import com.capgemini.bus_booking.bean.Admin; import com.capgemini.bus_booking.dao.AdminDaoImpl; public class AdminDaoImplTest { @Test public void test1(){ AdminDaoImpl helper = new AdminDaoImpl(); Admin actual = helper.findByUsername("Pushkar"); String expected ="Pushkar"; //assertEquals("Pushkar","Pushkar"); } @Test public void test2() { AdminDaoImpl helper = new AdminDaoImpl(); Admin actual = helper.findByUsername("Rathore"); String expected ="Rathore"; // assertEquals("Rathore","Rathore"); } @Test public void test3() { AdminDaoImpl helper = new AdminDaoImpl(); Admin actual = helper.findByUsername("Yash"); String expected ="Pushkar"; assertEquals("Pushkar","Ammu"); } @Test public void test4() { AdminDaoImpl helper = new AdminDaoImpl(); Admin actual = helper.findByUsername("Dinesh"); String expected ="Ammu"; assertEquals("Ammu","Dinesh"); } } <file_sep>package com.capgemini.bus_booking.services; import java.util.List; import com.capgemini.bus_booking.bean.Bus; import com.capgemini.bus_booking.bean.Reserve; import com.capgemini.bus_booking.bean.Route; public interface AdminServices { public List<Bus> addBus(); public List<Route> addRoute(); public List<Bus> changeTiming(); public void cancelBus(int busId); public void cancelRoute(int routeId); public List<Bus> updateBusTiming(); public List<Route> updateRoute(); public List<Reserve> generateReport(); public List<Integer> checkSeatByBusDate(int bid, String date); } <file_sep>package com.capgemini.bus_booking.ui; import java.util.Scanner; import com.capgemini.bus_booking.services.UserServiceImpl; public class Login { public static void main(String[] args) { Scanner scr = new Scanner(System.in); System.out.println("\t\t\t\t****************************Login Page************************************"); System.out.println("Enter 1 for Admin \nEnter 2 for Customer\nEnter Any number exit out from Page"); int choice = scr.nextInt(); switch (choice) { case 1: System.out.println("Enter UserName"); String userName = scr.next(); System.out.println("Enter Password"); String password = scr.next(); boolean check = new UserServiceImpl().loginAdmin(userName, password); if (check == true) { System.out.println("Welcome to Login Page"); } else { System.out.println("Invalid Creditional"); } break; case 2: System.out.println("Enter UserName"); String custname = scr.next(); System.out.println("Enter Password"); String custpass = scr.next(); boolean checkCust = new UserServiceImpl().loginCustomer(custname, custpass); if (checkCust == true) { System.out.println("Welcome to Login Page"); } else { System.out.println("Invalid Creditional"); } break; default: System.exit(1); break; } } } <file_sep>package com.capgemini.bus_booking.services; import static org.junit.Assert.*; import org.junit.Test; import com.capgemini.bus_booking.bean.Bus; import com.capgemini.bus_booking.bean.Customer; import com.capgemini.bus_booking.bean.Route; import com.capgemini.bus_booking.dao.AdminDaoImpl; import com.capgemini.bus_booking.dao.BusDao; import com.capgemini.bus_booking.dao.BusDaoImpl; import com.capgemini.bus_booking.dao.CustomerDaoImpl; import com.capgemini.bus_booking.dao.RouteDaoImpl; import junit.framework.Assert; public class AdminServicesImplTest { BusDaoImpl asi = new BusDaoImpl(); AdminDaoImpl s = new AdminDaoImpl(); @Test public void cancelBusTest() { int busid = 1; int expected = asi.getLbusList().size()-1; asi.remove(1 ); int actual = asi.getLbusList().size(); assertEquals(expected,actual); } @Test public void cancelBusTest1() { int busid = 2; int expected = asi.getLbusList().size()-1; asi.remove(2); int actual = asi.getLbusList().size(); assertEquals(2,2); } @Test public void cancelRouteTest2() { int routeid = 22; int expected = asi.getLbusid().size()-1; asi.remove(22); int actual = asi.getLbusList().size(); assertEquals(22,22); } @Test public void cancelRouteTest3() { int routeId = 11; int expected = asi.getLbusList().size(); asi.remove(11); int actual = asi.getLbusList().size(); assertEquals(11,11); } } <file_sep>package com.capgemini.bus_booking.services; import com.capgemini.bus_booking.bean.Admin; import com.capgemini.bus_booking.bean.Customer; import com.capgemini.bus_booking.dao.AdminDaoImpl; import com.capgemini.bus_booking.dao.CustomerDaoImpl; public class UserServiceImpl implements UserServices { @Override public boolean loginCustomer(String userName, String password) { boolean check = false; Customer cst = new CustomerDaoImpl().findByUsername(userName); if (cst.getCust_pass().equals(password)) { check = true; } return check; } @Override public boolean loginAdmin(String userName, String password) { boolean check = false; Admin ad = new AdminDaoImpl().findByUsername(userName); if (ad.getAdmin_pass().equals(password)) { check = true; } return check; } @Override public String forgotPassword(int cID) { Customer cst = new CustomerDaoImpl().findById(cID); String str = cst.getCust_pass(); return str; } @Override public void addAdditionalData(String address, String phno, int custId) { Customer cst = new CustomerDaoImpl().findById(custId); cst.setCust_address(address); cst.setCust_phno(phno); } @Override public void changePassword() { } @Override public void signupCustomer(int cust_id, String cust_name, String cust_dob, String cust_email, String cust_address, String cust_phno, String cust_pass) { Customer cst = new Customer(cust_id, cust_name, cust_dob, cust_email, cust_address, cust_phno, cust_pass); new CustomerDaoImpl().addCustomerDao(cst); } @Override public void signupAdmin(int admin_id, String admin_name, String admin_email, String admin_pass) { Admin ad = new Admin(admin_id, admin_name, admin_email, admin_pass); new AdminDaoImpl().addAdminDao(ad); } }
d3c2e7daae669633eaea8f909a0218e3adbbcce2
[ "Java" ]
6
Java
Pushkarsinghrathore/busbookingtest
7d3531618541a7bcb8c08c61cc5ca507da7fa1c6
694d2f8cbc1404644d200a8356e3bc40475407d3
refs/heads/master
<repo_name>wyc7758775/hrFaceGuardRN<file_sep>/src/components/InOutLog.js import React, {Component} from 'react'; import { Platform, StyleSheet, Text, View, AsyncStorage, object, Image, RefreshControl, } from 'react-native'; import {StackNavigator} from 'react-navigation'; import { GET_IN_OUT_LOG_BY_ADDRESS, BASE_URL, GET_USER_PERMISSION_TIME_BY_ADDRESS, UPDATE_PERMISSION_TIME } from '../commons/Api'; import Toast, {DURATION} from 'react-native-easy-toast' import Storage from 'react-native-storage'; import Timeline from 'react-native-timeline-listview'; import TitleBar from './TitleBar'; import PopupDialog, { SlideAnimation, ScaleAnimation, DialogTitle, DialogButton, } from 'react-native-popup-dialog'; import {SelectMultipleButton, SelectMultipleGroupButton} from 'react-native-selectmultiple-button' const slideAnimation = new SlideAnimation({slideFrom: 'bottom'}); const scaleAnimation = new ScaleAnimation(); const ios_blue = '#007AFF' const radioData = ['家人', '亲戚', '保姆', '暂行'] export default class InOutLog extends Component { constructor(props) { super(props); this.onEndReached = this.onEndReached.bind(this); this.renderFooter = this.renderFooter.bind(this); this.onRefresh = this.onRefresh.bind(this); this._renderContent = this._renderContent.bind(this); this.data = []; } state = { days: [true, true, true, true, true, true, true, true], user_id: '', list: [], token: '', isRefreshing: false, waiting: false, dialogShow: false, nick_name: 'tom', role_id: '', role_alias: '', address_id: '', isDateTimePickerVisible: false, isBeginTime: true, beginTime: '点击选择开始时间', endTime: '点击选择结束时间', isShowPeopleDate: false, imageUrl: 'www', radioSelectedData: '亲戚' } // ActionSheetCustom showActionSheet = () => this.actionSheet.show() getActionSheetRef = ref => (this.actionSheet = ref) componentWillMount() { } componentDidMount() { this.loadUserInfo(); } onRefresh() { this.setState({isRefreshing: true}); this.fetchInOutList(); } onEndReached() { if (!this.state.waiting) { this.setState({waiting: true}); this.fetchInOutList(); } } renderFooter() { return <Text>~</Text>; } fetchInOutList = () => { (async () => { try { // TODO 更新 const resC = await fetch(GET_IN_OUT_LOG_BY_ADDRESS + '1' + '/visits', { method: 'GET', headers: { 'Authorization': this.state.token } }); const data = await resC.json(); var logList = data.data; let length = logList.length; if (length == 0) { this.setState({isRefreshing: false}); this.setState({waiting: false}); return; } // 转换json var lists = '['; lists = lists + "{ \"" + "time" + "\":" + "\"" + logList[length - 1].visit_time + "\" , "; lists = lists + "\"" + "title" + "\":" + "\"" + logList[length - 1].nickname + "\" , "; lists = lists + "\"" + "imageUrl" + "\":" + "\"" + BASE_URL + "/" + logList[length - 1].pic + "\","; lists = lists + "\"" + "description" + "\":" + "\"" + logList[length - 1].result + "\","; lists = lists + "\"" + "description" + "\":" + "\"" + logList[length - 1].result + "\","; lists = lists + "\"" + "role_id" + "\":" + "\"" + logList[length - 1].role.id + "\","; lists = lists + "\"" + "address_id" + "\":" + "\"" + logList[length - 1].address.id + "\","; lists = lists + "\"" + "user_id" + "\":" + "\"" + logList[length - 1].user_id + "\","; lists = lists + "\"" + "role_alias" + "\":" + "\"" + logList[length - 1].role.alias + "\""; if (logList[length - 1].result == '通过') { lists = lists + " , \"" + "circleColor" + "\":" + "\"" + "#00BFFF" + "\" , "; lists = lists + "\"" + "lineColor" + "\":" + "\"" + "#00BFFF" + "\""; } else { lists = lists + " , \"" + "circleColor" + "\":" + "\"" + "#FF4500" + "\" , "; lists = lists + "\"" + "lineColor" + "\":" + "\"" + "#FF4500" + "\""; } lists = lists + " }" for (var i = length - 2; i >= 0; i--) { lists = lists + ",{ \"" + "time" + "\":" + "\"" + logList[i].visit_time + "\" , "; lists = lists + "\"" + "title" + "\":" + "\"" + logList[i].nickname + "\" , "; lists = lists + "\"" + "imageUrl" + "\":" + "\"" + BASE_URL + "/" + logList[i].pic + "\" , "; lists = lists + "\"" + "description" + "\":" + "\"" + logList[i].result + "\","; lists = lists + "\"" + "user_id" + "\":" + "\"" + logList[i].user_id + "\","; lists = lists + "\"" + "role_id" + "\":" + "\"" + logList[i].role.id + "\","; lists = lists + "\"" + "address_id" + "\":" + "\"" + logList[i].address.id + "\","; lists = lists + "\"" + "role_alias" + "\":" + "\"" + logList[i].role.alias + "\""; if (logList[i].result == '通过') { lists = lists + ",\"" + "circleColor" + "\":" + "\"" + "#00BFFF" + "\" , "; lists = lists + "\"" + "lineColor" + "\":" + "\"" + "#00BFFF" + "\" "; } else { lists = lists + ",\"" + "circleColor" + "\":" + "\"" + "#FF4500" + "\" , "; lists = lists + "\"" + "lineColor" + "\":" + "\"" + "#FF4500" + "\""; } lists = lists + " }" } lists = lists + "]"; var jlist = JSON.parse(lists); this.setState({isRefreshing: false}); this.setState({waiting: false}); this.setState({list: jlist}); } catch (err) { this.refs.toast.show('获取进出信息失败'); console.log(err); } })(); }; loadUserInfo() { this.setState({isRefreshing: true}); storage.load({ key: 'user', autoSync: true, syncInBackground: true, syncParams: { extraFetchOptions: { // 各种参数 }, someFlag: true, }, }).then(ret => { this.setState({token: ret.token}); this.fetchInOutList(); }).catch(err => { this.refs.toast.show('获取用户信息失败'); switch (err.name) { case 'NotFoundError': // TODO; break; case 'ExpiredError': // TODO break; } }) } _renderContent(section) { return ( <View> {this._showTimeBetween()} </View> ); } renderDetail(rowData, sectionID, rowID) { let title = <Text style={[styles.title]}>{rowData.title}</Text> var desc = null if (rowData.description && rowData.imageUrl) desc = ( <View style={styles.descriptionContainer}> <Image source={{uri: rowData.imageUrl}} style={styles.image}/> <Text style={[styles.textDescription]}>{rowData.description}</Text> </View> ) return ( <View style={{flex: 1}}> {title} {desc} </View> ) } showScaleAnimationDialog() { this.scaleAnimationDialog.show(); } clickItem(event) { this.setState({nick_name: event.title}); this.setState({role_id: event.role_id}); this.setState({address_id: event.address_id}); this.setState({imageUrl: event.imageUrl}); this.setState({role_alias: event.role_alias}); this.setState({user_id: event.user_id}); this.showScaleAnimationDialog(); } // 获取当前点击用户的配置信息 getUserTimeInfo(us_id, ad_id) { (async () => { try { var uuri = GET_USER_PERMISSION_TIME_BY_ADDRESS + us_id + "/addresses/" + ad_id; const resC = await fetch(uuri, { method: 'GET', headers: { 'Authorization': this.state.token }, }); const data = await resC.json(); var timeInfo = JSON.parse(data.data.time); this.setState({beginTime: timeInfo.date[0]}); this.setState({endTime: timeInfo.date[1]}); var te = timeInfo.week; var temp = this.state.days; for (var i = 0; i <= 7; i++) { temp[i] = false; } for (var i = 0; i < te.length; i++) { var j = te[i]; temp[j] = true; } this.setState({days: temp}); return true; } catch (err) { console.log(err) this.refs.toast.show('获取信息失败'); } })(); } // 获取 role id getRoleId() { var role = this.state.radioSelectedData; if (role == '家人') { return 6; } else if (role == '亲戚') { return 7; } else if (role == '保姆') { return 8; } else if (role == '暂行') { return 9; } } // 更新权限 toFetchUpdateTime() { var times = '{"date":["2018-03-28","2018-03-30"],"week":[1,2,3,4,5,6,7]}'; let formData = new FormData(); formData.append("role_id", this.getRoleId()); formData.append("time", JSON.stringify(JSON.parse(times))); formData.append("_method", "PATCH"); (async () => { try { var uuri = UPDATE_PERMISSION_TIME + this.state.user_id + "/addresses/1"; const resC = await fetch(uuri, { method: 'PATCH', headers: { 'Authorization': this.state.token, 'Content-Type': 'application/json' }, body: JSON.stringify({ "role_id": this.getRoleId(), "time": JSON.stringify(JSON.parse(times)) }) }); const data = await resC.json(); this.scaleAnimationDialog.dismiss(); return true; } catch (err) { console.log(err) this.refs.toast.show('绑定失败'); } })(); } render() { return ( <View style={styles.cover}> <TitleBar title="进出情况" navigation={this.props.navigation}></TitleBar> <View style={styles.container}> <Timeline style={styles.list} data={this.state.list} circleSize={20} enableEmptySections={true} circleColor='rgba(0,0,0,0)' lineColor='rgb(45,156,219)' timeContainerStyle={{minWidth: 52, marginTop: 0}} timeStyle={{ textAlign: 'center', backgroundColor: '#ff9797', color: 'white', padding: 5, borderRadius: 13 }} descriptionStyle={{color: 'gray'}} options={{ refreshControl: ( <RefreshControl refreshing={this.state.isRefreshing} onRefresh={this.onRefresh} /> ), // renderFooter: this.renderFooter, onEndReached: this.onEndReached }} columnFormat='two-column' renderDetail={this.renderDetail} separator={false} onEventPress={(event) => { this.clickItem(event) }} detailContainerStyle={{ marginBottom: 20, paddingLeft: 5, paddingRight: 5, backgroundColor: "#BBDAFF", borderRadius: 10 }} /> <View> </View> <PopupDialog ref={(popupDialog) => { this.scaleAnimationDialog = popupDialog; }} height={0.5} dialogAnimation={scaleAnimation} dialogTitle={<DialogTitle title="修改人员权限"/>} actions={[ <View style={styles.dia_btn_warpper} key="view-1"> <DialogButton text="绑定" buttonStyle={styles.dia_btn} onPress={() => { this.toFetchUpdateTime(); }} key="button-1" /> <DialogButton text="关闭" buttonStyle={styles.dia_btn} onPress={() => { this.scaleAnimationDialog.dismiss(); }} key="button-2" /> </View> ]} > <View style={{flex: 1}}> <View style={styles.person_warpper}> <Image style={styles.person_img} source={{uri: this.state.imageUrl}}/> </View> {this._tabView()} </View> </PopupDialog> <Toast ref="toast"/> </View> </View> ); } _tabView() { return ( <View> <Text style={{color: ios_blue, marginLeft: 20}}> 当前角色 {this.state.radioSelectedData} </Text> <View style={{flexWrap: 'wrap', flexDirection: 'row', justifyContent: 'center'}}> { radioData.map((gender) => <SelectMultipleButton key={gender} multiple={false} value={gender} displayValue={gender} selected={this.state.radioSelectedData === gender} singleTap={(valueTap) => this._singleTapRadioSelectedButtons(valueTap, gender)}/> ) } </View> </View> ) } _singleTapRadioSelectedButtons(valueTap, gender) { this.setState({ radioSelectedData: gender }) } } const styles = StyleSheet.create({ cover: { flex: 1, backgroundColor: 'white' }, dropdown_6: { flex: 1, backgroundColor: 'gray' }, dropdown_6_image: { width: 40, height: 40, }, person_warpper: { flex: 1, justifyContent: 'center', alignItems: 'center', }, person_img: { // flex: 1, width: 120, height: 100, }, input_warpper: { flexDirection: 'row', }, input_lable: { flex: 1, paddingTop: 10, paddingBottom: 10, fontSize: 20, justifyContent: 'center', textAlign: 'center', }, input_style: { flex: 3, height: 40, borderColor: 'gray', borderWidth: 1, paddingRight: 10, justifyContent: 'center', }, tb_warpper: { flex: 1 }, time_lable: { // flex: 1, paddingTop: 10, paddingBottom: 10, fontSize: 18, justifyContent: 'center', textAlign: 'center', }, dia_btn_warpper: { flexDirection: 'row', }, dia_btn: { flex: 1, flexDirection: 'row', justifyContent: 'center', }, container: { flex: 1, paddingLeft: 20, paddingRight: 20, backgroundColor: 'white' }, list: { flex: 1, marginTop: 10, }, title: { fontSize: 16, fontWeight: 'bold' }, descriptionContainer: { flexDirection: 'row', paddingRight: 50 }, image: { width: 50, height: 50, borderRadius: 25 }, textDescription: { marginLeft: 10, color: 'gray' } });<file_sep>/src/Login.js import React, {Component} from 'react'; import { AppRegistry, StyleSheet, Text, View, TextInput, StatusBar, Image, TouchableWithoutFeedback } from 'react-native'; import MainPage from './MainPage'; import { NavigationActions } from 'react-navigation'; import {Sae} from 'react-native-textinput-effects'; import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'; import {Button} from 'react-native-elements'; import {LOGIN_BY_PASSWORD, GET_USER_BY_ID} from './commons/Api'; import Toast, {DURATION} from 'react-native-easy-toast'; export default class Login extends Component { constructor(props) { super(props); this.loginInMainpage = this.loginInMainpage.bind(this); } static navigationOptions = { header: null }; state = { logining: false, } componentWillMount() { // this.toLoad(); } render() { const {logining} = this.state; return ( <View style={styles.container}> <StatusBar backgroundColor={'#1C86EE'}/> <TouchableWithoutFeedback onPress={() => this.toTakePhoto()}> <View style={styles.img_facewarpper}> <Image source={require('./components/img/face.png')} // source={{uri: 'http://otj6w86xd.bkt.clouddn.com/face.png'}} style={styles.img_face} /> </View> </TouchableWithoutFeedback> <View style={styles.warpper}> <Sae label={'账 号'} iconClass={FontAwesomeIcon} iconName={'pencil'} iconColor={'white'} // TextInput props autoCapitalize={'none'} autoCorrect={false} labelStyle={{color: '#ffffff'}} /> <Sae label={'密 码'} iconClass={FontAwesomeIcon} iconName={'pencil'} iconColor={'white'} // TextInput props autoCapitalize={'none'} autoCorrect={false} labelStyle={{color: '#ffffff'}} secureTextEntry={true} /> <View style={{height: 50}}></View> <Button title='登 录' style={styles.loginBtn} borderRadius={70} fontSize={18} loading={logining} backgroundColor={'#7bbfea'} onPress={() => this.loginInMainpage()}/> </View> <Toast ref="toast"/> </View> ) } toTakePhoto() { this.props.navigation.navigate('TakePhoto'); } gotoMainPage() { resetActions = NavigationActions.reset({ index: 0, actions: [NavigationActions.navigate({routeName: 'MainPage'})] }); this.props.navigation.dispatch(resetActions); } fetchLogin = () => { let formData = new FormData(); formData.append("email", "<EMAIL>"); formData.append("password", "<PASSWORD>"); this.setState({logining: true}); (async () => { try { const resC = await fetch(LOGIN_BY_PASSWORD, { method: 'POST', body: formData }); const data = await resC.json(); storage.save({ key: 'user', // 注意:请不要在key中使用_下划线符号! data: { token: data.token }, expires: 1000 * 3600 }); this.gotoMainPage(); return true; } catch (err) { console.log(err) this.setState({logining: false}); this.refs.toast.show('登录失败 请检查账号密码'); } })(); return false; }; toLoad() { console.log(1); // // 读取 storage.load({ key: 'user', // autoSync(默认为true)意味着在没有找到数据或数据过期时自动调用相应的sync方法 autoSync: true, // syncInBackground(默认为true)意味着如果数据过期, // 在调用sync方法的同时先返回已经过期的数据。 // 设置为false的话,则始终强制返回sync方法提供的最新数据(当然会需要更多等待时间)。 syncInBackground: true, // 你还可以给sync方法传递额外的参数 syncParams: { extraFetchOptions: { // 各种参数 }, someFlag: true, }, }).then(ret => { this.gotoMainPage(); }).catch(err => { console.warn(err.message); switch (err.name) { case 'NotFoundError': // TODO; break; case 'ExpiredError': // TODO break; } }) } /** * 登录进入主页面 */ loginInMainpage() { // this.gotoMainPage(); // 这里开始验证 this.fetchLogin(); } setLoginName(input) { this.setState = {inputName: input} } setLoginPwd(input) { this.setState = {inputPwd: input} } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', backgroundColor: '#1C86EE', }, img_facewarpper: { height: 64, alignItems: 'center', justifyContent: 'center', }, img_face: { height: 64, width: 64 }, warpper: { justifyContent: 'center', padding: 16, flexDirection: 'column', }, item: { flexDirection: 'row', alignItems: 'center', margin: 10 }, textStyle: { fontSize: 18, color: 'black', marginRight: 10 }, loginBtn: { marginTop: 80, }, loginText: { fontSize: 20, alignSelf: 'center', backgroundColor: '#00BFFF' } }) <file_sep>/README.md ## 虹软人脸识别门禁系统 移动端 ### 开发框架 : React-Native ### 项目成绩: * 获2018年浙江省大学生服务外包创新应用大赛一等奖 * 获2018年中国大学生服务外包创新创业大赛大赛三等奖 ### 项目整体框架: ![项目整体框架](public/total.png) ### 移动端概览: <img src="public/login.png" width="50%" height="50%"><img src="public/code.png" width="50%" height="50%"><img src="public/history.png" width="50%" height="50%"><img src="public/manage.png" width="50%" height="50%"><img src="public/add.png" width="50%" height="50%"><img src="public/period.png" width="50%" height="50%"><img src="public/me.png" width="50%" height="50%"><img src="public/qr.png" width="50%" height="50%"> (照片已做打码处理) ### 说明: 1、登录支持账号密码登录与人脸识别登录。 2、可通过门禁提供的验证码来查看来访人员信息与门禁开启授权。 3、进出情况通过时间轴的形式查看来访进历史记录。 4、注册成员管理可以进行查看添加与删除,可设置来访人员允许访问的时间段。 5、可通过右上角的扫描二维码图标来扫描二维码通过门禁(适用于人脸门禁未成功识别的情况)。 6、可通过操作门禁端来发送推送通知到APP,并在APP端查看门禁端的实时内容(与门禁处实时视频流交互)。 ### 框架: * jcore-react-native * jpush-react-native * prop-types * rc-animate * rc-queue-anim * rc-tween-one * react * react-native * react-native-action-button * react-native-actionsheet * react-native-calendar-select * react-native-camera * react-native-collapsible * react-native-confirmation-code-input * react-native-custom-actionsheet * react-native-easy-toast * react-native-elements * react-native-gifted-listview * react-native-gifted-spinner * react-native-image-picker * react-native-loading-spinner-overlay * react-native-material-cards * react-native-modal-datetime-picker * react-native-modal-dropdown * react-native-popup-dialog * react-native-selectmultiple-button * react-native-settings-list * react-native-storage * react-native-swipe-list-view * react-native-syan-image-picker * react-native-tab-navigator * react-native-textinput-effects * react-native-timeline-listview * react-native-vector-icons * react-navigation <file_sep>/src/components/data/WeekData.js /** * 星期选择器数据 */ import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View, AsyncStorage, object, Image, RefreshControl, ActivityIndicator, TouchableWithoutFeedback, Button, TextInput, TouchableOpacity, TouchableNativeFeedback, CheckBox } from 'react-native'; export const weekData = [ '取消', { component: <View style={{flexDirection: 'row', }}> <Text style={{ flex:1 , fontSize:16, textAlign:'center', paddingTop: 5 }}>全选</Text> <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <CheckBox value={true}></CheckBox> </View> </View> , height: 36, }, { component: <View style={{flexDirection: 'row', }}> <Text style={{ flex:1 , fontSize:16, textAlign:'center', paddingTop: 5 }}>星期一</Text> <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <CheckBox ></CheckBox> </View> </View> , height: 36, }, { component: <View style={{flexDirection: 'row', }}> <Text style={{ flex:1 , fontSize:16, textAlign:'center', paddingTop: 5 }}>星期二</Text> <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <CheckBox ></CheckBox> </View> </View> , height: 36, }, { component: <View style={{flexDirection: 'row', }}> <Text style={{ flex:1 , fontSize:16, textAlign:'center', paddingTop: 5 }}>星期三</Text> <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <CheckBox ></CheckBox> </View> </View> , height: 36, }, { component: <View style={{flexDirection: 'row', }}> <Text style={{ flex:1 , fontSize:16, textAlign:'center', paddingTop: 5 }}>星期四</Text> <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <CheckBox ></CheckBox> </View> </View> , height: 36, }, { component: <View style={{flexDirection: 'row', }}> <Text style={{ flex:1 , fontSize:16, textAlign:'center', paddingTop: 5 }}>星期五</Text> <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <CheckBox ></CheckBox> </View> </View> , height: 36, }, { component: <View style={{flexDirection: 'row', }}> <Text style={{ flex:1 , fontSize:16, textAlign:'center', paddingTop: 5 }}>星期六</Text> <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <CheckBox ></CheckBox> </View> </View> , height: 36, }, { component: <View style={{flexDirection: 'row', }}> <Text style={{ flex:1 , fontSize:16, textAlign:'center', paddingTop: 5 }}>星期天</Text> <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <CheckBox ></CheckBox> </View> </View> , height: 36, }, ];<file_sep>/src/components/QrScanView.js import React from 'react'; import {Image, StatusBar, StyleSheet, TouchableOpacity, View} from 'react-native'; import Camera from 'react-native-camera'; import Toast, {DURATION} from 'react-native-easy-toast' import QrScan from './QrScan'; import { StackNavigator, NavigationActions } from 'react-navigation'; import {PASS_BY_QRCODE} from '../commons/Api'; const styles = StyleSheet.create({ container: { flex: 1, }, preview: { flex: 1, justifyContent: 'flex-end', alignItems: 'center' }, overlay: { position: 'absolute', padding: 16, right: 0, left: 0, alignItems: 'center', }, topOverlay: { top: 0, flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }, bottomOverlay: { bottom: 0, backgroundColor: 'rgba(0,0,0,0.4)', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, captureButton: { padding: 15, backgroundColor: 'white', borderRadius: 40, }, typeButton: { padding: 5, }, flashButton: { padding: 5, }, buttonsSpace: { width: 10, }, }); export default class QrScanView extends React.Component { constructor(props) { super(props); this.camera = null; this.state = { camera: { aspect: Camera.constants.Aspect.fill, captureTarget: Camera.constants.CaptureTarget.cameraRoll, type: Camera.constants.Type.back, orientation: Camera.constants.Orientation.auto, flashMode: Camera.constants.FlashMode.auto, }, isRecording: false, token: '' }; } state = { isScan: false } componentDidMount() { this.setState({isScan: false}); } takePicture = () => { if (this.camera) { this.camera .capture() .then(data => console.log('takePicture success')) .catch(err => console.error(err)); } }; startRecording = () => { if (this.camera) { this.camera .capture({mode: Camera.constants.CaptureMode.video}) .then(data => console.log('startRecording success')) .catch(err => console.error(err)); this.setState({ isRecording: true, }); } }; stopRecording = () => { if (this.camera) { this.camera.stopCapture(); this.setState({ isRecording: false, }); } }; switchType = () => { let newType; const {back, front} = Camera.constants.Type; if (this.state.camera.type === back) { newType = front; } else if (this.state.camera.type === front) { newType = back; } this.setState({ camera: { ...this.state.camera, type: newType, }, }); }; get typeIcon() { let icon; const {back, front} = Camera.constants.Type; if (this.state.camera.type === back) { icon = require('./assets/ic_camera_rear_white.png'); } else if (this.state.camera.type === front) { icon = require('./assets/ic_camera_front_white.png'); } return icon; } switchFlash = () => { let newFlashMode; const {auto, on, off} = Camera.constants.FlashMode; if (this.state.camera.flashMode === auto) { newFlashMode = on; } else if (this.state.camera.flashMode === on) { newFlashMode = off; } else if (this.state.camera.flashMode === off) { newFlashMode = auto; } this.setState({ camera: { ...this.state.camera, flashMode: newFlashMode, } }); }; get flashIcon() { let icon; const {auto, on, off} = Camera.constants.FlashMode; if (this.state.camera.flashMode === auto) { icon = require('./assets/ic_flash_auto_white.png'); } else if (this.state.camera.flashMode === on) { icon = require('./assets/ic_flash_on_white.png'); } else if (this.state.camera.flashMode === off) { icon = require('./assets/ic_flash_off_white.png'); } return icon; } onBarCodeRead = (data) => { //将返回的结果转为对象 if (data.type == 'QR_CODE') { if (this.state.isScan) { return; } this.toConfirm(data.data); this.setState({isScan: true}); } } toConfirm(code) { storage.load({ key: 'user', // autoSync(默认为true)意味着在没有找到数据或数据过期时自动调用相应的sync方法 autoSync: true, // syncInBackground(默认为true)意味着如果数据过期, // 在调用sync方法的同时先返回已经过期的数据。 // 设置为false的话,则始终强制返回sync方法提供的最新数据(当然会需要更多等待时间)。 syncInBackground: true, // 你还可以给sync方法传递额外的参数 syncParams: { extraFetchOptions: { // 各种参数 }, someFlag: true, }, }).then(ret => { this.setState({token: ret.token}); this.toFetchCode(code); }).catch(err => { this.refs.toast.show('获取用户信息失败'); console.log('token err' + err.message); switch (err.name) { case 'NotFoundError': // TODO; break; case 'ExpiredError': // TODO break; } }) } toFetchCode(code) { let formData = new FormData(); formData.append("uuid", code); (async () => { try { const resC = await fetch(PASS_BY_QRCODE, { method: 'POST', headers: { 'Authorization': this.state.token }, body: formData }); resetActions = NavigationActions.reset({ index: 0, actions: [NavigationActions.navigate({routeName: 'MainPage'})] }); this.props.navigation.dispatch(resetActions); return true; } catch (err) { console.log(err) this.refs.toast.show('扫码失败'); } })(); } render() { const navigation = this.props.navigation; return ( <View style={styles.container}> <StatusBar animated hidden/> <Camera ref={cam => { this.camera = cam; }} style={styles.preview} aspect={this.state.camera.aspect} captureTarget={this.state.camera.captureTarget} type={this.state.camera.type} flashMode={this.state.camera.flashMode} onFocusChanged={() => { }} onZoomChanged={() => { }} defaultTouchToFocus mirrorImage={false} cropToPreview={false} permissionDialogTitle="相机权限请求" permissionDialogMessage="请打开相机权限" onBarCodeRead={this.onBarCodeRead} // barcodeFinderVisible={true} // barcodeFinderWidth={290} // barcodeFinderHeight={290} // barcodeFinderBorderColor="red" // barcodeFinderBorderWidth={2} > <QrScan cornerBorderLength={40} cornerBorderWidth={4} rectWidth={280} rectHeight={280} scanBarImage={null} cornerColor={'#008B8B'} cornerOffsetSize={0} borderWidth={0} hintText={'我的二维码'} hintTextStyle={{ color: '#fff', fontSize: 16, paddingTop: 8, paddingBottom: 8, paddingLeft: 32, paddingRight: 32, borderRadius: 4, }} hintTextPosition={70} maskColor={'#0000004D'} bottomMenuHeight={80} bottomMenuStyle={{backgroundColor: '#0000004D', height: 80}} onScanResultReceived={this.onBarCodeRead.bind(this)} isShowScanBar={true} ></QrScan> </Camera> <Toast ref="toast"/> </View> ); } }<file_sep>/src/components/TitleBar.js import React, {Component} from 'react'; import { Platform, StyleSheet, Text, View, StatusBar, Image, TouchableNativeFeedback } from 'react-native'; import QrScanView from './QrScanView'; export default class TitleBar extends Component { constructor(props) { super(props); } toQrScan() { this.props.navigation.navigate('QrScanView'); } render() { return ( <View style={styles.container}> <StatusBar backgroundColor={'#1C86EE'}/> <View style={styles.text_warpper}> <Text style={{fontSize: 20, color: '#fff', paddingBottom: 10}}>{this.props.title}</Text> </View> <TouchableNativeFeedback onPress={() => this.toQrScan()}> <View style={styles.qr_warpper}> <Image style={styles.img_style} // source={require('./img/qrscan.png')} source={{uri: 'http://otj6w86xd.bkt.clouddn.com/qrscan.png'}} /> </View> </TouchableNativeFeedback> </View> ); } } const styles = StyleSheet.create({ container: { backgroundColor: '#1C86EE', height: 45, flexDirection: 'row', justifyContent: 'center', }, text_warpper: { justifyContent: 'center' }, qr_warpper: { position: 'absolute', top: 5, right: 15 }, img_style: { width: 25, height: 25, } }) <file_sep>/src/commons/ColorUtil.js /** * 颜色集合 */ export const TAB_COLOR = "#666"; export const TAB_SELECT_COLOR = "#3496f0"; <file_sep>/src/components/ConfirmCode.js import React, {Component} from 'react'; import { Platform, StyleSheet, Text, View, Image, WebView, TouchableOpacity, TouchableWithoutFeedback, TouchableNativeFeedback } from 'react-native'; import {StackNavigator} from 'react-navigation'; import TitleBar from './TitleBar'; import CodeInput from 'react-native-confirmation-code-input'; import {Button} from 'react-native-elements'; import {GET_IMG_BY_CODE, BASE_URL, GATE_CONTROL, CNANGE_STATE} from '../commons/Api'; import PopupDialog, { SlideAnimation, ScaleAnimation, DialogTitle, DialogButton, } from 'react-native-popup-dialog'; import JPushModule from 'jpush-react-native'; const slideAnimation = new SlideAnimation({slideFrom: 'bottom'}); const scaleAnimation = new ScaleAnimation(); export default class ConfirmCode extends Component { constructor(props) { super(props); navigation = this.props.navigation; } state = { imgurl: "./img/head.jpg", dialogShow: false, pushMsg: '' } // // example componentDidMount() { JPushModule.notifyJSDidLoad((resultCode) => { // do something console.log("receive notifyJSDidLoad: " + resultCode); }); JPushModule.addReceiveCustomMsgListener((message) => { this.setState({pushMsg: message}); }); JPushModule.addReceiveNotificationListener((message) => { console.log("receive notification: " + message); this.showWebViewDialog.show(); }) } componentWillUnmount() { JPushModule.removeReceiveCustomMsgListener(); JPushModule.removeReceiveNotificationListener(); } permit() { console.log('permit'); } showScaleAnimationDialog() { this.scaleAnimationDialog.show(); } showWebViewDialog() { this.showWebViewDialog.show(); } checkNumberLegal(isValid) { this.toFetchImg(isValid); } toFetchImg(isValid) { (async () => { try { const resC = await fetch(GET_IMG_BY_CODE + isValid); const data = await resC.json(); if (data.success) { this.setState({imgurl: BASE_URL + "/" + data.data.pic}); this.setState({user_id: data.data.user_id}); } this.scaleAnimationDialog.dismiss(); this.showWebViewDialog.dismiss(); return true; } catch (err) { console.log(err); this.refs.toast.show('图片获取失败失败'); } })(); } toFetchConfirmCode() { let formData = new FormData(); formData.append("type", "open"); formData.append("building_id", "1"); (async () => { try { const resC = await fetch(GATE_CONTROL, { method: 'POST', // headers: { // 'Accept': 'application/json', // 'Content-Type': 'application/json', // }, body: formData }); // const data = await resC.json(); this.scaleAnimationDialog.dismiss(); this.showWebViewDialog.dismiss(); return true; } catch (err) { console.log(err) this.setState({logining: false}); this.refs.toast.show('授权失败'); } })(); } toFetchState() { let formData = new FormData(); formData.append("user_id", this.state.user_id); formData.append("address_id", "1"); (async () => { try { const resC = await fetch(CNANGE_STATE, { method: 'POST', // headers: { // 'Accept': 'application/json', // 'Content-Type': 'application/json', // }, body: formData }); // const data = await resC.json(); this.scaleAnimationDialog.dismiss(); this.showWebViewDialog.dismiss(); return true; } catch (err) { console.log(err) this.setState({logining: false}); this.refs.toast.show('授权失败'); } })(); } render() { return ( <View style={styles.container}> <TitleBar title="验证码" navigation={this.props.navigation}></TitleBar> <View style={{flex: 1, justifyContent:'center'}}> <CodeInput ref="codeInputRef2" keyboardType="numeric" activeColor='rgba(49, 180, 4, 1)' inactiveColor='rgba(49, 180, 4, 0.6)' autoFocus={false} ignoreCase={true} inputPosition='center' codeLength={4} size={50} onFulfill={(isValid) => this.checkNumberLegal(isValid)} containerStyle={{marginTop: 100}} codeInputStyle={{borderWidth: 1.5}} /> </View> <View style={{flex: 1, justifyContent:'center', flexDirection:'row'}}> <TouchableOpacity onPress={() => { this.showScaleAnimationDialog(); }} > <View> <Image style={{height:150, width:150,justifyContent:'center'}} source={{uri: 'http://otj6w86xd.bkt.clouddn.com/%E9%AA%8C%E8%AF%81.png'}} /> <View style={{flexDirection:'row',flex: 1, justifyContent:'center'}}> <Text style={{fontSize:25}}>验 证</Text> </View> </View> </TouchableOpacity> {/* <Button title='暂时授权' style={styles.ConfirmBtn} borderRadius={100} fontSize={18} // loading={logining} onPress={() => { this.showScaleAnimationDialog(); }}/> */} </View> <View style={styles.fakeView}> <TouchableWithoutFeedback style={styles.fakeView} onPress={() => { this.showWebViewDialog.show(); }} > <View style={styles.fakeView}></View> </TouchableWithoutFeedback> </View> <PopupDialog ref={(popupDialog) => { this.scaleAnimationDialog = popupDialog; }} height={0.5} dialogAnimation={scaleAnimation} dialogTitle={<DialogTitle title="查看来访人员信息"/>} actions={[ <View style={styles.dia_btn_warpper} key="view-1"> <DialogButton text="确认" buttonStyle={styles.dia_btn} onPress={() => { this.toFetchConfirmCode(); this.toFetchState(); }} key="button-1" /> <DialogButton text="关闭" buttonStyle={styles.dia_btn} onPress={() => { this.scaleAnimationDialog.dismiss(); }} key="button-2" /> </View> ]} > <View style={styles.person_warpper}> <Image style={styles.person_img} source={{uri: this.state.imgurl}}/> </View> </PopupDialog> <PopupDialog ref={(popupDialog) => { this.showWebViewDialog = popupDialog; }} height={0.8} dialogAnimation={scaleAnimation} dialogTitle={<DialogTitle title='查看视频'/>} actions={[ <View style={styles.dia_btn_warpper} key="view-2"> <DialogButton text="确认" buttonStyle={styles.dia_btn} onPress={() => { this.toFetchConfirmCode(); }} key="button-3" /> <DialogButton text="关闭" buttonStyle={styles.dia_btn} onPress={() => { this.showWebViewDialog.dismiss(); }} key="button-4" /> </View> ]} > <View style={{flex: 1}}> <WebView source={{uri: 'http://192.168.127.12:8082'}} /> </View> </PopupDialog> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#E0F8F1' }, ConfirmBtn: { backgroundColor: '#009C92', width: 60 }, dia_btn_warpper: { flexDirection: 'row', }, dia_btn: { flex: 1, flexDirection: 'row', justifyContent: 'center' }, person_warpper: { flex: 1, justifyContent: 'center', alignItems: 'center', }, person_img: { // flex: 1, width: 100, height: 120, }, fakeView: { backgroundColor: '#E0F8F1', height: 50 } })<file_sep>/src/components/Me.js import React, {Component} from 'react'; import { Platform, StyleSheet, Text, Image, View, TouchableWithoutFeedback } from 'react-native'; import {List, ListItem} from 'react-native-elements'; import TitleBar from './TitleBar'; import SettingsList from 'react-native-settings-list'; const list = [ { name: '<NAME>', avatar_url: './head.jpg', subtitle: 'Vice President' }, { name: '<NAME>', avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg', subtitle: 'Vice Chairman' } ] class Head extends Component { render() { return ( <View style={ProfilePageStyle.container}> {/* <Image source={require('./img/head.jpg')} /> */} <View style={ProfilePageStyle.container_avater}> <Image style={ProfilePageStyle.img_avatar} // source={require('./img/png.png')} source={{uri: 'http://otj6w86xd.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180402161554.png'}} /> <Text onPress={this.props.onNameClick}>业主阿伟</Text> </View> </View> ) } } // class SetList extends Component { render() { var bgColor = '#DCE3F4'; return ( <View style={{backgroundColor:'#f6f6f6', marginTop: 15}}> <View style={{backgroundColor:'#f6f6f6'}}> <SettingsList borderColor='#d6d5d9' defaultItemSize={50}> {/* <SettingsList.Item hasNavArrow={false} title='常用设置' titleStyle={{color:'#009688', fontWeight:'500'}} itemWidth={50} borderHide={'Both'} /> */} <SettingsList.Item icon={ <View style={ProfilePageStyle.imageStyle}> <Image style={{alignSelf:'center',height:24, width:24, marginLeft: 14}} // source={require('./img/ali/黑名单.png')} source={{uri: 'http://otj6w86xd.bkt.clouddn.com/%E9%BB%91%E5%90%8D%E5%8D%95.png'}} /> </View> } hasNavArrow={true} itemWidth={70} titleStyle={{color:'black', fontSize: 16}} title='黑名单' /> <SettingsList.Item icon={ <View style={ProfilePageStyle.imageStyle}> <Image style={{alignSelf:'center',height:24, width:24, marginLeft: 14}} // source={require('./img/ali/邮件.png')} source={{uri: 'http://otj6w86xd.bkt.clouddn.com/%E9%82%AE%E4%BB%B6.png'}} /> </View> } hasNavArrow={true} title='消息' itemWidth={70} titleStyle={{color:'black', fontSize: 16}} hasNavArrow={false} /> <SettingsList.Item icon={ <View style={ProfilePageStyle.imageStyle}> <Image style={{alignSelf:'center',height:24, width:24, marginLeft: 14}} // source={require('./img/ali/设置.png')} source={{uri: 'http://otj6w86xd.bkt.clouddn.com/%E8%AE%BE%E7%BD%AE.png'}} /> </View> } hasNavArrow={true} title='设置' itemWidth={70} titleStyle={{color:'black', fontSize: 16}} hasNavArrow={false} /> </SettingsList> </View> </View> ) } } export default class Me extends Component { static navigationOptions = { // header: null // title: '我' }; render() { var bgColor = '#DCE3F4'; return ( <View> <TitleBar title="我" navigation={this.props.navigation}></TitleBar> <Head></Head> <SetList></SetList> </View> ); } } const ProfilePageStyle = StyleSheet.create({ container: { paddingBottom: 20, borderBottomWidth: 0.5, borderBottomColor: '#B5B5B5', backgroundColor: 'white', }, container_favority_and_reply: { flexDirection: 'row', }, container_favority: { flexDirection: 'row', flex: 1, alignItems: 'center', justifyContent: 'center', borderRightWidth: 0.5, borderRightColor: '#B5B5B5' }, container_reply: { flexDirection: 'row', flex: 1, alignItems: 'center', justifyContent: 'center' }, container_avater: { alignItems: 'center', marginTop: 32, marginBottom: 26, }, header: { backgroundColor: '#333333', height: 240, }, btn_setting: { height: 40, width: 40, }, img_avatar: { borderRadius: 80, height: 120, width: 120, marginBottom: 16, }, tv_favority: { color: '#888888', }, tv_reply: { color: '#888888', }, img_favority: { height: 20, width: 20, resizeMode: 'contain', marginRight: 8, }, img_reply: { height: 20, width: 20, resizeMode: 'contain', marginRight: 8, }, tv_myItem: { height: 80, textAlign: 'center', textAlignVertical: 'center' }, imageStyle:{ marginLeft:15, marginRight:20, alignSelf:'center', width:20, height:24, justifyContent:'center' }, titleInfoStyle:{ fontSize:16, color: '#8e8e93' } })
979e1c21cc3b45e0fcfd77a25149a2fddd285cf0
[ "JavaScript", "Markdown" ]
9
JavaScript
wyc7758775/hrFaceGuardRN
ab3c78af1f06e3ac1798f132e75835ce290b6e70
fbe4a8c509b5829a33ff282858290fb9f698663f
refs/heads/master
<repo_name>Sergey-7/mygeekshop<file_sep>/mainapp/management/commands/fill_db.py from django.core.management.base import BaseCommand from mainapp.models import ProductCategory, Product from authapp.models import ShopUser from basketapp.models import Basket import random import json, os JSON_PATH = 'mainapp/json' def load_from_json(file_name): with open(os.path.join(JSON_PATH, file_name + '.json'), 'r') as infile: return json.load(infile) class Command(BaseCommand): help = 'Fill DB new data' def handle(self, *args, **options): categories = load_from_json('categories') ProductCategory.objects.all().delete() for category in categories: new_category = ProductCategory(**category) new_category.save() products = load_from_json('products') Product.objects.all().delete() for product in products: category_name = product['category'] # Получаем категорию по имени _category = ProductCategory.objects.get(name=category_name) # Заменяем название категории объектом product['category'] = _category new_product = Product(**product) new_product.save() # Создаем суперпользователя при помощи менеджера модели ShopUser.objects.all().delete() django = ShopUser.objects.create_superuser('django', '<EMAIL>', \ 'geekbrains', age=18) user_1 = ShopUser.objects.create_user('user1', '<EMAIL>', \ 'geekbrains', age=22) user_2 = ShopUser.objects.create_user('user2', '<EMAIL>', \ 'geekbrains', age=32) user_3 = ShopUser.objects.create_user('user3', '<EMAIL>', \ 'geekbrains', age=42) products = list(Product.objects.all()) user_products = random.sample(products, 4) for product in user_products: Basket(user=django, product=product, quantity=int(random.random() * 20) + 1).save() user_products = random.sample(products, 3) for product in user_products: Basket(user=user_1, product=product, quantity=int(random.random() * 15) + 1).save() user_products = random.sample(products, 5) for product in user_products: Basket(user=user_2, product=product, quantity=int(random.random() * 10) + 1).save() user_products = random.sample(products, 2) for product in user_products: Basket(user=user_3, product=product, quantity=int(random.random() * 25) + 1).save() <file_sep>/adminapp/urls.py from django.urls import re_path import adminapp.views as adminapp app_name = 'adminapp' urlpatterns = [ # re_path(r'^$', adminapp.main, name='main'), re_path(r'^$', adminapp.UsersListView.as_view(), name='main'), re_path(r'^user/create/$', adminapp.user_create, name='user_create'), re_path(r'^user/update/(?P<pk>\d+)/$', adminapp.user_update, name='user_update'), re_path(r'^user/delete/(?P<pk>\d+)/$', adminapp.user_delete, name='user_delete'), re_path(r'^categories/$', adminapp.categories, name='categories'), # re_path(r'^category/create/$', adminapp.category_create, name='category_create'), re_path(r'^category/create/$', adminapp.ProductCategoryCreateView.as_view(), name='category_create'), # re_path(r'^category/update/(?P<pk>\d+)/$', adminapp.category_update, name='category_update'), re_path(r'^category/update/(?P<pk>\d+)/$', adminapp.ProductCategoryUpdateView.as_view(), name='category_update'), # re_path(r'^category/delete/(?P<pk>\d+)/$', adminapp.category_delete, name='category_delete'), re_path(r'^category/delete/(?P<pk>\d+)/$', adminapp.ProductCategoryDeleteView.as_view(), name='category_delete'), re_path(r'^category/(?P<category_pk>\d+)/products/$', adminapp.category_products, name='category_products'), re_path(r'^category/(?P<category_pk>\d+)/product/create/$', adminapp.product_create, name='product_create'), # re_path(r'^product/read/(?P<pk>\d+)/$', adminapp.product_read, name='product_read'), re_path(r'^product/read/(?P<pk>\d+)/$', adminapp.ProductDetailView.as_view(), name='product_read'), re_path(r'^product/update/(?P<pk>\d+)/$', adminapp.product_update, name='product_update'), re_path(r'^product/delete/(?P<pk>\d+)/$', adminapp.product_delete, name='product_delete'), ] <file_sep>/README.md # mygeekshop Django testing project of online shop ![image](https://user-images.githubusercontent.com/41647618/198526372-9caee66e-a2a6-4868-a80f-6c251526e6e9.png) <file_sep>/adminapp/views.py from django.shortcuts import render, HttpResponseRedirect, get_object_or_404 from django.contrib.auth.decorators import user_passes_test from django.urls import reverse from authapp.models import ShopUser from adminapp.forms import ShopUserCreateForm, ShopUserUpdateForm, \ ProductCategoryUpdateForm, ProductEditForm from mainapp.models import ProductCategory, Product from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.detail import DetailView from django.urls import reverse_lazy from django.utils.decorators import method_decorator # @user_passes_test(lambda user: user.is_superuser) # def main(request): # title = 'админка/пользователи' # # users_list = ShopUser.objects.all().order_by('-is_active', '-is_superuser', '-is_staff', \ # 'username') # # context = { # 'title': title, # 'objects': users_list # } # # return render(request, 'adminapp/users.html', context) class UsersListView(ListView): model = ShopUser template_name = 'adminapp/users.html' @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) # def get_queryset(self): # pass def user_create(request): title = 'новый пользователь' if request.method == 'POST': form = ShopUserCreateForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('adminapp:main')) else: form = ShopUserCreateForm() context = { 'title': title, 'form': form } return render(request, 'adminapp/user_update.html', context) def user_update(request, pk): title = 'редактирование пользователя' updated_user = get_object_or_404(ShopUser, pk=int(pk)) if request.method == 'POST': form = ShopUserUpdateForm(request.POST, request.FILES, instance=updated_user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('adminapp:main')) else: form = ShopUserUpdateForm(instance=updated_user) context = { 'title': title, 'form': form } return render(request, 'adminapp/user_update.html', context) def user_delete(request, pk): title = 'удаление пользователя' updated_user = get_object_or_404(ShopUser, pk=int(pk)) if request.method == 'POST': updated_user.is_active = False updated_user.save() return HttpResponseRedirect(reverse('adminapp:main')) else: context = { 'title': title, 'user_to_delete': updated_user, } return render(request, 'adminapp/user_delete.html', context) def categories(request): title = 'админка/категории' objects_list = ProductCategory.objects.all().order_by('-is_active', 'name') context = { 'title': title, 'objects': objects_list } return render(request, 'adminapp/categories.html', context) # def category_create(request): # title = 'новая категория' # # if request.method == 'POST': # form = ProductCategoryUpdateForm(request.POST, request.FILES) # if form.is_valid(): # form.save() # return HttpResponseRedirect(reverse('adminapp:categories')) # else: # form = ProductCategoryUpdateForm() # # context = { # 'title': title, # 'form': form # } # # return render(request, 'adminapp/category_update.html', context) class ProductCategoryCreateView(CreateView): model = ProductCategory template_name = 'adminapp/category_update.html' success_url = reverse_lazy('admin:categories') fields = ('__all__') # def category_update(request, pk): # title = 'редактирование категории' # updated_category = get_object_or_404(ProductCategory, pk=int(pk)) # # if request.method == 'POST': # form = ProductCategoryUpdateForm(request.POST, request.FILES, \ # instance=updated_category) # if form.is_valid(): # form.save() # return HttpResponseRedirect(reverse('adminapp:categories')) # else: # form = ProductCategoryUpdateForm(instance=updated_category) # # context = { # 'title': title, # 'form': form # } # # return render(request, 'adminapp/category_update.html', context) class ProductCategoryUpdateView(UpdateView): model = ProductCategory template_name = 'adminapp/category_update.html' success_url = reverse_lazy('admin:categories') fields = ('__all__') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'категории/редактирование' # print(context['form']) return context # def category_delete(request, pk): # title = 'удаление категории' # updated_object = get_object_or_404(ProductCategory, pk=int(pk)) # if request.method == 'POST': # updated_object.is_active = False # updated_object.save() # return HttpResponseRedirect(reverse('adminapp:categories')) # else: # context = { # 'title': title, # 'object': updated_object, # } # # return render(request, 'adminapp/object_delete.html', context) class ProductCategoryDeleteView(DeleteView): model = ProductCategory template_name = 'adminapp/object_delete.html' success_url = reverse_lazy('admin:categories') def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.is_active = False self.object.save() return HttpResponseRedirect(self.get_success_url()) def category_products(request, category_pk): category = get_object_or_404(ProductCategory, pk=int(category_pk)) title = f'продукты категории {category.name}' # products = category.product_set.all() products = Product.objects.filter(category=category) context = { 'title': title, 'category': category, 'objects': products, } return render(request, 'adminapp/products.html', context) def product_create(request, category_pk): title = 'продукт/создание' category = get_object_or_404(ProductCategory, pk=int(category_pk)) if request.method == 'POST': product_form = ProductEditForm(request.POST, request.FILES) if product_form.is_valid(): product_form.save() return HttpResponseRedirect(reverse('admin:category_products', args=[category_pk])) else: # задаем начальное значение категории в форме product_form = ProductEditForm(initial={'category': category}) # product_form = ProductEditForm() context = { 'title': title, 'form': product_form, 'category': category } return render(request, 'adminapp/product_update.html', context) # def product_read(request, pk): # title = 'продукт/подробнее' # product = get_object_or_404(Product, pk=int(pk)) # context = { # 'title': title, # 'object': product, # } # # return render(request, 'adminapp/product_read.html', context) class ProductDetailView(DetailView): model = Product # template_name = 'adminapp/product_read.html' def product_update(request, pk): title = 'продукт/редактирование' product = get_object_or_404(Product, pk=int(pk)) if request.method == 'POST': product_form = ProductEditForm(request.POST, request.FILES, instance=product) if product_form.is_valid(): product_form.save() return HttpResponseRedirect(reverse('admin:category_products', args=[product.category.pk])) else: product_form = ProductEditForm(instance=product) context = { 'title': title, 'form': product_form, 'category': product.category } return render(request, 'adminapp/product_update.html', context) def product_delete(request, pk): title = 'удаление продукта' object = get_object_or_404(Product, pk=int(pk)) if request.method == 'POST': object.is_active = False object.save() return HttpResponseRedirect(reverse('admin:category_products', args=[object.category.pk])) else: context = { 'title': title, 'object': object, } return render(request, 'adminapp/object_delete.html', context)<file_sep>/mainapp/views.py from django.shortcuts import render, get_object_or_404 import json import random from mainapp.models import ProductCategory, Product from basketapp.models import Basket from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def get_basket(request): if request.user.is_authenticated: return request.user.basket_set.all() def get_hot_product(): products = Product.objects.filter(category__is_active=True, is_active=True) return random.sample(list(products), 1)[0] def get_same_products(hot_product): same_products = Product.objects.filter(category=hot_product.category, is_active=True).\ exclude(pk=hot_product.pk)[:3] return same_products def main(request): context = { 'page_title': 'главная', 'basket': get_basket(request), } return render(request, 'mainapp/index.html', context) def products(request, category_pk=None, page=1): title = 'каталог' categories = ProductCategory.objects.filter(is_active=True) if category_pk: if category_pk == '0': category = { 'name': 'все', 'pk': 0, } products = Product.objects.filter(category__is_active=True, is_active=True).order_by('price') else: category = get_object_or_404(ProductCategory, pk=category_pk) products = Product.objects.filter(category__pk=category_pk, is_active=True).order_by('price') paginator = Paginator(products, 2) try: products_paginator = paginator.page(page) except PageNotAnInteger: products_paginator = paginator.page(1) except EmptyPage: products_paginator = paginator.page(paginator.num_pages) context = { 'title': title, 'categories': categories, 'category': category, 'products': products_paginator, 'basket': get_basket(request), } return render(request, 'mainapp/products_list.html', context) hot_product = get_hot_product() same_products = get_same_products(hot_product) context = { 'page_title': title, 'categories': categories, 'hot_product': hot_product, 'same_products': same_products, 'basket': get_basket(request), } return render(request, 'mainapp/products.html', context) def product(request, pk): product = get_object_or_404(Product, pk=pk) context = { 'product': product, 'categories': ProductCategory.objects.all(), 'category': product.category, 'basket': get_basket(request), } return render(request, 'mainapp/product.html', context) def contact(request): contacts = [ { 'phone': '+7-888-888-8888', 'email': '<EMAIL>', 'address': 'В пределах МКАД', }, { 'phone': '+7-999-999-9999', 'email': '<EMAIL>', 'address': 'В пределах МКАД', }, { 'phone': '+7-111-111-1111', 'email': '<EMAIL>', 'address': 'В пределах МКАД', }, ] context = { 'page_title': 'контакты', 'contacts': contacts, 'basket': get_basket(request), } return render(request, 'mainapp/contact.html', context) <file_sep>/requirements.common.txt django<2.1 psycopg2<2.8 Pillow<4.4.0
743b0a1dc42df947d84fa53b59a5190e6caa2c63
[ "Markdown", "Python", "Text" ]
6
Python
Sergey-7/mygeekshop
eeec8273dcfea8e98929492593f6f95d97c800e0
781f54484433ec0603733fbdf1f544d0f1bf112a
refs/heads/main
<repo_name>Kriannn/testshoter<file_sep>/.env.example SLEEP_TIME=1000 DISCORD_TOKEN=<your-token-here> COMMAND_PREFIX=><file_sep>/README.pl-PL.md # Testshoter Discord Bot [![GitHub stars](https://img.shields.io/github/stars/fhodun/testshoter)](https://github.com/fhodun/testshoter/stargazers) [![GitHub license](https://img.shields.io/github/license/fhodun/testshoter)](https://github.com/fhodun/testshoter/blob/main/LICENSE) [![Twitter](https://img.shields.io/twitter/url?url=https%3A%2F%2Fgithub.com%2Ffhodun%2Ftestshoter)](https://twitter.com/intent/tweet?text=Wow:&url=https%3A%2F%2Fgithub.com%2Ffhodun%2Ftestshoter) ## Przegląd Bot Discord wysyłający treść pytań i odpowiedzi do testów na testportal'u - [Testshoter Discord Bot](#testshoter-discord-bot) - [Ważne](#ważne) - [Komendy](#komendy) - [Wymagania wstępne](#wymagania-wstępne) - [Pobieranie Testshoter'a](#pobieranie-testshoter'a) - [Klonowanie repozytorium](#klonowanie-repozytorium) - [Pobieranie repozytorium](#pobieranie-repozytorium) - [Tworzenie i dodawanie tokena Discord](#tworzenie-i-dodawanie-tokena-discord) - [Zapraszanie bota](#zapraszanie-bota) - [Instalowanie wymaganych pakietów](#instalowanie-wymaganych-pakietów) - [Uruchamianie bota](#uruchamianie-bota) - [Pozdrowienia](#pozdrowienia) - [Licencja i wyłączenie odpowiedzialności](#licencja-i-wyłączenie-odpowiedzialności) ## Ważne Najważniejsze informacje: - bot nie wysyła poprawnych odpowiedzi do testów, a jedynie treść pytań i odpowiedzi - bot nie jest niewidoczny, nauczyciel widzi go jako puste pole w wynikach, ale jeśli nie jest zaznajomiony z technologią, nie zrozumie tego, przykład <https://i.imgur.com/B9fE0gP.png> - jeśli w teście jest otwarte pytanie, na które odpowiedź jest wymagana, bot się zatrzyma ## Komendy - Aby rozpocząć wykonywanie zrzutów ekranu testu ```discord >test (testportal_test_link) ``` przykład: `>test https://www.testportal.pl/exam/LoadTestStart.html?t=565CaL1WT4UZ` - Aby sprawdzić czy bot jest aktualny ```discord >version ``` - Aby wyświetlić pomoc ```discord >help ``` - Aby wyświetlić najważniejsze informacje ```discord >important ``` - Aby wyświetlić najważniejsze informacje po Polsku ```discord >wazne ``` ## Instalacja i uruchamianie Instrukcja w języku angielskim na [stronie wiki](https://github.com/fhodun/testshoter/wiki/Installation-and-starting-up) ### Wymagania wstępne Upewnij się, że zainstalowałeś wszystkie wymagania wstępne: - [Node.js](https://nodejs.org/en/download/). ### Pobieranie Testshoter'a Istnieje kilka sposobów na pobranie Testshotera: #### Klonowanie repozytorium Zalecanym sposobem uzyskania Testshoter jest użycie Git'a do bezpośredniego sklonowania repozytorium: ```sh git clone https://github.com/fhodun/testshoter ``` Spowoduje to sklonowanie najnowszej wersji repozytorium Testshoter do folderu **testshoter**. #### Pobieranie repozytorium Innym sposobem na pobranie Testshotera jest [pobranie kopii zip](https://github.com/fhodun/testshoter/archive/main.zip) z GitHub'a ### Tworzenie i dodawanie tokena Discord Utwórz nową [aplikację](https://discord.com/developers/applications) Discorda i w menu wybierz bota używając [tego](https://i.imgur.com/WKQgdyH.png) przycisku. Skopiuj [Token](https://i.imgur.com/r322GcU.png), otwórz plik `.env.example` i wklej token w miejsce ` <your-token-here> `, następnie zmień nazwę tego pliku na` .env ` i zapisz. ### Zapraszanie bota Aby dodać bota do serwera, przejdź [tutaj](https://discord.com/developers/applications) i wybierz swoją aplikację. W menu wybierz [OAuth2](https://i.imgur.com/TtXF7U2.png), wybierz [bot](https://i.imgur.com/TtXF7U2.png), w tabeli poniżej wybierz `Wyślij wiadomości, Menage Messages, Embed links, Attach Files`, następnie otwórz wygenerowany linku w przeglądarce i wybierz serwer. ### Instalowanie wymaganych pakietów Zainstaluj wymagane pakiety w terminalu: ```sh npm install ``` ### Uruchamianie bota Uruchom bota w terminalu: ```sh npm start ``` ## Pozdrowienia Podziękowania dla [gbaransky](https://github.com/gbaranski) za jego wkład w projekt. Inspiracja i pomysł zaczerpnięte z [arekminajj/testportal-discord-bot](https://github.com/arekminajj/testportal-discord-bot). ## Licencja i wyłączenie odpowiedzialności Wydany na licencji [GNU GPL-3.0](LICENSE). Stworzone w celach edukacyjnych. Autor nie ponosi żadnej odpowiedzialności za jakiekolwiek szkody, które mogą wyniknąć z korzystania z tego oprogramowania. <file_sep>/src/misc.ts import fetch from 'node-fetch'; export const checkNewestVersion = async (): Promise<string> => { const res = await fetch( 'https://api.github.com/repos/fhodun/testshoter/releases/latest', ); const json = await res.json(); const version = json.tag_name; if (!version) throw new Error('Unable to get newest version'); return json.tag_name; }; export interface TestURL { url: URL; testID: string; err?: undefined; } export const validateTestURL = (strURL: string): TestURL | { err: Error } => { let url: URL; try { url = new URL(strURL); const testID = url.searchParams.get('t'); if (!testID) throw new Error('URL does not contain `t` search param'); } catch (err) { return { err, }; } return { url, // assertion here bcs im sure that won't be null testID: url.searchParams.get('t') as string, }; }; <file_sep>/src/testportal/index.ts import { TestURL } from '@/misc'; import puppeteer from 'puppeteer'; // Max answers per test, used to avoid endless loop const ANSWER_LIMIT = 200; const fillForm = (page: puppeteer.Page) => { return page.$$eval('input', (inputs) => inputs.map((input) => { if (!(input instanceof HTMLInputElement)) return; switch (input.type) { case 'email': input.value = 'a@aa.aa'; break; case 'text': if (input.name == 'Nr_w_dzienniku_number' || input.name == 'age') input.value = '0'; else input.value = '‎'; break; case 'radio': input.checked = true; break; } }), ); }; const submitForm = (page: puppeteer.Page) => { return page.$eval('#start-form-submit', (e) => { if (!(e instanceof HTMLElement)) throw new Error('Submit form button is invalid!'); e.click(); }); }; const submitAnswer = (page: puppeteer.Page) => { return page.$eval( '#questionForm > div > div.test_button_box.section > a', (e) => { if (!(e instanceof HTMLElement)) throw new Error('Submit question button is invalid!'); if (!e.onclick) throw new Error('Button does not have onclick property'); e.onclick(new MouseEvent('click')); }, ); }; const isQuestionPage = async (page: puppeteer.Page): Promise<boolean> => { return page.evaluate(() => document.querySelector( '#questionForm > div > div.test_button_box.section > a', ), ); }; interface QuestionScreenshot { image: Buffer; testID: string; question: number; } export async function* getQuestions( testURL: TestURL, ): AsyncGenerator<QuestionScreenshot, void, void> { const browser = await puppeteer.launch({ args: ['--no-sandbox'], }); const page = await browser.newPage(); await page.setDefaultNavigationTimeout(0); await page.goto(testURL.url.href, { waitUntil: 'networkidle0' }); await fillForm(page); await Promise.all([ submitForm(page), page.waitForNavigation({ waitUntil: 'load' }) ]) const questions = await page.$eval('.question_header_content', (el) => el.textContent); if(!questions) throw new Error("There was an error with retrieving questions amount data"); const questionsAmount = parseInt(questions.slice(10)); for (let i = 0; i < questionsAmount; i++) { const totalWidth = await page.evaluate( () => document.documentElement.offsetWidth ); const totalHeight = await page.evaluate( () => document.documentElement.offsetHeight ); await page.setViewport({ width: totalWidth, height: totalHeight, deviceScaleFactor: 1, }); console.log(`Screenshotting question ${i + 1}, TestID: ${testURL.testID}`); const image = await page.screenshot({ encoding: 'binary' }); yield { image, testID: testURL.testID, question: i + 1, }; await Promise.all([ submitAnswer(page), page.waitForNavigation({ waitUntil: 'networkidle2' }) ]) } console.log(`Completed test TestID: ${testURL.testID}`); await browser.close(); } <file_sep>/README.md # Testshoter Discord Bot [![GitHub stars](https://img.shields.io/github/stars/fhodun/testshoter)](https://github.com/fhodun/testshoter/stargazers) [![GitHub license](https://img.shields.io/github/license/fhodun/testshoter)](https://github.com/fhodun/testshoter/blob/main/LICENSE) [![Twitter](https://img.shields.io/twitter/url?url=https%3A%2F%2Fgithub.com%2Ffhodun%2Ftestshoter)](https://twitter.com/intent/tweet?text=Wow:&url=https%3A%2F%2Fgithub.com%2Ffhodun%2Ftestshoter) ## Overview Discord bot that send content of questions and possible answers for tests on testportal.pl - [Important](#important) - [Commands](#commands) - [Installation and starting up](#installation-and-starting-up) - [Greetings](#greetings) - [License and disclaimer](#license-and-disclaimer) ## Important The most important informations the bot: - bot does not send the answers to the tests, only the content of the questions and answers - bot is not invisible, the teacher sees it as an empty field in the results, but if it is not familiar with technology, it won't understand that, example <https://i.imgur.com/B9fE0gP.png> - if there is an open question in the test, the answer to which is required, the bot will stop ## Commands - To testportal screenshoting program start ```discord >test (testportal_test_link) ``` example: `>test https://www.testportal.pl/exam/LoadTestStart.html?t=565CaL1WT4UZ` - To check the bot is up to date ```discord >version ``` - To grant help ```discord >help ``` - To display the most important informations ```discord >important ``` - To display the most important informations in Polish ```discord >wazne ``` ## Installation and starting up Go to the [wiki page](https://github.com/fhodun/testshoter/wiki/Installation-and-starting-up) ## Greetings Thanks to [gbaransky](https://github.com/gbaranski) for his great contribution to the project. Inspiration and idea taken from [arekminajj/testportal-discord-bot](https://github.com/arekminajj/testportal-discord-bot). ## License and disclaimer Released under the [GNU GPL-3.0 license](LICENSE). Created in educational purposes. The author assumes no responsibility for any damages that may result from the use of this software. <file_sep>/src/discord/misc.ts import { Message, MessageEmbed } from 'discord.js'; export const embedMessage = async ( message: Message, title: string, description: string, ): Promise<void> => { const embed = new MessageEmbed() .setTitle(title) .setColor(0xff0000) .setDescription(description); await message.channel.send(embed); }; <file_sep>/src/discord/commands/index.ts import { checkNewestVersion, validateTestURL } from '@/misc'; import { getQuestions } from '@/testportal'; import { embedMessage } from '../misc'; import { Command, CommandHandler } from '../types'; // Duplicated from ../index.ts, maybe fix const commandPrefix = process.env.COMMAND_PREFIX; if (!commandPrefix) throw new Error( "COMMAND_PREFIX is not defined in .env, default value is '>'", ); export const onGetQuestions: CommandHandler = async (cmd) => { const testURL = cmd.args[0]; if (!testURL) throw new Error('Test URL is not defined'); const url = validateTestURL(testURL); if (url.err) { return embedMessage( cmd.msg, 'Wrong URL', `${url.err.message}\nhere an example \`!test (testportal_test_link)\``, ); } for await (const screenshot of getQuestions(url)) { await cmd.msg.channel.send(`We got screenshot of question!`, { files: [screenshot.image], }); } // embedMessage( // message, // 'Screenshotting start', // 'This may take a while, please be patient', // ); // getQuestions(message, test_link); }; export const onImportant: CommandHandler = async (cmd) => { switch (cmd.command) { case 'important': await embedMessage( cmd.msg, 'Important', 'The most important information: \n' + ' - the bot **does not send the answers** to the tests, only the content of the questions and answers\n' + ' - the bot **is not invisible**, the teacher sees it as an empty field in the results, but if it is not familiar with technology, it will not understand that, example https://i.imgur.com/B9fE0gP.png\n' + ' - if there is an **open** question in the test, the answer to which is **required**, the bot will stop\n', ); break; case 'wazne': await embedMessage( cmd.msg, 'Ważne', 'Najważniejsze informacje: \n' + ' - bot **nie wysyła odpowiedzi** do testów, tylko treści pytań i odpowiedzi\n' + ' - bot **nie jest niewidzialny**, nauczyciel widzi go w wynikach jako puste pole lecz jeżeli nie ogarnia to się nie skapnie, przykład https://i.imgur.com/B9fE0gP.png\n' + ' - jeżeli w teście istnieje pytanie **otwarte**, na które odpowiedź jest **wymagana** to bot się zatrzyma\n', ); break; default: throw new Error('Unsupported language'); } }; export const onShowHelp = async (cmd: Command) => { await embedMessage( cmd.msg, 'Testshots commands help', '**Commands: **\n' + ':white_check_mark: `' + `${commandPrefix}` + 'test (testportal_test_link)` testportal test screenshotting start\n' + ':new: `' + `${commandPrefix}` + 'version` check the bot is up to date\n' + ':label: `' + `${commandPrefix}` + 'help` grants help\n' + ':bangbang: `' + `${commandPrefix}` + 'important` displays the most important information\n' + ':flag_pl: `' + `${commandPrefix}` + 'wazne` displays the most important information in Polish\n' + '\n**:busts_in_silhouette: Support server: **\n' + 'https://discord.gg/TWRwsnMzD9 ', ); }; export const onCheckUpdates = async (cmd: Command) => { const version = await checkNewestVersion(); const runningVersion = process.env.npm_package_version; if (version === runningVersion) await embedMessage( cmd.msg, 'Version', ':tada: Your bot has the latest version of the program :tada:', ); else await embedMessage( cmd.msg, 'Version', ':sob: Your bot does not have the latest version of the program :sob:', ); }; <file_sep>/src/index.ts import inquirer from 'inquirer'; import { initDiscordClient } from './discord'; import { TestURL, validateTestURL } from './misc'; import { getQuestions } from './testportal'; const init = async () => { const discordClient = await initDiscordClient(); }; const getTestURLFromUserInput = async (): Promise<TestURL> => { const { testURL } = await inquirer.prompt<{ testURL: string }>([ { type: 'input', name: 'testURL', }, ]); try { const valid = validateTestURL(testURL); if (valid.err) throw valid.err; return valid; } catch (e) { console.log(e.message); return getTestURLFromUserInput(); } }; const initStandalone = async () => { console.log("Starting in standalone mode, discord client won't run"); while (true) { const testURL = await getTestURLFromUserInput(); for await (const question of getQuestions(testURL)) { // console.log(question); } } }; const standaloneMode = process.argv.includes('--standalone') || process.argv.includes('-standalone'); standaloneMode ? initStandalone() : init(); <file_sep>/src/discord/types.ts import { Message } from 'discord.js'; export interface Command { msg: Message; command: string; args: string[]; } export type CommandHandler = (cmd: Command) => Promise<void>; export interface AvailableCommand { handler: CommandHandler; triggers: string[]; } <file_sep>/src/discord/index.ts import { Client } from 'discord.js'; import { onCheckUpdates, onGetQuestions, onImportant, onShowHelp, } from './commands'; import { embedMessage } from './misc'; import { AvailableCommand } from './types'; const commandPrefix = process.env.COMMAND_PREFIX; if (!commandPrefix) throw new Error( "COMMAND_PREFIX is not defined in .env, default value is '>'", ); export const commands: AvailableCommand[] = [ { handler: onGetQuestions, triggers: ['test'], }, { handler: onImportant, triggers: ['important'], }, { handler: onShowHelp, triggers: ['help', 'pomoc'], }, { handler: onCheckUpdates, triggers: ['update'], }, ]; export const initDiscordClient = async () => { const discordToken = process.env.DISCORD_TOKEN; if (!discordToken) throw new Error('Unable to retrieve DISCORD_TOKEN from .env'); const client = new Client(); await client.login(discordToken); client.on('ready', () => { console.log(`Logged in!`); }); client.on('message', async (msg) => { if (!msg.content.startsWith(commandPrefix) || msg.author.bot) return; const args = msg.content.slice(commandPrefix.length).trim().split(/ +/); const command = args.shift()?.toLowerCase(); if (!command) throw new Error('Unable to retrieve command from message'); const targetCommand = commands.find((cmd) => cmd.triggers.includes(command), ); if (!targetCommand) { await embedMessage(msg, 'Wrong command', 'Use `!help` for some help...'); return; } await targetCommand.handler({ msg, command, args, }); }); };
ffeb1e0a1ec5eda5af25a6e52dda071308b5e3ea
[ "Markdown", "TypeScript", "Shell" ]
10
Shell
Kriannn/testshoter
6052f9499d351a5cc47b5ed12df7167b8a04f9ed
f654e38dbd98e93aeb7a74831b04f7058db7af0d
refs/heads/master
<file_sep>#include<iostream> using namespace std; struct node { int num; node *next; }*head,*tail; //add to tail void addToTail() { node * n = new node; cout << "Enter the num for node: "; cin >> n-> num; n -> next = NULL; if(head == NULL) { head = n; tail = n; } else { tail -> next = n; tail = n; } } //add to mid void addToMid() { bool flag = false; node *temp; temp = head; int value; cout << "Enter the value from the node after which you want to add a new node: "; cin >> value; while(temp->num != value) { temp = temp -> next; if(temp == NULL) { flag = true; break; } } if(flag == false) { node *n = new node; cout << "Enter the num for new node: "; cin >> n -> num; n -> next = temp -> next; temp -> next = n; } } void display() { node *temp; temp = head; while(temp != NULL) { cout << temp->num << " " << endl; temp = temp -> next; } } int main() { head = tail = NULL; for(int i=0; i<4; i++) { addToTail(); } display(); addToMid(); display(); } <file_sep>#include<iostream> using namespace std; struct node { int num; node *next; }*head,*tail; //AddToHead void addToHead() { node* n = new node; cout << "Enter the value: "; cin >> n->num; n->next = NULL; if(head == NULL) { head = n; tail = n; } else { n -> next = head; head = n; } } void display() { node* temp; temp = head; while(temp != tail) { cout << temp -> num << " "; temp = temp->next; } } int main() { head = tail = NULL; /*for(int i=0; i<5; i++) { addToHead(); } cout << "Following are the elements: "; cout << endl; display();*/ cout << &head; } <file_sep>#include<iostream> using namespace std; struct node { int num; node *next; }*head, *tail; //add to tail void addToTail() { node * n = new node; cout << "Enter the num for node: "; cin >> n-> num; n -> next = NULL; if(head == NULL) { head = n; tail = n; } else { tail -> next = n; tail = n; } } void display() { node *temp; temp = head; while(temp != tail -> next) { cout << temp -> num << " "; temp = temp -> next; } } int main() { head = tail = NULL; for(int i=0; i<3; i++) { addToTail(); } cout << "Elements are the following: \n"; display(); }
fd392247475a6ad9a220717c82be5ff9e6c7f24b
[ "C++" ]
3
C++
jukha/LinkedListRelatedProgramsC-
16d95be11b8ece70a0f81f90a58971d4d771cda4
b9232a9f31e81e31dc24bea894fe0a6fbcdb7bb4
refs/heads/master
<repo_name>SFWLtd/crm-plus-plus<file_sep>/Civica.CrmPlusPlus.Sdk/Validation/GuardIntExtensions.cs using System; namespace Civica.CrmPlusPlus.Sdk.Validation { internal static class GuardIntExtensions { internal static GuardThis<int> AgainstNegative(this GuardThis<int> guard) { if (guard.Obj < 0) { throw new ArgumentException("Value should not be less than zero"); } return guard; } internal static GuardThis<int> AgainstZero(this GuardThis<int> guard) { if (guard.Obj == 0) { throw new ArgumentException("Value should not be zero"); } return guard; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/PropertyNameAttribute.cs using System; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using Civica.CrmPlusPlus.Sdk.Validation; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class PropertyNameAttribute : Attribute { public string PropertyName { get; } public PropertyNameAttribute(string propertyName) { Guard.This(propertyName).AgainstNullOrEmpty("CrmPlusPlusEntity should not have a null or empty logical name"); PropertyName = propertyName; } internal static string GetFromType<T, TProperty>(Expression<Func<T, TProperty>> propertyExpr) where T : CrmPlusPlusEntity, new() { Guard.This(propertyExpr.Body).AgainstNonMemberExpression(); var propertyInfo = ((MemberExpression)propertyExpr.Body).Member; var propertyNameAttributes = propertyInfo.GetCustomAttributes(true) .Where(attr => attr.GetType() == typeof(PropertyNameAttribute)); if (propertyNameAttributes.Any()) { return ((PropertyNameAttribute)propertyNameAttributes.Single()).PropertyName; } throw new InvalidOperationException(string.Format("Cannot retrieve property name from member '{0}' of type '{1}'. PropertyAttribute not found for this type", propertyInfo.Name, typeof(T).Name)); } internal static string GetFromDescriptor(PropertyDescriptor property) { var propertyNameAttributes = property.Attributes.AsEnumerable() .Where(attr => attr.GetType() == typeof(PropertyNameAttribute)); if (propertyNameAttributes.Any()) { return ((PropertyNameAttribute)propertyNameAttributes.Single()).PropertyName; } throw new InvalidOperationException(string.Format("Cannot retrieve property name from member '{0}' of type '{1}'. PropertyAttribute not found for this type", property.Name, property.PropertyType.Name)); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Client/CrmPlusPlusEntityClient.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Civica.CrmPlusPlus.Sdk.Client.Association; using Civica.CrmPlusPlus.Sdk.Client.Retrieve; using Civica.CrmPlusPlus.Sdk.Client.RetrieveMultiple; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.Querying; using Civica.CrmPlusPlus.Sdk.Validation; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; namespace Civica.CrmPlusPlus.Sdk.Client { public class CrmPlusPlusEntityClient : ICrmPlusPlusEntityClient { private readonly IOrganizationService service; internal CrmPlusPlusEntityClient(IOrganizationService service) { this.service = service; } public void Associate(string relationshipName, Associate association) { Guard.This(relationshipName).AgainstNullOrEmpty(); var relationship = new Relationship(relationshipName); var relatedEntities = new EntityReferenceCollection(); relatedEntities.AddRange(association.RelatedEntities.Select(s => new EntityReference(s.Value, s.Key))); service.Associate(association.EntityName, association.EntityId, relationship, relatedEntities); } public void Disassociate(string relationshipName, Associate association) { Guard.This(relationshipName).AgainstNullOrEmpty(); var relationship = new Relationship(relationshipName); var relatedEntities = new EntityReferenceCollection(); relatedEntities.AddRange(association.RelatedEntities.Select(s => new EntityReference(s.Value, s.Key))); service.Disassociate(association.EntityName, association.EntityId, relationship, relatedEntities); } public Guid Create<T>(T entity) where T : CrmPlusPlusEntity, new() { service.Create(entity.ToCrmEntity()); return entity.Id; } public void Update<T>(T entity) where T: CrmPlusPlusEntity, new() { service.Update(entity.ToCrmEntity()); } public T Retrieve<T>(Retrieval<T> retrieval) where T : CrmPlusPlusEntity, new() { var crmEntity = service.Retrieve(EntityNameAttribute.GetFromType<T>(), retrieval.Id, retrieval.AllColumns ? new ColumnSet(true) : new ColumnSet(retrieval.IncludedColumns.ToArray())); return crmEntity.ToCrmPlusPlusEntity<T>(); } public void Delete<T>(T entity) where T : CrmPlusPlusEntity, new() { service.Delete(EntityNameAttribute.GetFromType<T>(), entity.Id); } public IEnumerable<T> RetrieveMultiple<T>(Query<T> query) where T : CrmPlusPlusEntity, new() { var results = service.RetrieveMultiple(new FetchExpression(query.ToFetchXml())); var parser = new RetrieveMultipleParser<T>(results.Entities); var entities = parser.GetMainEntities(); parser.PopulateOneToManyEntities(entities); parser.PopulateManyToOneEntity(entities); return entities; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/PropertyTypes/StringAttribute.cs using System; using Civica.CrmPlusPlus.Sdk.Validation; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class StringAttribute : Attribute { public int MaxLength { get; } public Microsoft.Xrm.Sdk.Metadata.StringFormatName StringFormat { get; } public StringAttribute(int maxLength, Metadata.StringFormatName stringFormat) { Guard.This(maxLength) .AgainstNegative() .AgainstZero(); MaxLength = maxLength; switch (stringFormat) { case Metadata.StringFormatName.Email: StringFormat = Microsoft.Xrm.Sdk.Metadata.StringFormatName.Email; return; case Metadata.StringFormatName.Phone: StringFormat = Microsoft.Xrm.Sdk.Metadata.StringFormatName.Phone; return; case Metadata.StringFormatName.PhoneticGuide: StringFormat = Microsoft.Xrm.Sdk.Metadata.StringFormatName.PhoneticGuide; return; case Metadata.StringFormatName.Text: StringFormat = Microsoft.Xrm.Sdk.Metadata.StringFormatName.Text; return; case Metadata.StringFormatName.TextArea: StringFormat = Microsoft.Xrm.Sdk.Metadata.StringFormatName.TextArea; return; case Metadata.StringFormatName.TickerSymbol: StringFormat = Microsoft.Xrm.Sdk.Metadata.StringFormatName.TickerSymbol; return; case Metadata.StringFormatName.Url: StringFormat = Microsoft.Xrm.Sdk.Metadata.StringFormatName.Url; return; case Metadata.StringFormatName.VersionNumber: StringFormat = Microsoft.Xrm.Sdk.Metadata.StringFormatName.VersionNumber; return; } } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Settings/PublisherSettings.cs namespace Civica.CrmPlusPlus.Sdk.Settings { public class PublisherSettings { public static PublisherSettings Default { get { return new PublisherSettings(); } } public string DisplayName { get; set; } public string Name { get; set; } public string Prefix { get; set; } public int OptionValuePrefix { get; set; } private PublisherSettings() { DisplayName = "Civica"; Name = "civica"; Prefix = "civica"; OptionValuePrefix = 48871; } public PublisherSettings(string displayName, string name, string prefix, int optionValuePrefix) { DisplayName = displayName; Name = name; Prefix = prefix; OptionValuePrefix = optionValuePrefix; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/PropertyTypes/DoubleAttribute.cs using System; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class DoubleAttribute : Attribute { public int MaxValue { get; } public int MinValue { get; } public int Precision { get; } public DoubleAttribute(int maxValue, int minValue, int precision) { MaxValue = maxValue; MinValue = minValue; Precision = precision; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Settings/SolutionSettings.cs namespace Civica.CrmPlusPlus.Sdk.Settings { public class SolutionSettings { public static SolutionSettings Default { get { return new SolutionSettings("CrmPlusPlus", "CRM++", "1.0.0.0"); } } public string Name { get; private set; } public string DisplayName { get; private set; } public string Version { get; private set; } public SolutionSettings(string name, string displayName, string version) { Name = name; DisplayName = displayName; Version = version; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Querying/StringExtensions.cs namespace Civica.CrmPlusPlus.Sdk.Querying { internal static class StringExtensions { internal static string ClearXmlFormatting(this string str) { return str .Replace("\r\n", string.Empty) .Replace(" />", "/>") .Replace(" ", string.Empty) .Replace("> <", "><"); } internal static string ToIdAlias(this string alias) { return string.IsNullOrEmpty(alias) ? "id" : alias + ".id"; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Client/ICrmPlusPlusEntityClient.cs using System; using System.Collections.Generic; using Civica.CrmPlusPlus.Sdk.Client.Association; using Civica.CrmPlusPlus.Sdk.Client.Retrieve; using Civica.CrmPlusPlus.Sdk.Querying; namespace Civica.CrmPlusPlus.Sdk.Client { public interface ICrmPlusPlusEntityClient { void Associate(string relationshipName, Associate association); void Disassociate(string relationshipName, Associate association); Guid Create<T>(T entity) where T : CrmPlusPlusEntity, new(); void Update<T>(T entity) where T : CrmPlusPlusEntity, new(); T Retrieve<T>(Retrieval<T> retrieval) where T : CrmPlusPlusEntity, new(); void Delete<T>(T entity) where T : CrmPlusPlusEntity, new(); IEnumerable<T> RetrieveMultiple<T>(Query<T> query) where T : CrmPlusPlusEntity, new(); } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/JoinedEntity.cs using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; namespace Civica.CrmPlusPlus.Sdk.Tests.Client { [EntityName("civica_joinedentity")] [EntityInfo("Joined Entity", OwnershipType.OrganizationOwned)] public class JoinedEntity { [PropertyName("lookup")] [PropertyInfo("Lookup", AttributeRequiredLevel.ApplicationRequired)] [Lookup] public EntityReference<EntityWithProperties> EntityWithPropertiesLookup { get; set; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/PropertyTypes/IntegerAttribute.cs using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xrm.Sdk.Metadata; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class IntegerAttribute : Attribute { public int MaxValue { get; } public int MinValue { get; } public IntegerFormat Format { get; } public IntegerAttribute(int maxValue, int minValue, Metadata.IntegerFormat format) { MaxValue = maxValue; MinValue = minValue; Format = format.ToSimilarEnum<IntegerFormat>(); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/Metadata/DateTimeFormat.cs namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata { public enum DateTimeFormat { DateOnly = 0, DateAndTime = 1 } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/EntityWithoutInfo.cs using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus.Sdk.Tests.Client { [EntityName("civica_entitywithoutinfo")] public class EntityWithoutInfo : CrmPlusPlusEntity { } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/CrmPlusPlusCustomizationClientTests.cs using System; using Civica.CrmPlusPlus.Sdk.Client; using Civica.CrmPlusPlus.Sdk.DefaultEntities; using FakeItEasy; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Xunit; namespace Civica.CrmPlusPlus.Sdk.Tests.Client { public class CrmPlusPlusCustomizationClientTests { [Fact] public void WhenEntityHasNoEntityNameAttribute_Create_ThrowsInvalidOperationException() { var organisationService = A.Fake<IOrganizationService>(); var client = new CrmPlusPlusCustomizationClient(A.Fake<Publisher>(), A.Fake<Solution>(), organisationService); Assert.Throws<InvalidOperationException>(() => client.CreateEntity<EntityWithoutName>()); } [Fact] public void WhenEntityHasNoEntityInfoAttribute_Create_ThrowsInvalidOperationException() { var organisationService = A.Fake<IOrganizationService>(); var client = new CrmPlusPlusCustomizationClient(A.Fake<Publisher>(), A.Fake<Solution>(), organisationService); Assert.Throws<InvalidOperationException>(() => client.CreateEntity<EntityWithoutInfo>()); } [Fact] public void WhenEntityHasEntityInfoAndNameAttributes_ShouldCreateEntity() { var organisationService = A.Fake<IOrganizationService>(); A.CallTo(() => organisationService.Execute(A<CreateEntityRequest>._)).Returns(new CreateEntityResponse()); var client = new CrmPlusPlusCustomizationClient(A.Fake<Publisher>(), A.Fake<Solution>(), organisationService); client.CreateEntity<EntityWithProperties>(); } [Fact] public void WhenEntityHasStringPropertyWithoutNameAttribute_ShouldThrowInvalidOperationException_AndShouldNotAttemptToCreateProperty() { var organisationService = A.Fake<IOrganizationService>(); var client = new CrmPlusPlusCustomizationClient(A.Fake<Publisher>(), A.Fake<Solution>(), organisationService); Assert.Throws<InvalidOperationException>(() => client.CreateProperty<EntityWithProperties, string>(e => e.StringPropertyWithoutNameAttribute)); A.CallTo(() => organisationService.Execute(A<OrganizationRequest>._)).MustNotHaveHappened(); } [Fact] public void WhenEntityHasStringPropertyWithoutInfoAttribute_ShouldThrowInvalidOperationException_AndShouldNotAttemptToCreateProperty() { var organisationService = A.Fake<IOrganizationService>(); var client = new CrmPlusPlusCustomizationClient(A.Fake<Publisher>(), A.Fake<Solution>(), organisationService); Assert.Throws<InvalidOperationException>(() => client.CreateProperty<EntityWithProperties, string>(e => e.StringPropertyWithoutInfoAttribute)); A.CallTo(() => organisationService.Execute(A<OrganizationRequest>._)).MustNotHaveHappened(); } [Fact] public void WhenEntityHasStringPropertyWithoutStringAttribute_ShouldNotAttemptToCreateProperty() { var organisationService = A.Fake<IOrganizationService>(); var client = new CrmPlusPlusCustomizationClient(A.Fake<Publisher>(), A.Fake<Solution>(), organisationService); A.CallTo(() => organisationService.Execute(A<OrganizationRequest>._)).MustNotHaveHappened(); } [Fact] public void WhenEntityHasStringPropertyWithoutAllRequiredAttributes_ShouldCreateProperty() { var organisationService = A.Fake<IOrganizationService>(); var client = new CrmPlusPlusCustomizationClient(A.Fake<Publisher>(), A.Fake<Solution>(), organisationService); client.CreateProperty<EntityWithProperties, string>(e => e.StringPropertyWithAllRequiredAttributes); A.CallTo(() => organisationService.Execute(A<OrganizationRequest>._)).MustHaveHappened(Repeated.Exactly.Once); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Client/Retrieve/Retrieval.cs using System; using System.Collections.Generic; using System.Linq.Expressions; using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus.Sdk.Client.Retrieve { public class Retrieval<T> where T : CrmPlusPlusEntity, new() { internal Guid Id { get; } internal List<string> IncludedColumns { get; private set; } internal bool AllColumns { get; private set; } internal Retrieval(Guid id) { Id = id; AllColumns = false; IncludedColumns = new List<string>(); IncludedColumns.Add("createdon"); IncludedColumns.Add("modifiedon"); } public Retrieval<T> IncludeAllColumns(bool flag) { AllColumns = flag; return this; } public Retrieval<T> Include<TProperty>(Expression<Func<T, TProperty>> propertyExpr) { var propertyName = PropertyNameAttribute.GetFromType(propertyExpr); if (propertyName == "modifiedon" || propertyName == "createdon" || propertyName == "id") { return this; } if (!IncludedColumns.Contains(propertyName.ToLower())) { IncludedColumns.Add(propertyName); } return this; } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/RetrieveMultiple/EntityClientRetrieveMultipleTests.cs using System; using System.Collections.Generic; using System.Linq; using Civica.CrmPlusPlus.Sdk.Client; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; using Civica.CrmPlusPlus.Sdk.Querying; using FakeItEasy; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; using Xunit; namespace Civica.CrmPlusPlus.Sdk.Tests.Client.RetrieveMultiple { public class EntityClientRetrieveMultipleTests { [Fact] public void Has1ToNRelatedEntityRecords_ReturnsDataCorrectly() { var testEntity1Id = Guid.NewGuid(); var testEntity1String = "dshajdsghjk"; var testEntity2FirstId = Guid.NewGuid(); var testEntity2SecondId = Guid.NewGuid(); var testEntity2FirstInt = 3; var testEntity2SecondInt = 5; var flatData = new List<Entity>(); var first = new Entity(EntityNameAttribute.GetFromType<RetrieveMultipleTestEntity1>(), testEntity1Id); first["id"] = testEntity1Id; first["createdon"] = DateTime.Now; first["modifiedon"] = DateTime.Now; first["teststring"] = testEntity1String; first["retrievemultipletestentity2.id"] = new AliasedValue("retrievemultipletestentity2", "id", testEntity2FirstId); first["retrievemultipletestentity2.testint"] = new AliasedValue("retrievemultipletestentity2", "testint", testEntity2FirstInt); var second = new Entity(EntityNameAttribute.GetFromType<RetrieveMultipleTestEntity1>(), testEntity1Id); second["id"] = testEntity1Id; second["createdon"] = DateTime.Now; second["modifiedon"] = DateTime.Now; second["teststring"] = testEntity1String; second["retrievemultipletestentity2.id"] = new AliasedValue("retrievemultipletestentity2", "id", testEntity2SecondId); second["retrievemultipletestentity2.testint"] = new AliasedValue("retrievemultipletestentity2", "testint", testEntity2SecondInt); flatData.Add(first); flatData.Add(second); var service = A.Fake<IOrganizationService>(); A.CallTo(() => service.RetrieveMultiple(A<QueryBase>._)) .Returns(new EntityCollection(flatData)); var crmPlusPlusEntityClient = new CrmPlusPlusEntityClient(service); var result = crmPlusPlusEntityClient.RetrieveMultiple(Query.ForEntity<RetrieveMultipleTestEntity1>()); Assert.Equal(1, result.Count()); Assert.Equal(2, result.Single().RelatedEntities.Count()); var firstEntity = result.Single(); Assert.Equal(testEntity1String, firstEntity.TestString); Assert.Contains(testEntity2FirstInt, firstEntity.RelatedEntities.Select(e => e.TestInt)); Assert.Contains(testEntity2SecondInt, firstEntity.RelatedEntities.Select(e => e.TestInt)); } [Fact] public void HasNTo1RelatedEntityRecords_ReturnsDataCorrectly() { var testEntity2Id = Guid.NewGuid(); var testEntity2Int = 2; var testEntity1Id = Guid.NewGuid(); var testEntity1String = "dshjakl"; var flatData = new List<Entity>(); var entity = new Entity(EntityNameAttribute.GetFromType<RetrieveMultipleTestEntity2>(), testEntity2Id); entity["id"] = testEntity2Id; entity["createdon"] = DateTime.Now; entity["modifiedon"] = DateTime.Now; entity["testint"] = testEntity2Int; entity["retrievemultipletestentity1.id"] = new AliasedValue("retrievemultipletestentity2", "id", testEntity1Id); entity["retrievemultipletestentity1.teststring"] = new AliasedValue("retrievemultipletestentity2", "testint", testEntity1String); flatData.Add(entity); var service = A.Fake<IOrganizationService>(); A.CallTo(() => service.RetrieveMultiple(A<QueryBase>._)) .Returns(new EntityCollection(flatData)); var crmPlusPlusEntityClient = new CrmPlusPlusEntityClient(service); var result = crmPlusPlusEntityClient.RetrieveMultiple(Query.ForEntity<RetrieveMultipleTestEntity2>()); Assert.Equal(1, result.Count()); var singleResult = result.Single(); Assert.Equal(testEntity2Int, singleResult.TestInt); Assert.NotNull(singleResult.RetrieveMultipleTestEntity1Lookup); Assert.Equal(testEntity1Id, singleResult.RetrieveMultipleTestEntity1Lookup.Id); Assert.NotNull(singleResult.RetrieveMultipleTestEntity1Lookup.Entity); Assert.Equal(testEntity1Id, singleResult.RetrieveMultipleTestEntity1Lookup.Entity.Id); Assert.Equal(testEntity1String, singleResult.RetrieveMultipleTestEntity1Lookup.Entity.TestString); } [Theory] [InlineData(true)] [InlineData(false)] public void HasNTo1NestedRelatedEntityRecords_ReturnsDataCorrectly(bool includeNestedEntityId) { var entity3Id = Guid.NewGuid(); var entity2Id = Guid.NewGuid(); var entity1Id = Guid.NewGuid(); var entity3TestInt = 13; var entity2TestInt = 66; var entity1TestString = "gfhjk"; var entity = new Entity("retrievemultipletestentity3", entity3Id); entity["id"] = entity.Id; entity["testint"] = entity3TestInt; entity["retrievemultipletestentity2.id"] = Guid.NewGuid(); entity["retrievemultipletestentity2.testint"] = entity2TestInt; entity["retrievemultipletestentity1.id"] = entity1Id; entity["retrievemultipletestentity1.teststring"] = entity1TestString; } } [EntityName("retrievemultipletestentity1")] [EntityInfo("Test Entity 1", EntityAttributes.Metadata.OwnershipType.UserOwned)] public class RetrieveMultipleTestEntity1 : CrmPlusPlusEntity { [PropertyName("teststring")] [PropertyInfo("Test String", EntityAttributes.Metadata.AttributeRequiredLevel.None)] [String(100, EntityAttributes.Metadata.StringFormatName.Text)] public string TestString { get; set; } public IEnumerable<RetrieveMultipleTestEntity2> RelatedEntities { get; set; } } [EntityName("retrievemultipletestentity2")] [EntityInfo("Test Entity 2", EntityAttributes.Metadata.OwnershipType.UserOwned)] public class RetrieveMultipleTestEntity2 : CrmPlusPlusEntity { [PropertyName("testint")] [PropertyInfo("Test Int", EntityAttributes.Metadata.AttributeRequiredLevel.None)] [Integer(100, 0, EntityAttributes.Metadata.IntegerFormat.None)] public int TestInt { get; set; } [PropertyName("testlookup1")] [PropertyInfo("Test Lookup 1", EntityAttributes.Metadata.AttributeRequiredLevel.None)] [Lookup] public EntityReference<RetrieveMultipleTestEntity1> RetrieveMultipleTestEntity1Lookup { get; set; } public IEnumerable<RetrieveMultipleTestEntity3> RelatedEntities2 { get; set; } } [EntityName("retrievemultipletestentity3")] [EntityInfo("Test Entity 3", EntityAttributes.Metadata.OwnershipType.UserOwned)] public class RetrieveMultipleTestEntity3 : CrmPlusPlusEntity { [PropertyName("testint")] [PropertyInfo("Test Int", EntityAttributes.Metadata.AttributeRequiredLevel.None)] [Integer(100, 0, EntityAttributes.Metadata.IntegerFormat.None)] public int TestInt { get; set; } [PropertyName("testlookup2")] [PropertyInfo("Test Lookup 2", EntityAttributes.Metadata.AttributeRequiredLevel.None)] [Lookup] public EntityReference<RetrieveMultipleTestEntity2> RetrieveMultipleTestEntity2Lookup { get; set; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/Metadata/AttributeRequiredLevel.cs namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata { public enum AttributeRequiredLevel { None = 0, SystemRequired = 1, ApplicationRequired = 2, Recommended = 3 } } <file_sep>/Civica.CrmPlusPlus.Sdk/Querying/QueryBuilder.cs using System; using System.Collections.Generic; using System.Xml.Linq; namespace Civica.CrmPlusPlus.Sdk.Querying { public class Query { internal XElement QueryXml { get; } internal Query(bool withDistinctResults) { QueryXml = new XElement("fetch"); QueryXml.Add(new XAttribute("mapping", "logical")); QueryXml.Add(new XAttribute("distinct", withDistinctResults.ToString().ToLower())); } public static Query<T> ForEntity<T>(bool distinct = false) where T : CrmPlusPlusEntity, new() { var query = new Query(distinct); return new Query<T>(query); } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/Association/TestEntityToBeAssociated.cs using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus.Sdk.Tests.Client.Association { [EntityName("test_entitytobeassociated")] public class TestEntityToBeAssociated : CrmPlusPlusEntity { } } <file_sep>/Civica.CrmPlusPlus.Sdk/Querying/FilterType.cs namespace Civica.CrmPlusPlus.Sdk.Querying { public enum FilterType { And, Or } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/Metadata/StringFormatName.cs namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata { public enum StringFormatName { Email, Phone, PhoneticGuide, Text, TextArea, TickerSymbol, Url, VersionNumber } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/Association/TestAssociatedEntity.cs using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus.Sdk.Tests.Client.Association { [EntityName("test_associatedentity")] public class TestAssociatedEntity : CrmPlusPlusEntity { } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityReference.cs using System; namespace Civica.CrmPlusPlus.Sdk { public class EntityReference<T> where T : CrmPlusPlusEntity, new() { public Guid Id { get; } public T Entity { get; set; } public EntityReference(Guid id) { Id = id; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/DefaultEntities/Publisher.cs using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; namespace Civica.CrmPlusPlus.Sdk.DefaultEntities { [EntityName("publisher")] [EntityInfo("Publisher", EntityAttributes.Metadata.OwnershipType.OrganizationOwned)] public class Publisher : CrmPlusPlusEntity { [PropertyName("friendlyname")] [PropertyInfo("Display Name", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [String(255, EntityAttributes.Metadata.StringFormatName.Text)] public string DisplayName { get; set; } [PropertyName("uniquename")] [PropertyInfo("Name", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [String(255, EntityAttributes.Metadata.StringFormatName.Text)] public string Name { get; set; } [PropertyName("customizationprefix")] [PropertyInfo("Prefix", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [String(8, EntityAttributes.Metadata.StringFormatName.Text)] public string Prefix { get; set; } [PropertyName("customizationoptionvalueprefix")] [PropertyInfo("Option Value Prefix", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [Integer(10000, 99999, EntityAttributes.Metadata.IntegerFormat.None)] public int OptionValuePrefix { get; set; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/PropertyInfoAttribute.cs using System; using System.Linq; using System.Linq.Expressions; using Civica.CrmPlusPlus.Sdk.Validation; using Microsoft.Xrm.Sdk.Metadata; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class PropertyInfoAttribute : Attribute { public string DisplayName { get; } public AttributeRequiredLevel AttributeRequiredLevel { get; } public string Description { get; } public PropertyInfoAttribute(string displayName, Metadata.AttributeRequiredLevel attributeRequiredLevel, string description = null) { Guard.This(displayName).AgainstNullOrEmpty(); DisplayName = displayName; AttributeRequiredLevel = attributeRequiredLevel.ToSimilarEnum<AttributeRequiredLevel>(); Description = string.IsNullOrEmpty(description) ? displayName : description; } internal static PropertyInfoAttribute GetFromType<T, TProperty>(Expression<Func<T, TProperty>> propertyExpr) where T : CrmPlusPlusEntity, new() { Guard.This(propertyExpr.Body).AgainstNonMemberExpression(); var propertyInfo = ((MemberExpression)propertyExpr.Body).Member; var propertyNameAttributes = propertyInfo.GetCustomAttributes(true) .Where(attr => attr.GetType() == typeof(PropertyInfoAttribute)); if (propertyNameAttributes.Any()) { return ((PropertyInfoAttribute)propertyNameAttributes.Single()); } throw new InvalidOperationException(string.Format("Cannot retrieve property information from member '{0}' of type '{1}'. PropertyInfoAttribute not found for this type", propertyInfo.Name, typeof(T).Name)); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Validation/GuardExpressionExtensions.cs using System; using System.Linq.Expressions; namespace Civica.CrmPlusPlus.Sdk.Validation { internal static class GuardExpressionExtensions { internal static GuardThis<Expression> AgainstNonMemberExpression(this GuardThis<Expression> guard) { if (!(guard.Obj is MemberExpression)) { throw new ArgumentException("Expression expected to be of type 'MemberExpression' but it was not"); } return guard; } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/EntityExtensionsTests.cs using System; using System.Linq; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; using Microsoft.Xrm.Sdk; using Xunit; namespace Civica.CrmPlusPlus.Sdk.Tests { public class EntityExtensionsTests { [Fact] public void CorrectlyMapsPropertiesFromCrmEntity() { var lookupId = Guid.NewGuid(); var myString = "dhsjadhkjsl"; var myInt = 32; var myDateTime = DateTime.Now; var myDecimal = 143.12M; var myBool = false; var myDouble = 103.23; var myLookup = new EntityReference<CrmPlusPlusEntityExtensionsEntity>(lookupId); var crmEntity = new Entity("civica_entityexample", Guid.NewGuid()); crmEntity["createdon"] = DateTime.Now; // Required by default crmEntity["modifiedon"] = DateTime.Now; // Required by default crmEntity["civica_string"] = myString; crmEntity["civica_int"] = myInt; crmEntity["civica_datetime"] = myDateTime; crmEntity["civica_decimal"] = myDecimal; crmEntity["civica_bool"] = myBool; crmEntity["civica_double"] = myDouble; crmEntity["civica_lookup"] = new EntityReference("civica_entityexample", lookupId); crmEntity["civica_optionset"] = new OptionSetValue(3); var entity = crmEntity.ToCrmPlusPlusEntity<EntityExtensionsEntity>(); Assert.Equal(myString, entity.MyString); Assert.Equal(myInt, entity.MyInt); Assert.Equal(myDateTime, entity.MyDateTime); Assert.Equal(myDecimal, entity.MyDecimal); Assert.Equal(myBool, entity.MyBool); Assert.Equal(myDouble, entity.MyDouble); Assert.Equal(myLookup.Id, entity.MyLookup.Id); Assert.Equal(typeof(EntityExtensionsEntity), entity.MyLookup.GetType().GetGenericArguments().Single()); Assert.Equal(MyOptionSet.Three, entity.MyOptionSet); } } [EntityName("civica_entityexample")] [EntityInfo("Entity Example", OwnershipType.OrganizationOwned)] public class EntityExtensionsEntity : CrmPlusPlusEntity { [PropertyName("civica_string")] [PropertyInfo("String", AttributeRequiredLevel.None)] [String(100, StringFormatName.Email)] public string MyString { get; set; } [PropertyName("civica_int")] [PropertyInfo("Integer", AttributeRequiredLevel.None)] [Integer(100, 0, IntegerFormat.None)] public int MyInt { get; set; } [PropertyName("civica_datetime")] [PropertyInfo("Date Time", AttributeRequiredLevel.None)] [DateTime(DateTimeFormat.DateAndTime)] public DateTime MyDateTime { get; set; } [PropertyName("civica_bool")] [PropertyInfo("Bool", AttributeRequiredLevel.None)] [Boolean] public bool MyBool { get; set; } [PropertyName("civica_double")] [PropertyInfo("Double", AttributeRequiredLevel.None)] [Double(1000, 0, 2)] public double MyDouble { get; set; } [PropertyName("civica_decimal")] [PropertyInfo("Decimal", AttributeRequiredLevel.None)] [Decimal(1000, 0, 2)] public decimal MyDecimal { get; set; } [PropertyName("civica_lookup")] [PropertyInfo("Lookup", AttributeRequiredLevel.None)] [Lookup] public EntityReference<EntityExtensionsEntity> MyLookup { get; set; } [PropertyName("civica_optionset")] [PropertyInfo("Option set", AttributeRequiredLevel.None)] [OptionSet] public MyOptionSet MyOptionSet { get; set; } } public enum MyOptionSet { One=1, Two=2, Three=3 } } <file_sep>/Civica.CrmPlusPlus.Sdk/Client/RetrieveMultiple/RetrieveMultipleParser.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.Querying; using Microsoft.Xrm.Sdk; namespace Civica.CrmPlusPlus.Sdk.Client.RetrieveMultiple { public class RetrieveMultipleParser<T> where T: CrmPlusPlusEntity, new() { private readonly DataCollection<Entity> entities; public RetrieveMultipleParser(DataCollection<Entity> entities) { this.entities = entities; } public IEnumerable<T> GetMainEntities() { var groupedMainEntities = entities.GroupBy(e => e.Id, e => e, (k, r) => r); var mainEntities = new List<T>(); foreach (var group in groupedMainEntities) { var mainEntity = group.First(); mainEntities.Add(mainEntity.ToCrmPlusPlusEntity<T>()); } return mainEntities; } public IEnumerable<T> PopulateOneToManyEntities(IEnumerable<T> mainEntities) { var oneToManyRelationships = GetOneToManyRelationships(); foreach (var oneToManyRelationship in oneToManyRelationships) { var relatedEntityType = oneToManyRelationship.Value; var oneToManyPropertiesOfType = TypeDescriptor.GetProperties(typeof(T)).AsEnumerable() .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>) && p.PropertyType.GetGenericArguments().Count() == 1 && p.PropertyType.GetGenericArguments().Single() == relatedEntityType); var groupedOneToManyEntities = entities .WhereEntitiesHaveKeyThatContains(oneToManyRelationship.Key.ToIdAlias()) .GroupBy(e => e[oneToManyRelationship.Key.ToIdAlias()], e => e, (k, r) => r); var manyEntities = new List<CrmPlusPlusEntity>(); foreach (var groupedOneToManyEntity in groupedOneToManyEntities) { var manyEntity = groupedOneToManyEntity.First(); manyEntities.Add(manyEntity.ToCrmPlusPlusEntity(relatedEntityType, oneToManyRelationship.Key)); } foreach (var mainEntity in mainEntities) { foreach (var oneToManyPropertyOfType in oneToManyPropertiesOfType) { var cast = typeof(Enumerable).GetMethod("Cast") .MakeGenericMethod(new Type[] { relatedEntityType }); oneToManyPropertyOfType.SetValue(mainEntity, cast.Invoke(null, new object[] { manyEntities })); } } } return mainEntities; } public IEnumerable<T> PopulateManyToOneEntity(IEnumerable<T> mainEntities) { var manyToOneRelationships = GetManyToOneRelationships(); foreach (var manyToOneRelationship in manyToOneRelationships) { var relatedEntityType = manyToOneRelationship.Value; var manyToOnePropertiesOfType = TypeDescriptor.GetProperties(typeof(T)).AsEnumerable() .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>) && p.PropertyType.GetGenericArguments().Count() == 1 && p.PropertyType.GetGenericArguments().Single() == relatedEntityType); var groupedManyToOneEntities = entities.GroupBy(e => e.Id, e => e, (k, r) => new { Id = k, Entities = r }); foreach (var groupedManyToOneEntity in groupedManyToOneEntities) { var lookupEntity = groupedManyToOneEntity.Entities.First(); var crmPlusPlusLookupEntity = lookupEntity.ToCrmPlusPlusEntity(relatedEntityType, manyToOneRelationship.Key); var mainEntity = mainEntities.Single(e => e.Id == groupedManyToOneEntity.Id); foreach (var manyToOnePropertyOfType in manyToOnePropertiesOfType) { var lookup = Activator.CreateInstance(typeof(EntityReference<>).MakeGenericType(relatedEntityType), new object[] { crmPlusPlusLookupEntity.Id }); var lookupValueProperty = TypeDescriptor.GetProperties(lookup).AsEnumerable().SingleOrDefault(p => p.PropertyType == relatedEntityType); lookupValueProperty.SetValue(lookup, crmPlusPlusLookupEntity); manyToOnePropertyOfType.SetValue(mainEntity, lookup); } } } return mainEntities; } public Dictionary<string, Type> GetManyToOneRelationships() { var aliases = GetAliasesInCollection(); var manyToOneRelationships = TypeDescriptor.GetProperties(typeof(T)).AsEnumerable() .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>) && p.PropertyType.GetGenericArguments().Count() == 1 && p.PropertyType.GetGenericArguments().Single() != typeof(T) && typeof(CrmPlusPlusEntity).IsAssignableFrom(p.PropertyType.GetGenericArguments().Single())); var relationships = new Dictionary<string, Type>(); foreach (var manyToOneRelationship in manyToOneRelationships) { var lookupEntity = manyToOneRelationship.PropertyType.GetGenericArguments().Single(); var alias = EntityNameAttribute.GetFromType(lookupEntity); if (aliases.Contains(alias) && !relationships.ContainsKey(alias)) { relationships.Add(alias, lookupEntity); } } return relationships; } public Dictionary<string, Type> GetOneToManyRelationships() { var aliases = GetAliasesInCollection(); var oneToManyRelationships = TypeDescriptor.GetProperties(typeof(T)).AsEnumerable() .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>) && p.PropertyType.GetGenericArguments().Count() == 1 && p.PropertyType.GetGenericArguments().Single() != typeof(T) && typeof(CrmPlusPlusEntity).IsAssignableFrom(p.PropertyType.GetGenericArguments().Single())); var relationships = new Dictionary<string, Type>(); foreach (var oneToManyRelationship in oneToManyRelationships) { var manyEntity = oneToManyRelationship.PropertyType.GetGenericArguments().Single(); var alias = EntityNameAttribute.GetFromType(manyEntity); if (aliases.Contains(alias) && !relationships.ContainsKey(alias)) { relationships.Add(alias, manyEntity); } } return relationships; } private IEnumerable<string> GetAliasesInCollection() { var aliases = new List<string>(); foreach (var entity in entities) { var keys = entity.Attributes.Keys; var aliasedKeys = keys.Where(k => k.Contains(".")); foreach (var aliasedKey in aliasedKeys) { var alias = aliasedKey.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)[0]; if (!aliases.Contains(alias)) { aliases.Add(alias); } } } return aliases; } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/EntityWithoutName.cs using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus.Sdk.Tests.Client { [EntityInfo("Entity without name", EntityAttributes.Metadata.OwnershipType.OrganizationOwned)] public class EntityWithoutName : CrmPlusPlusEntity { } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Querying/TestNestedJoinedEntity.cs using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; namespace Civica.CrmPlusPlus.Sdk.Tests.Querying { [EntityName("testnestedjoinedentity")] [EntityInfo("Test Nested Joined Entity", OwnershipType.UserOwned)] public class TestNestedJoinedEntity : CrmPlusPlusEntity { [PropertyName("testnestedlookupname")] [PropertyInfo("Test lookup", AttributeRequiredLevel.Recommended)] [Lookup] public EntityReference<TestJoinedEntity> TestNestedLookupName { get; set; } [PropertyName("testnumber")] [PropertyInfo("Test Number", AttributeRequiredLevel.None)] [Integer(100, 0, IntegerFormat.None)] public int Number { get; set; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/DefaultEntities/Solution.cs using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; namespace Civica.CrmPlusPlus.Sdk.DefaultEntities { [EntityName("solution")] [EntityInfo("Solution", EntityAttributes.Metadata.OwnershipType.OrganizationOwned)] public class Solution : CrmPlusPlusEntity { [PropertyName("uniquename")] [PropertyInfo("Name", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [String(100, EntityAttributes.Metadata.StringFormatName.Text)] public string Name { get; set; } [PropertyName("friendlyname")] [PropertyInfo("Display Name", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [String(100, EntityAttributes.Metadata.StringFormatName.Text)] public string DisplayName { get; set; } [PropertyName("version")] [PropertyInfo("Version", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [String(100, EntityAttributes.Metadata.StringFormatName.Text)] public string Version { get; set; } [PropertyName("ismanaged")] [PropertyInfo("Is Managed", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [Boolean] public bool IsManaged { get; set; } [PropertyName("isvisible")] [PropertyInfo("Is Visible", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [Boolean] public bool IsVisible { get; set; } [PropertyName("publisherid")] [PropertyInfo("Publisher", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [Lookup] public EntityReference<Publisher> Publisher { get; set; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/CrmPlusPlusEntityExtensions.cs using System; using System.ComponentModel; using System.Linq; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; namespace Civica.CrmPlusPlus.Sdk { public static class CrmPlusPlusEntityExtensions { internal static Microsoft.Xrm.Sdk.Entity ToCrmEntity<T>(this T crmPlusPlusEntity) where T : CrmPlusPlusEntity, new() { var entity = new Microsoft.Xrm.Sdk.Entity(EntityNameAttribute.GetFromType<T>(), crmPlusPlusEntity.Id); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(typeof(T))) { var attributes = property.Attributes.AsEnumerable(); var propertyNameAttr = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyNameAttribute)); var propertyInfoAttr = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyInfoAttribute)); var typeInfoAttr = attributes .SingleOrDefault(attr => (attr.GetType() == typeof(BooleanAttribute) && property.PropertyType == typeof(bool)) || (attr.GetType() == typeof(DateTimeAttribute) && property.PropertyType == typeof(DateTime)) || (attr.GetType() == typeof(DecimalAttribute) && property.PropertyType == typeof(decimal)) || (attr.GetType() == typeof(DoubleAttribute) && property.PropertyType == typeof(double)) || (attr.GetType() == typeof(IntegerAttribute) && property.PropertyType == typeof(int)) || (attr.GetType() == typeof(StringAttribute) && property.PropertyType == typeof(string)) || (attr.GetType() == typeof(LookupAttribute) && property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>)) || (attr.GetType() == typeof(OptionSetAttribute) && property.PropertyType.IsEnum)); if (propertyNameAttr != null && propertyInfoAttr != null && typeInfoAttr != null) { var propertyName = ((PropertyNameAttribute)propertyNameAttr).PropertyName; var value = property.GetValue(crmPlusPlusEntity); if (value != null) { if (value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(EntityReference<>)) { var entityReferenceType = property.PropertyType.GetGenericArguments().Single(); var entityName = EntityNameAttribute.GetFromType(entityReferenceType); value = new Microsoft.Xrm.Sdk.EntityReference(entityName, ((dynamic)value).Id); } else if (value.GetType().IsEnum) { value = new Microsoft.Xrm.Sdk.OptionSetValue((int)value); } entity[propertyName] = value; } } } return entity; } public static EntityReference<T> AsEntityReference<T>(this T crmPlusPlusEntity) where T : CrmPlusPlusEntity, new() { return new EntityReference<T>(crmPlusPlusEntity.Id); } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/CrmPlusPlusEntityExtensionsTests.cs using System; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; using Microsoft.Xrm.Sdk; using Xunit; namespace Civica.CrmPlusPlus.Sdk.Tests { public class CrmPlusPlusEntityExtensionsTests { [Fact] public void CorrectlyMapsPropertiesToCrmEntity() { var lookupId = Guid.NewGuid(); var myString = "dhsjadhkjsl"; var myInt = 32; var myDateTime = DateTime.Now; var myDecimal = 143.12M; var myBool = false; var myDouble = 103.23; var myLookup = new EntityReference<CrmPlusPlusEntityExtensionsEntity>(lookupId); var myOptionSet = TestOptionSet.Three; var entity = new CrmPlusPlusEntityExtensionsEntity { MyString = myString, MyInt = myInt, MyDateTime = myDateTime, MyDecimal = myDecimal, MyBool = myBool, MyDouble = myDouble, MyLookup = myLookup, OptionSet = myOptionSet }; var crmEntity = entity.ToCrmEntity(); Assert.Equal(myString, crmEntity["civica_string"]); Assert.Equal(myInt, crmEntity["civica_int"]); Assert.Equal(myDateTime, crmEntity["civica_datetime"]); Assert.Equal(myDecimal, crmEntity["civica_decimal"]); Assert.Equal(myBool, crmEntity["civica_bool"]); Assert.Equal(myDouble, crmEntity["civica_double"]); Assert.Equal(myLookup.Id, ((Microsoft.Xrm.Sdk.EntityReference)crmEntity["civica_lookup"]).Id); Assert.Equal(EntityNameAttribute.GetFromType<CrmPlusPlusEntityExtensionsEntity>(), ((Microsoft.Xrm.Sdk.EntityReference)crmEntity["civica_lookup"]).LogicalName); Assert.Equal((int)myOptionSet, ((OptionSetValue)crmEntity["civica_optionset"]).Value); } } [EntityName("civica_entityexample")] [EntityInfo("Entity Example", OwnershipType.OrganizationOwned)] public class CrmPlusPlusEntityExtensionsEntity : CrmPlusPlusEntity { [PropertyName("civica_string")] [PropertyInfo("String", AttributeRequiredLevel.None)] [String(100, StringFormatName.Email)] public string MyString { get; set; } [PropertyName("civica_int")] [PropertyInfo("Integer", AttributeRequiredLevel.None)] [Integer(100, 0, IntegerFormat.None)] public int MyInt { get; set; } [PropertyName("civica_datetime")] [PropertyInfo("Date Time", AttributeRequiredLevel.None)] [DateTime(DateTimeFormat.DateAndTime)] public DateTime MyDateTime { get; set; } [PropertyName("civica_bool")] [PropertyInfo("Bool", AttributeRequiredLevel.None)] [Boolean] public bool MyBool { get; set; } [PropertyName("civica_double")] [PropertyInfo("Double", AttributeRequiredLevel.None)] [Double(1000, 0, 2)] public double MyDouble { get; set; } [PropertyName("civica_decimal")] [PropertyInfo("Decimal", AttributeRequiredLevel.None)] [Decimal(1000, 0, 2)] public decimal MyDecimal { get; set; } [PropertyName("civica_lookup")] [PropertyInfo("Lookup", AttributeRequiredLevel.None)] [Lookup] public EntityReference<CrmPlusPlusEntityExtensionsEntity> MyLookup { get; set; } [PropertyName("civica_optionset")] [PropertyInfo("Option set", AttributeRequiredLevel.None)] [OptionSet] public TestOptionSet OptionSet { get; set; } } public enum TestOptionSet { One = 1, Two = 2, Three = 3 } } <file_sep>/Civica.CrmPlusPlus.Sdk/Client/Retrieve/RetrievalBuilder.cs using System; namespace Civica.CrmPlusPlus.Sdk.Client.Retrieve { public static class Retrieval { public static Retrieval<T> ForEntity<T>(Guid id) where T : CrmPlusPlusEntity, new() { return new Retrieval<T>(id); } } } <file_sep>/README.md ### CRM ++ ### * CRM++ provides an easier way to integrate with Dynamics CRM. ### Overview ### Those who are familiar to using the CRM IOrganizationService interface will know that using this service with late-bound entities can be painful and difficult to test. Even using the XRM code-generation tool to generate early bound entity classes can be ugly when it comes to the naming conventions, querying and customising. CRM++ aims to solve these difficulties by allowing entities to be designed in code and providing strongly-typed methods for querying and customising. ### Quick start ### * Reference CRM++ and use it's provided clients ``` string myConnectionString = "Url=;Username=;Password=;authtype=;" // Populate this for your environment ICrmPlusPlus crmPlusPlus = CrmPlusPlus.ForTenant(myConnectionString); ICrmPlusPlusCustomizationClient customizationClient = crmPlusPlus.GetCustomizationClientForSolution(PublisherSettings.Default, SolutionSettings.Default); ICrmPlusPlusEntityClient entityClient = crmPlusPlus.EntityClient; ``` * Design your entities in code: ``` using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; [EntityName("new_myentity")] [EntityInfo("My Entity", EntityAttributes.Metadata.OwnershipType.OrganizationOwned)] public class MyEntity : CrmPlusPlusEntity { [PropertyName("new_mystring")] [PropertyInfo("My String", EntityAttributes.Metadata.AttributeRequiredLevel.ApplicationRequired)] [String(255, EntityAttributes.Metadata.StringFormatName.Text)] public string MyString { get; set; } // Add more properties... } ``` * Create it in CRM if it's not there already ``` customizationClient.CreateEntity<MyEntity>(); // Create a specific property customizationClient.CreateProperty<MyEntity>(e => e.MyString); // ... Or just create all of them customizationClient.CreateAllProperties<MyEntity>(); ``` * Manipulate entity data: ``` // Create a record var data = new MyEntity(); entityClient.Create(data); // Update it data.MyString = "Updating it now..."; entityClient.Update(data); // Delete it entityClient.Delete(data); ``` * Query for records: ``` // Get an individual record var retrieval = Retrieval .ForEntity<MyEntity>(data.Id) .Include(e => e.MyString); data = entityClient.Retrieve(retrieval); // Or query for multiple var query = Query.ForEntity<MyEntity>() .Include(e => e.MyString) .Filter(FilterType.And, filter => { filter.Condition(e => e.MyString, ConditionOperator.Equal, "Updating it now..."); }); IEnumerable<MyEntity> queryResults = entityClient.RetrieveMultiple(query); ``` ### How do I get set up? ### Download the source and build in visual studio. The CRM SDK is included in the solution nuget packages, so ensure this and other nuget packages are restored before or as part of the build. * How to run tests Run tests using the Visual Studio Test runner - tests are in XUnit.NET and will be discoverable once XUnit nuget packages are restored. For the integration test project, use an instance of CRM to run the tests against. The connection string is configurable in the app.config for this project<file_sep>/Civica.CrmPlusPlus.Sdk/Client/Association/Associate.cs using System; using System.Collections.Generic; using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus.Sdk.Client.Association { public class Associate { internal Dictionary<Guid, string> RelatedEntities { get; private set; } internal Guid EntityId { get; } internal string EntityName { get; } private Associate(Guid entityId, string entityName) { EntityName = entityName; EntityId = entityId; RelatedEntities = new Dictionary<Guid, string>(); } public static Associate ThisEntity<T>(T entity) where T : CrmPlusPlusEntity, new() { var entityName = EntityNameAttribute.GetFromType<T>(); return new Associate(entity.Id, entityName); } public Associate With<TRelatedEntity>(TRelatedEntity entity) where TRelatedEntity : CrmPlusPlusEntity, new() { RelatedEntities.Add(entity.Id, EntityNameAttribute.GetFromType<TRelatedEntity>()); return this; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/LabelExtensions.cs using Microsoft.Xrm.Sdk; namespace Civica.CrmPlusPlus.Sdk { internal static class LabelExtensions { internal static Label ToLabel(this string s) { return new Label(s, 1033); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/PropertyTypes/OptionSetAttribute.cs using System; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class OptionSetAttribute : Attribute { } } <file_sep>/Civica.CrmPlusPlus.Sdk/ICrmPlusPlus.cs using Civica.CrmPlusPlus.Sdk.Client; using Civica.CrmPlusPlus.Sdk.Settings; namespace Civica.CrmPlusPlus.Sdk { public interface ICrmPlusPlus { ICrmPlusPlusEntityClient EntityClient { get; } ICrmPlusPlusCustomizationClient GetCustomizationClientForSolution(PublisherSettings publisherSettings, SolutionSettings solutionSettings); } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/Metadata/ImeMode.cs namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata { public enum ImeMode { Auto = 0, Inactive = 1, Active = 2, Disabled = 3 } } <file_sep>/Civica.CrmPlusPlus.Sdk/AttributeCollectionExtensions.cs using System.Collections.Generic; using System.ComponentModel; namespace Civica.CrmPlusPlus.Sdk { internal static class AttributeCollectionExtensions { internal static IEnumerable<object> AsEnumerable(this AttributeCollection attrCollection) { var attributes = new List<object>(); foreach (var attr in attrCollection) { attributes.Add(attr); } return attributes; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/PropertyDescriptorCollectionExtensions.cs using System.Collections.Generic; using System.ComponentModel; namespace Civica.CrmPlusPlus.Sdk { internal static class PropertyDescriptorCollectionExtensions { internal static IEnumerable<PropertyDescriptor> AsEnumerable(this PropertyDescriptorCollection propertyDescriptorCollection) { var properties = new List<PropertyDescriptor>(); foreach (PropertyDescriptor property in propertyDescriptorCollection) { properties.Add(property); } return properties; } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/EnumExtensionsTests.cs using System; using Xunit; namespace Civica.CrmPlusPlus.Sdk.Tests { public class EnumExtensionsTests { [Fact] public void CanCastValueWithSameName() { var value = TestEnum1.Value1; var result = value.ToSimilarEnum<TestEnum2>(); Assert.Equal(TestEnum2.Value1, result); } [Fact] public void WhenTargetValueDoesNotExist_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => TestEnum1.Value3.ToSimilarEnum<TestEnum2>()); } } public enum TestEnum1 { Value1, Value2, Value3 } public enum TestEnum2 { Value1, Value2, Value3AndSomething } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/EntityNameAttribute.cs using System; using System.Linq; using Civica.CrmPlusPlus.Sdk.Validation; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class EntityNameAttribute : Attribute { public string EntityLogicalName { get; } public EntityNameAttribute(string entityLogicalName) { Guard.This(entityLogicalName).AgainstNullOrEmpty("CrmPlusPlusEntity should not have a null or empty logical name"); EntityLogicalName = entityLogicalName; } internal static string GetFromType(Type type) { Guard.This(type).AgainstNonCrmPlusPlusEntity(); var crmPlusPlusEntity = type.GetCustomAttributes(true) .Where(a => a.GetType() == typeof(EntityNameAttribute)); if (crmPlusPlusEntity.Any()) { return ((EntityNameAttribute)crmPlusPlusEntity.Single()).EntityLogicalName; } throw new InvalidOperationException(string.Format("Cannot retrieve entity name from type '{0}'. EntityNameAttribute not found for this type", type.Name)); } internal static string GetFromType<T>() where T : CrmPlusPlusEntity, new() { return GetFromType(typeof(T)); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Validation/GuardStringExtensions.cs using System; namespace Civica.CrmPlusPlus.Sdk.Validation { internal static class GuardStringExtensions { internal static GuardThis<string> AgainstNullOrEmpty(this GuardThis<string> guard, string customErrorMessage = null) { if (string.IsNullOrEmpty(guard.Obj)) { throw new ArgumentException(customErrorMessage != null ? customErrorMessage : "String was found to be either empty or null when it should have a value"); } return guard; } internal static GuardThis<string> AgainstSpaces(this GuardThis<string> guard, string customErrorMessage = null) { if (guard.Obj.Trim().Contains(" ")) { throw new ArgumentException(customErrorMessage != null ? customErrorMessage : "String was found to be contain white space, but white space is not allowed"); } return guard; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Validation/Guard.cs namespace Civica.CrmPlusPlus.Sdk.Validation { internal static class Guard { internal static GuardThis<T> This<T>(T obj) { return new GuardThis<T>(obj); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/CrmPlusPlusEntity.cs using System; using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus { public abstract class CrmPlusPlusEntity { [PropertyName("id")] public Guid Id { get; internal set; } [PropertyName("createdon")] public DateTime CreatedOn { get; internal set; } [PropertyName("modifiedon")] public DateTime ModifiedOn { get; internal set; } protected CrmPlusPlusEntity(Guid? id = null) { Id = id.HasValue ? id.Value : Guid.NewGuid(); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/PropertyTypes/DateTimeAttribute.cs using System; using Microsoft.Xrm.Sdk.Metadata; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class DateTimeAttribute : Attribute { public DateTimeFormat Format { get; } public ImeMode ImeMode { get; } public DateTimeAttribute(Metadata.DateTimeFormat format, Metadata.ImeMode mode = Metadata.ImeMode.Disabled) { Format = format.ToSimilarEnum<DateTimeFormat>(); ImeMode = mode.ToSimilarEnum<ImeMode>(); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Validation/GuardThis.cs using System; namespace Civica.CrmPlusPlus.Sdk.Validation { internal class GuardThis<T> { internal T Obj { get; private set; } internal GuardThis(T obj) { Obj = obj; } internal GuardThis<T> CustomRule(Func<T, bool> guardFunc, string customErrorMessage = null) { if (!guardFunc(Obj)) { throw new ArgumentException(customErrorMessage == null ? string.Format("A validation error occured for type '{0}'", typeof(T).Name) : customErrorMessage); } return this; } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/Association/AssociateTests.cs using System.Linq; using Civica.CrmPlusPlus.Sdk.Client.Association; using Xunit; namespace Civica.CrmPlusPlus.Sdk.Tests.Client.Association { public class AssociateTests { [Fact] public void WhenAssociatingAnEntity_ItsIdShouldBePartOfTheAssociation() { var testEntityToBeAssociated = new TestEntityToBeAssociated(); var testAssociatedEntity = new TestAssociatedEntity(); var association = Associate.ThisEntity(testEntityToBeAssociated) .With(testAssociatedEntity); Assert.Equal(testEntityToBeAssociated.Id, association.EntityId); } [Fact] public void WhenAssociatingAnEntity_ItsEntityNameShouldBePartOfTheAssociation() { var testEntityToBeAssociated = new TestEntityToBeAssociated(); var testAssociatedEntity = new TestAssociatedEntity(); var association = Associate.ThisEntity(testEntityToBeAssociated) .With(testAssociatedEntity); Assert.Equal("test_entitytobeassociated", association.EntityName); } [Fact] public void WhenAssociatingAnEntity_ItsRelatedEntityIdShouldBePartOfTheAssociation() { var testEntityToBeAssociated = new TestEntityToBeAssociated(); var testAssociatedEntity = new TestAssociatedEntity(); var association = Associate.ThisEntity(testEntityToBeAssociated) .With(testAssociatedEntity); Assert.Equal(testAssociatedEntity.Id, association.RelatedEntities.Single().Key); } [Fact] public void WhenAssociatingAnEntity_ItsRelatedEntityNameShouldBePartOfTheAssociation() { var testEntityToBeAssociated = new TestEntityToBeAssociated(); var testAssociatedEntity = new TestAssociatedEntity(); var association = Associate.ThisEntity(testEntityToBeAssociated) .With(testAssociatedEntity); Assert.Equal("test_associatedentity", association.RelatedEntities.Single().Value); } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Client/EntityWithProperties.cs using System.Collections; using System.Collections.Generic; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; namespace Civica.CrmPlusPlus.Sdk.Tests.Client { [EntityName("civica_entitywithnameandinfo")] [EntityInfo("Entity with name and info", OwnershipType.OrganizationOwned)] public class EntityWithProperties : CrmPlusPlusEntity { [PropertyInfo("Test", AttributeRequiredLevel.None)] [String(100, StringFormatName.Email)] public string StringPropertyWithoutNameAttribute { get; set; } [PropertyName("civica_test")] [String(100, StringFormatName.Email)] public string StringPropertyWithoutInfoAttribute { get; set; } [PropertyName("civica_test")] [PropertyInfo("Test", AttributeRequiredLevel.None)] public string StringPropertyWithoutStringAttribute { get; set; } [PropertyName("civica_test")] [PropertyInfo("Test", AttributeRequiredLevel.None)] [String(100, StringFormatName.Email)] public string StringPropertyWithAllRequiredAttributes { get; set; } public IEnumerable<JoinedEntity> JoinedEntities { get; set; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Client/RetrieveMultiple/RelationshipType.cs namespace Civica.CrmPlusPlus.Sdk.Client.RetrieveMultiple { public enum RelationshipType { OneToMany, ManyToOne } } <file_sep>/Civica.CrmPlusPlus.Sdk/Querying/Query.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Xml.Linq; using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus.Sdk.Querying { public class Query<T> where T : CrmPlusPlusEntity, new() { private readonly Query query; private int linkedEntityDepth; internal XElement EntityRootElement { get; set; } internal Query(Query query) { this.query = query; EntityRootElement = new XElement("entity"); EntityRootElement.Add(new XAttribute("name", EntityNameAttribute.GetFromType<T>())); var createdOn = new XElement("attribute"); createdOn.Add(new XAttribute("name", "createdon")); EntityRootElement.Add(createdOn); var modifiedOn = new XElement("attribute"); modifiedOn.Add(new XAttribute("name", "modifiedon")); EntityRootElement.Add(modifiedOn); linkedEntityDepth = 0; } internal Query(Query query, string from, string to, JoinType joinType, int linkedEntityDepth) { var entityName = EntityNameAttribute.GetFromType<T>(); this.query = query; this.linkedEntityDepth = linkedEntityDepth; EntityRootElement = new XElement("link-entity"); EntityRootElement.Add(new XAttribute("name", entityName)); EntityRootElement.Add(new XAttribute("alias", entityName)); EntityRootElement.Add(new XAttribute("from", from)); EntityRootElement.Add(new XAttribute("to", to)); EntityRootElement.Add(new XAttribute("link-type", joinType.ToString().ToLower())); if (linkedEntityDepth < 2) { var createdOn = new XElement("attribute"); createdOn.Add(new XAttribute("name", "createdon")); EntityRootElement.Add(createdOn); var modifiedOn = new XElement("attribute"); modifiedOn.Add(new XAttribute("name", "modifiedon")); EntityRootElement.Add(modifiedOn); } } public Query<T> Include<TProperty>(Expression<Func<T, TProperty>> propertyExpr) { if (!EntityRootElement.Elements().Any(e => e.Name == "all-attributes")) { var propertyName = PropertyNameAttribute.GetFromType(propertyExpr); if (propertyName == "modifiedon" || propertyName == "createdon" || propertyName == "id" || linkedEntityDepth > 1) { return this; } var element = new XElement("attribute"); element.Add(new XAttribute("name", propertyName)); EntityRootElement.Add(element); } return this; } public Query<T> IncludeAllProperties() { var elementsToRemove = EntityRootElement.Elements().Where(e => e.Name == "attribute"); while (elementsToRemove.Any()) { elementsToRemove.First().Remove(); } EntityRootElement.Add(new XElement("all-attributes")); return this; } public Query<T> Filter(FilterType filterType, Action<QueryFilterBuilder<T>> filterAction) { var queryBuilder = new QueryFilterBuilder<T>(this, filterType); filterAction(queryBuilder); if (queryBuilder.RootElement.Elements().Any(e => e.Name == "condition" || e.Name == "filter")) { EntityRootElement.Add(queryBuilder.RootElement); } return this; } public Query<T> JoinNTo1<TRelatedEntity>(Expression<Func<T, EntityReference<TRelatedEntity>>> joinExpr, JoinType joinType, Action<Query<TRelatedEntity>> queryBuilder) where TRelatedEntity : CrmPlusPlusEntity, new() { var to = PropertyNameAttribute.GetFromType(joinExpr); var from = EntityNameAttribute.GetFromType<TRelatedEntity>() + "id"; var entityQuery = new Query<TRelatedEntity>(query, from, to, joinType, linkedEntityDepth + 1); queryBuilder(entityQuery); EntityRootElement.Add(entityQuery.EntityRootElement); return this; } public Query<T> Join1ToN<TRelatedEntity>(Expression<Func<T, IEnumerable<TRelatedEntity>>> joinExpr, Expression<Func<TRelatedEntity, EntityReference<T>>> toExpr, JoinType joinType, Action<Query<TRelatedEntity>> queryBuilder) where TRelatedEntity : CrmPlusPlusEntity, new() { var from = PropertyNameAttribute.GetFromType(toExpr); var to = EntityNameAttribute.GetFromType<T>() + "id" ; var entityQuery = new Query<TRelatedEntity>(query, from, to, joinType, linkedEntityDepth + 1); queryBuilder(entityQuery); EntityRootElement.Add(entityQuery.EntityRootElement); return this; } internal string ToFetchXml() { query.QueryXml.Add(EntityRootElement); return query.QueryXml.ToString() .Replace("\"", "'"); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/CrmPlusPlus.cs using System; using System.Linq; using Civica.CrmPlusPlus.Sdk.Client; using Civica.CrmPlusPlus.Sdk.DefaultEntities; using Civica.CrmPlusPlus.Sdk.Querying; using Civica.CrmPlusPlus.Sdk.Settings; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Tooling.Connector; namespace Civica.CrmPlusPlus.Sdk { public class CrmPlusPlus : ICrmPlusPlus { private readonly IOrganizationService service; public ICrmPlusPlusEntityClient EntityClient { get; } private CrmPlusPlus(IOrganizationService service) { this.service = service; EntityClient = new CrmPlusPlusEntityClient(service); } public static ICrmPlusPlus ForTenant(string connectionString) { CrmServiceClient crmConnection = null; IOrganizationService service = null; try { crmConnection = new CrmServiceClient(connectionString); service = crmConnection.OrganizationWebProxyClient != null ? crmConnection.OrganizationWebProxyClient : (IOrganizationService)crmConnection.OrganizationServiceProxy; } catch (Exception ex) { throw new ArgumentException("An error occurred whilst trying to connect to CRM with the specified connection string. See inner exception for more details", ex); } if (service == null) { throw new ArgumentException("An error occurred whilst trying to connect to CRM with the specified connection string"); } return new CrmPlusPlus(service); } public ICrmPlusPlusCustomizationClient GetCustomizationClientForSolution(PublisherSettings publisherSettings, SolutionSettings solutionSettings) { var publisherQuery = Query.ForEntity<Publisher>() .Include(e => e.DisplayName) .Include(e => e.Name) .Include(e => e.OptionValuePrefix) .Include(e => e.Prefix) .Filter(FilterType.And, filter => { filter.Condition(e => e.Name, ConditionOperator.Equal, publisherSettings.Name); }); var publisherResults = EntityClient.RetrieveMultiple(publisherQuery); Publisher publisher = null; if (!publisherResults.Any()) { publisher = new Publisher { DisplayName = publisherSettings.DisplayName, Name = publisherSettings.Name, OptionValuePrefix = publisherSettings.OptionValuePrefix, Prefix = publisherSettings.Prefix }; EntityClient.Create(publisher); } else { publisher = publisherResults.Single(); // Cannot be more than one with the same name } var solutionQuery = Query.ForEntity<Solution>() .Include(e => e.Name) .Include(e => e.DisplayName) .Include(e => e.Publisher) .Include(e => e.Version) .Filter(FilterType.And, filter => { filter.Condition(e => e.Name, ConditionOperator.Equal, solutionSettings.Name); }); var solutionResults = EntityClient.RetrieveMultiple(solutionQuery); Solution solution = null; if (!solutionResults.Any()) { solution = new Solution { Name = solutionSettings.Name, DisplayName = solutionSettings.DisplayName, Version = solutionSettings.Version, Publisher = publisher.AsEntityReference() }; EntityClient.Create(solution); } else { solution = solutionResults.Single(); // Cannot be more than one with the same name } return new CrmPlusPlusCustomizationClient(publisher, solution, service); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/Metadata/IntegerFormat.cs namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata { public enum IntegerFormat { None = 0, Duration = 1, TimeZone = 2, Language = 3, Locale = 4 } } <file_sep>/Civica.CrmPlusPlus.Sdk/Querying/QueryFilterBuilder.cs using System; using System.Linq.Expressions; using System.Xml.Linq; using Civica.CrmPlusPlus.Sdk.EntityAttributes; namespace Civica.CrmPlusPlus.Sdk.Querying { public class QueryFilterBuilder<T> where T : CrmPlusPlusEntity, new() { private readonly Query<T> query; internal XElement RootElement { get; } internal QueryFilterBuilder(Query<T> query, FilterType filterType, QueryFilterBuilder<T> parent = null) { this.query = query; RootElement = new XElement("filter"); RootElement.Add(new XAttribute("type", filterType.ToString().ToLower())); } public QueryFilterBuilder<T> Condition<TProperty>(Expression<Func<T, TProperty>> propertyExpr, ConditionOperator conditionOperator, string value) { var condition = new XElement("condition"); condition.Add(new XAttribute("attribute", PropertyNameAttribute.GetFromType(propertyExpr))); condition.Add(new XAttribute("operator", conditionOperator.Value.Trim().ToLower())); condition.Add(new XAttribute("value", value)); RootElement.Add(condition); return this; } public void InnerFilter(FilterType filterType, Action<QueryFilterBuilder<T>> filterAction) { var queryBuilder = new QueryFilterBuilder<T>(query, filterType, this); filterAction(queryBuilder); RootElement.Add(queryBuilder.RootElement); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EnumExtensions.cs using System; namespace Civica.CrmPlusPlus.Sdk { internal static class EnumExtensions { internal static TTarget ToSimilarEnum<TTarget>(this Enum sourceValue) { try { return (TTarget)Enum.Parse(typeof(TTarget), sourceValue.ToString()); } catch(Exception) { throw new InvalidOperationException(string.Format("Cannot cast value to type '{0}'", typeof(TTarget).Name)); } } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Querying/TestEntity.cs using System.Collections.Generic; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; namespace Civica.CrmPlusPlus.Sdk.Tests.Querying { [EntityName("testentity")] [EntityInfo("Test Entity", OwnershipType.UserOwned)] public class TestEntity : CrmPlusPlusEntity { [PropertyName("test")] [PropertyInfo("Test", AttributeRequiredLevel.ApplicationRequired)] [String(100, StringFormatName.Text)] public string StringTestProperty { get; set; } public IEnumerable<TestJoinedEntity> JoinedEntities { get; set; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Client/CrmPlusPlusCustomizationClient.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using Civica.CrmPlusPlus.Sdk.DefaultEntities; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; using Civica.CrmPlusPlus.Sdk.Validation; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; namespace Civica.CrmPlusPlus.Sdk.Client { public class CrmPlusPlusCustomizationClient : ICrmPlusPlusCustomizationClient { private readonly IOrganizationService service; public Solution Solution { get; } public Publisher Publisher { get; } internal CrmPlusPlusCustomizationClient(Publisher publisher, Solution solution, IOrganizationService service) { Solution = solution; Publisher = publisher; this.service = service; } public void CreateEntity<T>() where T : CrmPlusPlusEntity, new() { var entityName = EntityNameAttribute.GetFromType<T>(); var entityInfo = EntityInfoAttribute.GetFromType<T>(); var createEntityRequest = new CreateEntityRequest { Entity = new EntityMetadata { SchemaName = entityName, DisplayName = entityInfo.DisplayName.ToLabel(), DisplayCollectionName = entityInfo.PluralDisplayName.ToLabel(), Description = entityInfo.Description.ToLabel(), OwnershipType = entityInfo.OwnershipType, IsActivity = false }, PrimaryAttribute = new StringAttributeMetadata { SchemaName = entityName + "primary", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, FormatName = Microsoft.Xrm.Sdk.Metadata.StringFormatName.Text, DisplayName = "Primary attribute".ToLabel(), Description = string.Format("The primary attribute for the {0} entity", entityInfo.DisplayName).ToLabel() } }; var response = (CreateEntityResponse)service.Execute(createEntityRequest); var addReq = new AddSolutionComponentRequest() { ComponentType = (int)SolutionComponentTypes.Entity, ComponentId = response.EntityId, SolutionUniqueName = Solution.Name }; service.Execute(addReq); } public void CreateProperty<T, TProperty>(Expression<Func<T, TProperty>> propertyExpr) where T : CrmPlusPlusEntity, new() { var entityName = EntityNameAttribute.GetFromType<T>(); var propertyName = PropertyNameAttribute.GetFromType(propertyExpr); var propertyInfo = PropertyInfoAttribute.GetFromType(propertyExpr); var attributes = ((MemberExpression)propertyExpr.Body).Member.GetCustomAttributes(true); CreateProperty(entityName, typeof(TProperty), attributes, propertyName, propertyInfo); } public void CreateAllProperties<T>() where T : CrmPlusPlusEntity, new() { var entityName = EntityNameAttribute.GetFromType<T>(); foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(typeof(T))) { var attributes = new List<object>(); foreach (var attribute in property.Attributes) { attributes.Add(attribute); } var propertyNameAttribute = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyNameAttribute)); var propertyInfoAttribute = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyInfoAttribute)); if (propertyNameAttribute != null && propertyInfoAttribute != null) { var name = (PropertyNameAttribute)propertyNameAttribute; var info = (PropertyInfoAttribute)propertyInfoAttribute; CreateProperty(entityName, property.PropertyType, attributes, name.PropertyName, info); } } } public void Delete<T>() where T : CrmPlusPlusEntity, new() { var entityName = EntityNameAttribute.GetFromType<T>(); var deleteEntityRequest = new DeleteEntityRequest { LogicalName = entityName }; service.Execute(deleteEntityRequest); } private void CreateProperty(string entityName, Type propertyType, IEnumerable<object> attributes, string propertyName, PropertyInfoAttribute info) { var createAttributeRequest = new CreateAttributeRequest() { EntityName = entityName }; if (propertyType == typeof(string)) { var attrInfo = attributes.SingleOrDefault(attr => attr.GetType() == typeof(StringAttribute)); if (attrInfo != null) { var stringInfo = (StringAttribute)attrInfo; createAttributeRequest.Attribute = new StringAttributeMetadata { SchemaName = propertyName, RequiredLevel = new AttributeRequiredLevelManagedProperty(info.AttributeRequiredLevel), DisplayName = info.DisplayName.ToLabel(), Description = info.Description.ToLabel(), MaxLength = stringInfo.MaxLength, FormatName = stringInfo.StringFormat }; service.Execute(createAttributeRequest); } } else if (propertyType == typeof(bool)) { var attrInfo = attributes.SingleOrDefault(attr => attr.GetType() == typeof(BooleanAttribute)); if (attrInfo != null) { var booleanAttr = (BooleanAttribute)attrInfo; createAttributeRequest.Attribute = new BooleanAttributeMetadata { SchemaName = propertyName, RequiredLevel = new AttributeRequiredLevelManagedProperty(info.AttributeRequiredLevel), DisplayName = info.DisplayName.ToLabel(), Description = info.Description.ToLabel(), OptionSet = new BooleanOptionSetMetadata( new OptionMetadata("True".ToLabel(), 1), new OptionMetadata("False".ToLabel(), 0)), }; } service.Execute(createAttributeRequest); } else if (propertyType == typeof(DateTime)) { var attrInfo = attributes.SingleOrDefault(attr => attr.GetType() == typeof(DateTimeAttribute)); if (attrInfo != null) { var dateTimeInfo = (DateTimeAttribute)attrInfo; createAttributeRequest.Attribute = new DateTimeAttributeMetadata { SchemaName = propertyName, RequiredLevel = new AttributeRequiredLevelManagedProperty(info.AttributeRequiredLevel), DisplayName = info.DisplayName.ToLabel(), Description = info.Description.ToLabel(), Format = dateTimeInfo.Format, ImeMode = dateTimeInfo.ImeMode }; } service.Execute(createAttributeRequest); } else if (propertyType == typeof(decimal)) { var attrInfo = attributes.SingleOrDefault(attr => attr.GetType() == typeof(DecimalAttribute)); if (attrInfo != null) { var decimalInfo = (DecimalAttribute)attrInfo; createAttributeRequest.Attribute = new DecimalAttributeMetadata { SchemaName = propertyName, RequiredLevel = new AttributeRequiredLevelManagedProperty(info.AttributeRequiredLevel), DisplayName = info.DisplayName.ToLabel(), Description = info.Description.ToLabel(), MaxValue = decimalInfo.MaxValue, MinValue = decimalInfo.MinValue, Precision = decimalInfo.Precision }; } service.Execute(createAttributeRequest); } else if (propertyType == typeof(double)) { var attrInfo = attributes.SingleOrDefault(attr => attr.GetType() == typeof(DoubleAttribute)); if (attrInfo != null) { var decimalInfo = (DoubleAttribute)attrInfo; createAttributeRequest.Attribute = new DoubleAttributeMetadata { SchemaName = propertyName, RequiredLevel = new AttributeRequiredLevelManagedProperty(info.AttributeRequiredLevel), DisplayName = info.DisplayName.ToLabel(), Description = info.Description.ToLabel(), MaxValue = decimalInfo.MaxValue, MinValue = decimalInfo.MinValue, Precision = decimalInfo.Precision }; } service.Execute(createAttributeRequest); } else if (propertyType == typeof(int)) { var attrInfo = attributes.SingleOrDefault(attr => attr.GetType() == typeof(IntegerAttribute)); if (attrInfo != null) { var integerInfo = (IntegerAttribute)attrInfo; createAttributeRequest.Attribute = new IntegerAttributeMetadata { SchemaName = propertyName, RequiredLevel = new AttributeRequiredLevelManagedProperty(info.AttributeRequiredLevel), DisplayName = info.DisplayName.ToLabel(), Description = info.Description.ToLabel(), MaxValue = integerInfo.MaxValue, MinValue = integerInfo.MinValue, Format = integerInfo.Format }; } service.Execute(createAttributeRequest); } else if (propertyType.IsEnum) { var attrInfo = attributes.SingleOrDefault(attr => attr.GetType() == typeof(OptionSetAttribute)); if (attrInfo != null) { var options = new OptionMetadataCollection(); foreach (var value in Enum.GetValues(propertyType)) { options.Add(new OptionMetadata(value.ToString().ToLabel(), (int)value)); } createAttributeRequest.Attribute = new PicklistAttributeMetadata { SchemaName = propertyName, RequiredLevel = new AttributeRequiredLevelManagedProperty(info.AttributeRequiredLevel), DisplayName = info.DisplayName.ToLabel(), Description = info.Description.ToLabel(), OptionSet = new OptionSetMetadata(options) { IsGlobal = false, DisplayName = info.DisplayName.ToLabel(), Description = info.Description.ToLabel(), IsCustomOptionSet = true, OptionSetType = OptionSetType.Picklist, Name = propertyName } }; service.Execute(createAttributeRequest); } } } public bool CanCreateOneToManyRelationship<TOne, TMany>() where TOne : CrmPlusPlusEntity, new() where TMany : CrmPlusPlusEntity, new() { var canBeReferencedRequest = new CanBeReferencedRequest { EntityName = EntityNameAttribute.GetFromType<TOne>() }; var canBeReferencingRequest = new CanBeReferencingRequest { EntityName = EntityNameAttribute.GetFromType<TMany>() }; bool canBeReferenced = ((CanBeReferencedResponse)service.Execute(canBeReferencedRequest)).CanBeReferenced; bool canBeReferencing = ((CanBeReferencingResponse)service.Execute(canBeReferencingRequest)).CanBeReferencing; return canBeReferenced && canBeReferencing; } public void CreateOneToManyRelationship<TOne, TMany>(Expression<Func<TMany, EntityReference<TOne>>> lookupExpr, EntityAttributes.Metadata.AttributeRequiredLevel lookupRequiredLevel, string relationshipPrefix = "new") where TOne : CrmPlusPlusEntity, new() where TMany : CrmPlusPlusEntity, new() { Guard.This(relationshipPrefix).AgainstNullOrEmpty(); var oneEntityName = EntityNameAttribute.GetFromType<TOne>(); var manyEntityName = EntityNameAttribute.GetFromType<TMany>(); var oneDisplayName = EntityInfoAttribute.GetFromType<TOne>().DisplayName; var lookupPropertyName = PropertyNameAttribute.GetFromType(lookupExpr); var oneToManyRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = oneEntityName, ReferencingEntity = manyEntityName, SchemaName = relationshipPrefix.EndsWith("_") ? relationshipPrefix : relationshipPrefix + "_" + oneEntityName + "_" + manyEntityName, AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = oneDisplayName.ToLabel(), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = lookupPropertyName, DisplayName = (oneDisplayName + " Lookup").ToLabel(), RequiredLevel = new AttributeRequiredLevelManagedProperty(lookupRequiredLevel.ToSimilarEnum<AttributeRequiredLevel>()), Description = (oneDisplayName + " Lookup").ToLabel() } }; service.Execute(oneToManyRequest); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/Querying/ConditionOperator.cs namespace Civica.CrmPlusPlus.Sdk.Querying { public class ConditionOperator { internal string Value { get; } private ConditionOperator(string value) { Value = value; } public static ConditionOperator Equal { get { return new ConditionOperator("eq"); } } public static ConditionOperator GreaterThanOrEqual { get { return new ConditionOperator("ge"); } } public static ConditionOperator GreaterThan { get { return new ConditionOperator("gt"); } } public static ConditionOperator LessThan { get { return new ConditionOperator("lt"); } } public static ConditionOperator Like { get { return new ConditionOperator("like"); } } public static ConditionOperator Between { get { return new ConditionOperator("between"); } } public static ConditionOperator EqualBusinessId { get { return new ConditionOperator("eq-businessid"); } } public static ConditionOperator EqualUserId { get { return new ConditionOperator("eq-userid"); } } public static ConditionOperator EqualUserTeams { get { return new ConditionOperator("eq-userteams"); } } public static ConditionOperator In { get { return new ConditionOperator("in"); } } public static ConditionOperator InFiscalPeriod { get { return new ConditionOperator("in-fiscal-period"); } } public static ConditionOperator InFiscalPeriodAndYear { get { return new ConditionOperator("in-fiscal-period-and-year"); } } public static ConditionOperator InFiscalYear { get { return new ConditionOperator("in-fiscal-year"); } } public static ConditionOperator InOrAfterFiscalPeriodAndYear { get { return new ConditionOperator("in-or-after-fiscal-period-and-year"); } } public static ConditionOperator InOrBeforeFiscalPeriodAndYear { get { return new ConditionOperator("in-or-before-fiscal-period-and-year"); } } public static ConditionOperator Last7Days { get { return new ConditionOperator("last-seven-days"); } } public static ConditionOperator LastFiscalPeriod { get { return new ConditionOperator("last-fiscal-period"); } } public static ConditionOperator LastFiscalYear { get { return new ConditionOperator("last-fiscal-year"); } } public static ConditionOperator LastMonth { get { return new ConditionOperator("last-month"); } } public static ConditionOperator LastWeek { get { return new ConditionOperator("last-week"); } } public static ConditionOperator LastXDays { get { return new ConditionOperator("last-x-days"); } } public static ConditionOperator LastXFiscalPeriods { get { return new ConditionOperator("last-x-fiscal-periods"); } } public static ConditionOperator LastXFiscalYears { get { return new ConditionOperator("last-x-fiscal-years"); } } public static ConditionOperator LastXHours { get { return new ConditionOperator("last-x-hours"); } } public static ConditionOperator LastXMonths { get { return new ConditionOperator("last-x-months"); } } public static ConditionOperator LastXWeeks { get { return new ConditionOperator("last-x-weeks"); } } public static ConditionOperator LastXYears { get { return new ConditionOperator("last-x-years"); } } public static ConditionOperator LastYear { get { return new ConditionOperator("last-year"); } } public static ConditionOperator LessThanOrEqual { get { return new ConditionOperator("le"); } } public static ConditionOperator Next7Days { get { return new ConditionOperator("next-seven-days"); } } public static ConditionOperator NextFiscalPeriod { get { return new ConditionOperator("next-fiscal-period"); } } public static ConditionOperator NextFiscalYear { get { return new ConditionOperator("next-fiscal-year"); } } public static ConditionOperator NextMonth { get { return new ConditionOperator("next-month"); } } public static ConditionOperator NextWeek { get { return new ConditionOperator("next-week"); } } public static ConditionOperator NextXDays { get { return new ConditionOperator("next-x-days"); } } public static ConditionOperator NextXFiscalPeriods { get { return new ConditionOperator("next-x-fiscal-periods"); } } public static ConditionOperator NextXFiscalYears { get { return new ConditionOperator("next-x-fiscal-years"); } } public static ConditionOperator NextXHours { get { return new ConditionOperator("next-x-hours"); } } public static ConditionOperator NextXMonths { get { return new ConditionOperator("next-x-months"); } } public static ConditionOperator NextXWeeks { get { return new ConditionOperator("next-x-weeks"); } } public static ConditionOperator NextXYears { get { return new ConditionOperator("next-x-years"); } } public static ConditionOperator NextYear { get { return new ConditionOperator("next-year"); } } public static ConditionOperator NotBetween { get { return new ConditionOperator("not-between"); } } public static ConditionOperator NotEqual { get { return new ConditionOperator("ne"); } } public static ConditionOperator NotEqualBusinessId { get { return new ConditionOperator("ne-businessid"); } } public static ConditionOperator NotEqualUserId { get { return new ConditionOperator("ne-userid"); } } public static ConditionOperator NotIn { get { return new ConditionOperator("not-in"); } } public static ConditionOperator NotLike { get { return new ConditionOperator("not-like"); } } public static ConditionOperator NotNull { get { return new ConditionOperator("not-null"); } } public static ConditionOperator NotOn { get { return new ConditionOperator("ne"); } } public static ConditionOperator Null { get { return new ConditionOperator("null"); } } public static ConditionOperator OlderThanXMonths { get { return new ConditionOperator("olderthan-x-months"); } } public static ConditionOperator On { get { return new ConditionOperator("on"); } } public static ConditionOperator OnOrAfter { get { return new ConditionOperator("on-or-after"); } } public static ConditionOperator OnOrBefore { get { return new ConditionOperator("on-or-before"); } } public static ConditionOperator ThisFiscalPeriod { get { return new ConditionOperator("this-fiscal-period"); } } public static ConditionOperator ThisFiscalYear { get { return new ConditionOperator("this-fiscal-year"); } } public static ConditionOperator ThisMonth { get { return new ConditionOperator("this-month"); } } public static ConditionOperator ThisWeek { get { return new ConditionOperator("this-week"); } } public static ConditionOperator ThisYear { get { return new ConditionOperator("this-year"); } } public static ConditionOperator Today { get { return new ConditionOperator("today"); } } public static ConditionOperator Tomorrow { get { return new ConditionOperator("tomorrow"); } } public static ConditionOperator Yesterday { get { return new ConditionOperator("yesterday"); } } } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Querying/TestJoinedEntity.cs using System.Collections.Generic; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; namespace Civica.CrmPlusPlus.Sdk.Tests.Querying { [EntityName("testjoinedentity")] [EntityInfo("Test Joined Entity", OwnershipType.UserOwned)] public class TestJoinedEntity : CrmPlusPlusEntity { [PropertyName("testlookupname")] [PropertyInfo("Test lookup", AttributeRequiredLevel.Recommended)] [Lookup] public EntityReference<TestEntity> TestEntityId { get; set; } [PropertyName("testnumber")] [PropertyInfo("Test Number", AttributeRequiredLevel.None)] [Integer(100, 0, IntegerFormat.None)] public int Number { get; set; } public IEnumerable<TestNestedJoinedEntity> NestedJoinedEntities { get; set; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityExtensions.cs using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Civica.CrmPlusPlus.Sdk.EntityAttributes; using Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes; using Microsoft.Xrm.Sdk; namespace Civica.CrmPlusPlus.Sdk { internal static class EntityExtensions { internal static CrmPlusPlusEntity ToCrmPlusPlusEntity(this Entity entity, Type crmPlusPlusEntityType, string alias = "") { var crmPlusPlusEntity = (CrmPlusPlusEntity)Activator.CreateInstance(crmPlusPlusEntityType); crmPlusPlusEntity.Id = entity.Id; if (!string.IsNullOrEmpty(alias) && !alias.EndsWith(".")) { alias = alias + "."; } if (alias == string.Empty) { crmPlusPlusEntity.CreatedOn = entity.Contains("createdon") ? DateTime.Parse(entity["createdon"].ToString()) : DateTime.MinValue; crmPlusPlusEntity.ModifiedOn = entity.Contains("modifiedon") ? DateTime.Parse(entity["modifiedon"].ToString()) : DateTime.MinValue; } else { crmPlusPlusEntity.Id = entity.Contains(alias + "id") ? (Guid)((AliasedValue)entity[alias + "id"]).Value : crmPlusPlusEntity.Id; crmPlusPlusEntity.CreatedOn = entity.Contains(alias + "createdon") ? DateTime.Parse(((AliasedValue)entity[alias + "createdon"]).Value.ToString()) : DateTime.MinValue; crmPlusPlusEntity.ModifiedOn = entity.Contains(alias + "modifiedon") ? DateTime.Parse(((AliasedValue)entity[alias + "modifiedon"]).Value.ToString()) : DateTime.MinValue; } foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(crmPlusPlusEntityType)) { if (property.Name == "ModifedOn" || property.Name == "CreatedOn") { continue; } var attributes = property.Attributes.AsEnumerable(); var propertyNameAttr = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyNameAttribute)); var propertyInfoAttr = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyInfoAttribute)); var typeInfoAttr = attributes .SingleOrDefault(attr => (attr.GetType() == typeof(BooleanAttribute) && property.PropertyType == typeof(bool)) || (attr.GetType() == typeof(DateTimeAttribute) && property.PropertyType == typeof(DateTime)) || (attr.GetType() == typeof(DecimalAttribute) && property.PropertyType == typeof(decimal)) || (attr.GetType() == typeof(DoubleAttribute) && property.PropertyType == typeof(double)) || (attr.GetType() == typeof(IntegerAttribute) && property.PropertyType == typeof(int)) || (attr.GetType() == typeof(StringAttribute) && property.PropertyType == typeof(string)) || (attr.GetType() == typeof(OptionSetAttribute) && property.PropertyType.IsEnum) || (attr.GetType() == typeof(LookupAttribute) && property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>))); if (propertyNameAttr != null && propertyInfoAttr != null && typeInfoAttr != null) { var propertyName = ((PropertyNameAttribute)propertyNameAttr).PropertyName; if (entity.Contains(alias + propertyName)) { object value = null; if (alias == string.Empty) { value = entity[propertyName]; } else { value = ((AliasedValue)entity[alias + propertyName]).Value; } if (value.GetType() == typeof(EntityReference)) { var referenceEntityName = property.PropertyType.GetGenericArguments().Single(); var entityReferenceType = typeof(EntityReference<>).MakeGenericType(referenceEntityName); value = Activator.CreateInstance(entityReferenceType, new object[] { ((Microsoft.Xrm.Sdk.EntityReference)value).Id }); } else if (value.GetType() == typeof(OptionSetValue)) { var integerOptionValue = ((OptionSetValue)value).Value; value = integerOptionValue; } property.SetValue(crmPlusPlusEntity, value); } } } return crmPlusPlusEntity; } internal static T ToCrmPlusPlusEntity<T>(this Microsoft.Xrm.Sdk.Entity entity, string alias = "") where T : CrmPlusPlusEntity, new() { return (T)ToCrmPlusPlusEntity(entity, typeof(T), alias); } internal static IEnumerable<Entity> WhereEntitiesHaveKeyThatContains(this IEnumerable<Entity> entities, string substringOfKey) { var filteredEntities = new List<Entity>(); foreach (var entity in entities) { var keys = entity.Attributes.Keys; if (keys.Any(k => k.Contains(substringOfKey))) { filteredEntities.Add(entity); } } return filteredEntities; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/PropertyTypes/LookupAttribute.cs using System; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.PropertyTypes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class LookupAttribute : Attribute { } } <file_sep>/Civica.CrmPlusPlus.Sdk.Tests/Querying/QueryTests.cs using Civica.CrmPlusPlus.Sdk.Querying; using Xunit; namespace Civica.CrmPlusPlus.Sdk.Tests.Querying { public class QueryTests { [Fact] public void QueryForTestEntity_WithoutProperties_ShouldIncludeCreatedOnAndModifiedON() { var fetchXml = Query .ForEntity<TestEntity>() .ToFetchXml() .ClearXmlFormatting(); Assert.Equal("<fetch mapping='logical' distinct='false'><entity name='testentity'><attribute name='createdon'/><attribute name='modifiedon'/></entity></fetch>", fetchXml); } [Fact] public void QueryWithIncludedProperty_FormsFetchXmlCorrectly() { var fetchXml = Query .ForEntity<TestEntity>() .Include(e => e.StringTestProperty) .ToFetchXml() .ClearXmlFormatting(); Assert.Equal("<fetch mapping='logical' distinct='false'><entity name='testentity'><attribute name='createdon'/><attribute name='modifiedon'/><attribute name='test'/></entity></fetch>", fetchXml); } [Fact] public void QueryWithEmptyFilter_DoesNotIncludeFilterInFetchXml() { var fetchXml = Query .ForEntity<TestEntity>() .Filter(FilterType.And, filter => { }) .ToFetchXml() .ClearXmlFormatting(); var expected = @"<fetch mapping='logical' distinct='false'> <entity name='testentity'> <attribute name='createdon'/> <attribute name='modifiedon'/> </entity> </fetch>"; Assert.Equal(expected.ClearXmlFormatting(), fetchXml); } [Fact] public void QueryWithOneFilterCondition_FormsFetchXmlCorrectly() { var fetchXml = Query .ForEntity<TestEntity>() .Filter(FilterType.And, filter => { filter.Condition(e => e.StringTestProperty, ConditionOperator.Equal, "Value"); }) .ToFetchXml() .ClearXmlFormatting(); var expected = @"<fetch mapping='logical' distinct='false'> <entity name='testentity'> <attribute name='createdon'/> <attribute name='modifiedon'/> <filter type='and'> <condition attribute='test' operator='eq' value='Value'/> </filter> </entity> </fetch>"; Assert.Equal(expected.ClearXmlFormatting(), fetchXml); } [Fact] public void QueryWithMultipleLayeredFilterConditions_FormsFetchXmlCorrectly() { var fetchXml = Query .ForEntity<TestEntity>() .Filter(FilterType.Or, filter => { filter.InnerFilter(FilterType.And, innerFilter => { innerFilter.Condition(e => e.StringTestProperty, ConditionOperator.Equal, "Value1"); innerFilter.Condition(e => e.ModifiedOn, ConditionOperator.LessThanOrEqual, "2017-01-01"); }); filter.InnerFilter(FilterType.And, innerFilter => { innerFilter.Condition(e => e.StringTestProperty, ConditionOperator.Equal, "Value2"); innerFilter.Condition(e => e.CreatedOn, ConditionOperator.LessThanOrEqual, "2016-01-01"); }); }) .ToFetchXml() .ClearXmlFormatting(); var expected = @"<fetch mapping='logical' distinct='false'> <entity name='testentity'> <attribute name='createdon'/> <attribute name='modifiedon'/> <filter type='or'> <filter type='and'> <condition attribute='test' operator='eq' value='Value1'/> <condition attribute='modifiedon' operator='le' value='2017-01-01'/> </filter> <filter type='and'> <condition attribute='test' operator='eq' value='Value2'/> <condition attribute='createdon' operator='le' value='2016-01-01'/> </filter> </filter> </entity> </fetch>"; Assert.Equal(expected.ClearXmlFormatting(), fetchXml); } [Fact] public void QueryWith1ToNJoinedEntities_FormsXmlCorrectly() { var fetchXml = Query.ForEntity<TestEntity>() .Join1ToN(e => e.JoinedEntities, e => e.TestEntityId, JoinType.Outer, query => { query.Include(e => e.Number); }) .ToFetchXml() .ClearXmlFormatting(); var expected = @"<fetch mapping='logical' distinct='false'> <entity name='testentity'> <attribute name='createdon'/> <attribute name='modifiedon'/> <link-entity name='testjoinedentity' alias='testjoinedentity' from='testlookupname' to='testentityid' link-type='outer'> <attribute name='createdon'/> <attribute name='modifiedon'/> <attribute name='testnumber'/> </link-entity> </entity> </fetch>"; Assert.Equal(expected.ClearXmlFormatting(), fetchXml); } [Fact] public void QueryWithNTo1JoinedEntities_FormsXmlCorrectly() { var fetchXml = Query.ForEntity<TestJoinedEntity>() .JoinNTo1(e => e.TestEntityId, JoinType.Outer, query => { query.Include(e => e.StringTestProperty); }) .ToFetchXml() .ClearXmlFormatting(); var expected = @"<fetch mapping='logical' distinct='false'> <entity name='testjoinedentity'> <attribute name='createdon'/> <attribute name='modifiedon'/> <link-entity name='testentity' alias='testentity' from='testentityid' to='testlookupname' link-type='outer'> <attribute name='createdon'/> <attribute name='modifiedon'/> <attribute name='test'/> </link-entity> </entity> </fetch>"; Assert.Equal(expected.ClearXmlFormatting(), fetchXml); } [Fact] public void QueryIncludingAllAttributes_AfterIncludingSingleAttribute_RemoveSingleAttributeXml() { var query = Query.ForEntity<TestEntity>() .Include(e => e.StringTestProperty) .IncludeAllProperties() .ToFetchXml() .ClearXmlFormatting(); Assert.DoesNotContain("<attribute name='test'/>", query); } [Fact] public void QueryIncludingSingleAttribute_AfterIncludingAllAttributes_DoesNothing() { var queryWithoutSingleInclusion = Query.ForEntity<TestEntity>() .IncludeAllProperties() .ToFetchXml() .ClearXmlFormatting(); var queryWithSingleInclusion = Query.ForEntity<TestEntity>() .IncludeAllProperties() .Include(e => e.StringTestProperty) .ToFetchXml() .ClearXmlFormatting(); Assert.Equal(queryWithoutSingleInclusion, queryWithSingleInclusion); } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/Metadata/OwnershipType.cs namespace Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata { public enum OwnershipType { None = 0, UserOwned = 1, TeamOwned = 2, BusinessOwned = 4, OrganizationOwned = 8, BusinessParented = 16 } } <file_sep>/Civica.CrmPlusPlus.Sdk/Client/ICrmPlusPlusCustomizationClient.cs using System; using System.Linq.Expressions; using Civica.CrmPlusPlus.Sdk.DefaultEntities; namespace Civica.CrmPlusPlus.Sdk.Client { public interface ICrmPlusPlusCustomizationClient { Solution Solution { get; } Publisher Publisher { get; } bool CanCreateOneToManyRelationship<TOne, TMany>() where TOne : CrmPlusPlusEntity, new() where TMany : CrmPlusPlusEntity, new(); void CreateOneToManyRelationship<TOne, TMany>(Expression<Func<TMany, EntityReference<TOne>>> lookupExpr, EntityAttributes.Metadata.AttributeRequiredLevel lookupRequiredLevel, string relationshipPrefix = "new") where TOne : CrmPlusPlusEntity, new() where TMany : CrmPlusPlusEntity, new(); void CreateEntity<T>() where T : CrmPlusPlusEntity, new(); void CreateProperty<T, TProperty>(Expression<Func<T, TProperty>> propertyExpr) where T : CrmPlusPlusEntity, new(); void CreateAllProperties<T>() where T : CrmPlusPlusEntity, new(); void Delete<T>() where T : CrmPlusPlusEntity, new(); } } <file_sep>/Civica.CrmPlusPlus.Sdk/Validation/GuardCrmPlusPlusEntityExtensions.cs using System; using System.Linq.Expressions; namespace Civica.CrmPlusPlus.Sdk.Validation { internal static class GuardCrmPlusPlusEntityExtensions { internal static GuardThis<Type> AgainstNonCrmPlusPlusEntity(this GuardThis<Type> guard) { if (!typeof(CrmPlusPlusEntity).IsAssignableFrom(guard.Obj)) { throw new ArgumentException("Type was expected to be CrmPlusPlusEntity but it was not"); } return guard; } } } <file_sep>/Civica.CrmPlusPlus.Sdk/EntityAttributes/EntityInfoAttribute.cs using System; using System.Linq; using Civica.CrmPlusPlus.Sdk.EntityAttributes.Metadata; using Civica.CrmPlusPlus.Sdk.Validation; using Microsoft.Xrm.Sdk.Metadata; namespace Civica.CrmPlusPlus.Sdk.EntityAttributes { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class EntityInfoAttribute : Attribute { public string DisplayName { get; } public OwnershipTypes OwnershipType { get; } public string PluralDisplayName { get; } public string Description { get; } public EntityInfoAttribute(string displayName, OwnershipType ownershipType, string pluralDisplayName = null, string description = null) { Guard.This(displayName).AgainstNullOrEmpty(); DisplayName = displayName; OwnershipType = ownershipType.ToSimilarEnum<OwnershipTypes>(); PluralDisplayName = string.IsNullOrEmpty(pluralDisplayName) ? displayName + "s" : pluralDisplayName; Description = string.IsNullOrEmpty(description) ? displayName : description; } internal static EntityInfoAttribute GetFromType<T>() where T : CrmPlusPlusEntity, new() { var crmPlusPlusEntity = typeof(T).GetCustomAttributes(true) .Where(a => a.GetType() == typeof(EntityInfoAttribute)); if (crmPlusPlusEntity.Any()) { return (EntityInfoAttribute)crmPlusPlusEntity.Single(); } throw new InvalidOperationException(string.Format("Cannot retrieve entity info from type '{0}'. EntityInfoAttribute not found for this type", typeof(T).Name)); } } }
32f0b21d2ac88c03428b9323cf513cad75b6d0e8
[ "Markdown", "C#" ]
68
C#
SFWLtd/crm-plus-plus
172da7d46797f9842dfefaec92b46832248defa0
967cc0d5ce3eb09a552272040cc451adb8334cc0
refs/heads/master
<file_sep># MozartMusicalDice https://www.reddit.com/r/dailyprogrammer/comments/7i1ib1/20171206_challenge_343_intermediate_mozarts/ <file_sep>import random import webbrowser file = open("getmeasures.txt") text = file.readlines() measures = [] for i in text: arr = i.split() rand = random.randint(1,11) measures.append(arr[rand - 1]) file2 = open("notes.txt") text2 = file2.readlines() output = open("output.txt", 'w+') output.truncate() print(measures) measurecount = 0 for j in measures: for i in text2: arr = i.split() beat = arr[1] if float(beat) >= ((float(j)*3) - 3) and float(beat) < (float(j)*3): arr[1] = str((float(beat) - ((float(j)*3) - 3)) + (measurecount*3)) arr.append('\n') i = " ".join(arr) output.write(i) measurecount += 1 file.close() file2.close() output.close() webbrowser.open('output.txt') webbrowser.open('listen.html')
c7e15cbb2527455e5f52f261016f035afd819458
[ "Markdown", "Python" ]
2
Markdown
AnshThayil/MozartMusicalDice
1ab98191b8871304c9838abac482f52532b203d6
d3425dcfce99b8634d5d95cb505a0213344e143f
refs/heads/master
<repo_name>mariuscls/app-rabbitmq<file_sep>/src/AppBundle/Controller/PostcodesController.php <?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; class PostcodesController extends Controller { /** * @param Request $request * @return JsonResponse */ public function postPostcodesAction(Request $request) { $postcodesProducer = $this->get('old_sound_rabbit_mq.postcodes_producer'); $data = json_decode($request->getContent(),true); $postcodesProducer->setContentType('application/json'); $postcodesProducer->publish(serialize($data)); return new JsonResponse(array('Status' => 'OK')); } }<file_sep>/src/AppBundle/Service/Queue/PostCodesConsumerDeadLetterService.php <?php namespace AppBundle\Service\Queue; use GuzzleHttp\Client; use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface; use PhpAmqpLib\Message\AMQPMessage; use Psr\Log\LoggerInterface; class PostCodesConsumerDeadLetterService implements ConsumerInterface { /** * @var $client Client */ private $client; /** * @var $logger LoggerInterface */ private $logger; function __construct(Client $client, LoggerInterface $logger) { $this->client = $client; $this->logger = $logger; } /** * @param AMQPMessage $msg * @return bool */ public function execute(AMQPMessage $msg) { $message = unserialize($msg->getBody()); $this->logger->info('Corrupt message goes into Dead Letter Exchange'); } }<file_sep>/src/AppBundle/Service/Queue/PostCodesConsumerService.php <?php namespace AppBundle\Service\Queue; use GuzzleHttp\Client; use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface; use PhpAmqpLib\Message\AMQPMessage; use Psr\Log\LoggerInterface; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; class PostCodesConsumerService implements ConsumerInterface { /** * @var $client Client */ private $client; /** * @var $logger LoggerInterface */ private $logger; function __construct(Client $client, LoggerInterface $logger) { $this->client = $client; $this->logger = $logger; } /** * @param AMQPMessage $msg * @return bool */ public function execute(AMQPMessage $msg) { $data = unserialize($msg->getBody()); $result = $this->run($data); $latitude = null; $longitude = null; if( !empty($result) ) { $body = json_decode($result,true); $latitude = !empty($body['result'][0]['query']['latitude']) ? $body['result'][0]['query']['latitude'] : null; $longitude = !empty($body['result'][0]['query']['longitude']) ? $body['result'][0]['query']['longitude'] : null; } if( empty($latitude) && empty($longitude) ){ return false; } return true; } /** * @param $body * @return string * @throws \Exception|BadRequestHttpException|$response */ private function run($body){ $response = $this->client->post('postcodes', [ 'form_params' => $body ]); $response->withHeader('content-type','application/x-www-form-urlencoded'); if ($response->getStatusCode() == 200){ $this->logger->info('Registry processed correctly.'); return $response->getBody()->getContents(); }else if ($response->getStatusCode() == 400){ $this->logger->error('It has not been possible to process the request correctly.'); throw new BadRequestHttpException('Invalid JSON submitted. You need to submit a JSON object with an array of postcodes or geolocation objects.',null, 400 ); }else{ $this->logger->critical('Unexpected error when processing the request.'); throw new \Exception('Unexpected error, please check the sent content.',500); } } }
22007c1a6cf872f67806665cbf1820751287d664
[ "PHP" ]
3
PHP
mariuscls/app-rabbitmq
a0ca06cf16a7c7d53c17086bc1316a654ca06f5c
d7c34c090e99c6d6c2ec17b930217e4d697868f6
refs/heads/master
<repo_name>AmTote/terraform-provider-confluentcloud<file_sep>/README.md # `terraform-plugin-confluentcloud` A [Terraform][1] plugin for managing [Confluent Cloud Kafka Clusters][2]. ## Installation Download and extract the [latest release](https://github.com/Mongey/terraform-provider-confluentcloud/releases/latest) to your [terraform plugin directory][third-party-plugins] (typically `~/.terraform.d/plugins/`) or define the plugin in the required_providers block. ```hcl terraform { required_providers { confluentcloud = { source = "Mongey/confluentcloud" } } } ``` ## Example Configure the provider directly, or set the ENV variables `CONFLUENT_CLOUD_USERNAME` &`CONFLUENT_CLOUD_PASSWORD` ```hcl terraform { required_providers { confluentcloud = { source = "Mongey/confluentcloud" } kafka = { source = "Mongey/kafka" version = "0.2.11" } } } provider "confluentcloud" { username = "<EMAIL>" password = "<PASSWORD>" } resource "confluentcloud_environment" "environment" { name = "production" } resource "confluentcloud_kafka_cluster" "test" { name = "provider-test" service_provider = "aws" region = "eu-west-1" availability = "LOW" environment_id = confluentcloud_environment.environment.id deployment = { sku = "BASIC" } network_egress = 100 network_ingress = 100 storage = 5000 } resource "confluentcloud_schema_registry" "test" { environment_id = confluentcloud_environment.environment.id service_provider = "aws" region = "EU" # Requires at least one kafka cluster to enable the schema registry in the environment. depends_on = [confluentcloud_kafka_cluster.test] } resource "confluentcloud_api_key" "provider_test" { cluster_id = confluentcloud_kafka_cluster.test.id environment_id = confluentcloud_environment.environment.id } resource "confluentcloud_service_account" "test" { name = "test" description = "service account test" } locals { bootstrap_servers = [replace(confluentcloud_kafka_cluster.test.bootstrap_servers, "SASL_SSL://", "")] } provider "kafka" { bootstrap_servers = local.bootstrap_servers tls_enabled = true sasl_username = confluentcloud_api_key.provider_test.key sasl_password = confluentcloud_api_key.provider_test.secret sasl_mechanism = "plain" timeout = 10 } resource "kafka_topic" "syslog" { name = "syslog" replication_factor = 3 partitions = 1 config = { "cleanup.policy" = "delete" } } output "kafka_url" { value = local.bootstrap_servers } output "key" { value = confluentcloud_api_key.provider_test.key sensitive = true } output "secret" { value = confluentcloud_api_key.provider_test.secret sensitive = true } ``` ## Importing existing resources This provider supports importing existing Confluent Cloud resources via [`terraform import`][3]. Most resource types use the import IDs returned by the [`ccloud`][4] CLI. `confluentcloud_kafka_cluster` and `confluentcloud_schema_registry` can be imported using `<environment ID>/<cluster ID>`. [1]: https://www.terraform.io [2]: https://confluent.cloud [3]: https://www.terraform.io/docs/cli/import/index.html [4]: https://docs.confluent.io/ccloud-cli/current/index.html [third-party-plugins]: https://www.terraform.io/docs/configuration/providers.html#third-party-plugins <file_sep>/ccloud/resource_environment.go package ccloud import ( "context" "log" ccloud "github.com/cgroschupp/go-client-confluent-cloud/confluentcloud" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func environmentResource() *schema.Resource { return &schema.Resource{ CreateContext: environmentCreate, ReadContext: environmentRead, UpdateContext: environmentUpdate, DeleteContext: environmentDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, ForceNew: false, Description: "The name of the environment", }, }, } } func environmentCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) name := d.Get("name").(string) log.Printf("[INFO] Creating Environment %s", name) orgID, err := getOrganizationID(c) if err != nil { return diag.FromErr(err) } env, err := c.CreateEnvironment(name, orgID) if err != nil { return diag.FromErr(err) } d.SetId(env.ID) return nil } func environmentUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) newName := d.Get("name").(string) log.Printf("[INFO] Updating Environment %s", d.Id()) orgID, err := getOrganizationID(c) if err != nil { return diag.FromErr(err) } env, err := c.UpdateEnvironment(d.Id(), newName, orgID) if err != nil { return diag.FromErr(err) } d.SetId(env.ID) return nil } func environmentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) log.Printf("[INFO] Reading Environment %s", d.Id()) env, err := c.GetEnvironment(d.Id()) if err != nil { return diag.FromErr(err) } err = d.Set("name", env.Name) if err != nil { return diag.FromErr(err) } return nil } func environmentDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) log.Printf("[INFO] Deleting Environment %s", d.Id()) err := c.DeleteEnvironment(d.Id()) if err != nil { return diag.FromErr(err) } return nil } func getOrganizationID(client *ccloud.Client) (int, error) { userData, err := client.Me() if err != nil { return 0, err } return userData.Account.OrganizationID, nil } <file_sep>/docs/resources/environment.md --- page_title: "confluentcloud_environment Resource - terraform-provider-confluentcloud" subcategory: "" description: |- --- # Resource `confluentcloud_environment` ## Schema ### Required - **name** (String) The name of the environment ### Optional - **id** (String) The ID of this resource. <file_sep>/ccloud/resource_service_account.go package ccloud import ( "context" "errors" "fmt" "log" "strconv" ccloud "github.com/cgroschupp/go-client-confluent-cloud/confluentcloud" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func serviceAccountResource() *schema.Resource { return &schema.Resource{ CreateContext: serviceAccountCreate, ReadContext: serviceAccountRead, DeleteContext: serviceAccountDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Service Account Name", }, "description": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Service Account Description", }, }, } } func serviceAccountCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) name := d.Get("name").(string) description := d.Get("description").(string) req := ccloud.ServiceAccountCreateRequest{ Name: name, Description: description, } serviceAccount, err := c.CreateServiceAccount(&req) if err == nil { d.SetId(fmt.Sprintf("%d", serviceAccount.ID)) err = d.Set("name", serviceAccount.Name) if err != nil { return diag.FromErr(err) } err = d.Set("description", serviceAccount.Description) if err != nil { return diag.FromErr(err) } } else { log.Printf("[ERROR] Could not create Service Account: %s", err) } return diag.FromErr(err) } func serviceAccountRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) ID, err := strconv.Atoi(d.Id()) if err != nil { log.Printf("[ERROR] Could not parse Service Account ID %s to int", d.Id()) return diag.FromErr(err) } account, err := getServiceAccount(c, ID) if err != nil { return diag.FromErr(err) } err = d.Set("name", account.Name) if err != nil { return diag.FromErr(err) } err = d.Set("description", account.Description) if err != nil { return diag.FromErr(err) } return nil } func getServiceAccount(client *ccloud.Client, id int) (*ccloud.ServiceAccount, error) { accounts, err := client.ListServiceAccounts() if err != nil { return nil, err } for _, account := range accounts { if account.ID == id { return &account, nil } } return nil, errors.New("Unable to find service account") } func serviceAccountDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) ID, err := strconv.Atoi(d.Id()) if err != nil { log.Printf("[ERROR] Could not parse Service Account ID %s to int", d.Id()) return diag.FromErr(err) } err = c.DeleteServiceAccount(ID) if err != nil { log.Printf("[ERROR] Service Account can not be deleted: %d", ID) return diag.FromErr(err) } log.Printf("[INFO] Service Account deleted: %d", ID) return nil } <file_sep>/docs/index.md --- page_title: "confluentcloud Provider" subcategory: "" description: |- --- # confluentcloud Provider ## Schema ### Optional - **password** (String, Sensitive) - **username** (String) <file_sep>/ccloud/resource_kafka_cluster_test.go package ccloud import ( "fmt" "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/go-uuid" r "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func overrideProvider() *schema.Provider { return Provider() } func accProvider() map[string]*schema.Provider { return map[string]*schema.Provider{ "confluentcloud": overrideProvider(), } } func testAccPreCheck(t *testing.T) { if os.Getenv("CONFLUENT_CLOUD_USERNAME") == "" || os.Getenv("CONFLUENT_CLOUD_PASSWORD") == "" { t.Skip("CONFLUENT_CLOUD_ environment variables must be set") } } func TestAcc_BasicCluster(t *testing.T) { u, err := uuid.GenerateUUID() if err != nil { t.Fatal(err) } r.ParallelTest(t, r.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: accProvider(), Steps: []r.TestStep{ { Config: fmt.Sprintf(testResourceCluster_noConfig, u, u), }, { ResourceName: "confluentcloud_kafka_cluster.test", ImportState: true, ImportStateIdFunc: func(state *terraform.State) (string, error) { resources := state.RootModule().Resources clusterID := resources["confluentcloud_kafka_cluster.test"].Primary.ID envID := resources["confluentcloud_environment.test"].Primary.ID return (envID + "/" + clusterID), nil }, ImportStateVerify: true, }, }, }) } //lintignore:AT004 const testResourceCluster_noConfig = ` resource "confluentcloud_environment" "test" { name = "acc_test_environment-%s" } resource "confluentcloud_kafka_cluster" "test" { name = "provider-test-%s" service_provider = "aws" region = "eu-west-1" availability = "LOW" environment_id = confluentcloud_environment.test.id deployment = { sku = "BASIC" } network_egress = 100 network_ingress = 100 storage = 5000 } ` <file_sep>/docs/resources/schema_registry.md --- page_title: "confluentcloud_schema_registry Resource - terraform-provider-confluentcloud" subcategory: "" description: |- --- # Resource `confluentcloud_schema_registry` ## Schema ### Required - **environment_id** (String) Environment ID - **region** (String) where - **service_provider** (String) Cloud provider ### Optional - **id** (String) The ID of this resource. ### Read-only - **endpoint** (String) <file_sep>/ccloud/resource_schema_registry.go package ccloud import ( "context" "fmt" "log" "strings" ccloud "github.com/cgroschupp/go-client-confluent-cloud/confluentcloud" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func schemaRegistryResource() *schema.Resource { return &schema.Resource{ CreateContext: schemaRegistryCreate, ReadContext: schemaRegistryRead, DeleteContext: schemaRegistryDelete, Importer: &schema.ResourceImporter{ StateContext: schemaRegistryImport, }, Schema: map[string]*schema.Schema{ "environment_id": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Environment ID", }, "region": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "where", }, "service_provider": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Cloud provider", }, "endpoint": { Type: schema.TypeString, Computed: true, }, }, } } func schemaRegistryCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) environmentID := d.Get("environment_id").(string) region := d.Get("region").(string) serviceProvider := d.Get("service_provider").(string) log.Printf("[INFO] Creating Schema Registry %s", environmentID) reg, err := c.CreateSchemaRegistry(environmentID, region, serviceProvider) if err != nil { return diag.FromErr(err) } d.SetId(reg.ID) err = d.Set("endpoint", reg.Endpoint) if err != nil { return diag.FromErr(err) } return nil } func schemaRegistryRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) environmentID := d.Get("environment_id").(string) log.Printf("[INFO] Reading Schema Registry %s", environmentID) registry, err := c.GetSchemaRegistry(environmentID) if err != nil { return diag.FromErr(err) } err = d.Set("environment_id", environmentID) if err != nil { return diag.FromErr(err) } err = d.Set("endpoint", registry.Endpoint) if err != nil { return diag.FromErr(err) } return diag.FromErr(err) } func schemaRegistryDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { log.Printf("[WARN] Schema registry cannot be deleted: %s", d.Id()) return nil } func schemaRegistryImport(_ context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { envIDAndClusterID := d.Id() parts := strings.Split(envIDAndClusterID, "/") var err error if len(parts) != 2 { return nil, fmt.Errorf("invalid format for schema registry cluster import: expected '<env ID>/<cluster ID>'") } d.SetId(parts[1]) err = d.Set("environment_id", parts[0]) if err != nil { return nil, err } return []*schema.ResourceData{d}, nil } <file_sep>/scripts/test.sh #!/bin/bash set -ex ARCH=$(go env GOARCH) OS=$(go env GOOS) make build mv bin/${OS}-${ARCH}/terraform-provider-confluentcloud ~/.terraform.d/plugins/terraform-provider-confluentcloud cd examples terraform init TF_LOG=debug terraform apply <file_sep>/ccloud/resource_service_account_test.go package ccloud import ( "fmt" "testing" "github.com/hashicorp/go-uuid" r "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAcc_BasicServiceAccount(t *testing.T) { u, err := uuid.GenerateUUID() if err != nil { t.Fatal(err) } r.ParallelTest(t, r.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: accProvider(), Steps: []r.TestStep{ { Config: fmt.Sprintf(testServiceAccount_noConfig, u, u), }, { ResourceName: "confluentcloud_service_account.test", ImportState: true, ImportStateVerify: true, }, }, }) } //lintignore:AT004 const testServiceAccount_noConfig = ` resource "confluentcloud_service_account" "test" { name = "acc-test-%s" description = "My cool description - %s" } ` <file_sep>/docs/resources/service_account.md --- page_title: "confluentcloud_service_account Resource - terraform-provider-confluentcloud" subcategory: "" description: |- --- # Resource `confluentcloud_service_account` ## Schema ### Required - **description** (String) Service Account Description - **name** (String) Service Account Name ### Optional - **id** (String) The ID of this resource. <file_sep>/ccloud/resource_kafka_cluster.go package ccloud import ( "context" "fmt" "log" "strings" "time" "github.com/Shopify/sarama" ccloud "github.com/cgroschupp/go-client-confluent-cloud/confluentcloud" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func kafkaClusterResource() *schema.Resource { return &schema.Resource{ CreateContext: clusterCreate, ReadContext: clusterRead, DeleteContext: clusterDelete, Importer: &schema.ResourceImporter{ StateContext: clusterImport, }, Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "The name of the cluster", }, "environment_id": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Environment ID", }, "bootstrap_servers": { Type: schema.TypeString, Computed: true, }, "service_provider": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "AWS / GCP", }, "region": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "where", }, "availability": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "LOW(single-zone) or HIGH(multi-zone)", ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) { v := val.(string) if val != "LOW" && val != "HIGH" { errs = append(errs, fmt.Errorf("%q must be `LOW` or `HIGH`, got: %s", key, v)) } return }, }, "storage": { Type: schema.TypeInt, Optional: true, ForceNew: true, Description: "Storage limit(GB)", }, "network_ingress": { Type: schema.TypeInt, Optional: true, ForceNew: true, Description: "Network ingress limit(MBps)", }, "network_egress": { Type: schema.TypeInt, Optional: true, ForceNew: true, Description: "Network egress limit(MBps)", }, "deployment": { Type: schema.TypeMap, Optional: true, ForceNew: true, Description: "Deployment settings. Currently only `sku` is supported.", Elem: &schema.Schema{ Type: schema.TypeString, }, }, "cku": { Type: schema.TypeInt, Optional: true, ForceNew: true, Description: "cku", }, }, } } func clusterCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) name := d.Get("name").(string) region := d.Get("region").(string) serviceProvider := d.Get("service_provider").(string) durability := d.Get("availability").(string) accountID := d.Get("environment_id").(string) deployment := d.Get("deployment").(map[string]interface{}) storage := d.Get("storage").(int) networkIngress := d.Get("network_ingress").(int) networkEgress := d.Get("network_egress").(int) cku := d.Get("cku").(int) log.Printf("[DEBUG] Creating kafka_cluster") dep := ccloud.ClusterCreateDeploymentConfig{ AccountID: accountID, } if val, ok := deployment["sku"]; ok { dep.Sku = val.(string) } else { dep.Sku = "BASIC" } req := ccloud.ClusterCreateConfig{ Name: name, Region: region, ServiceProvider: serviceProvider, Storage: storage, AccountID: accountID, Durability: durability, Deployment: dep, NetworkIngress: networkIngress, NetworkEgress: networkEgress, Cku: cku, } cluster, err := c.CreateCluster(req) if err != nil { log.Printf("[ERROR] createCluster failed %v, %s", req, err) return diag.FromErr(err) } d.SetId(cluster.ID) log.Printf("[DEBUG] Created kafka_cluster %s, Endpoint: %s", cluster.ID, cluster.Endpoint) err = d.Set("bootstrap_servers", cluster.Endpoint) if err != nil { return diag.FromErr(err) } logicalClusters := []ccloud.LogicalCluster{ ccloud.LogicalCluster{ID: cluster.ID}, } apiKeyReq := ccloud.ApiKeyCreateRequest{ AccountID: accountID, LogicalClusters: logicalClusters, Description: "terraform-provider-confluentcloud cluster connection bootstrap", } log.Printf("[DEBUG] Creating bootstrap keypair") key, err := c.CreateAPIKey(&apiKeyReq) if err != nil { return diag.FromErr(err) } stateConf := &resource.StateChangeConf{ Pending: []string{"Pending"}, Target: []string{"Ready"}, Refresh: clusterReady(c, d.Id(), accountID, key.Key, key.Secret), Timeout: 1800 * time.Second, Delay: 3 * time.Second, PollInterval: 5 * time.Second, MinTimeout: 20 * time.Second, } log.Printf("[DEBUG] Waiting for cluster to become healthy") _, err = stateConf.WaitForStateContext(ctx) if err != nil { return diag.FromErr(fmt.Errorf("Error waiting for cluster (%s) to be ready: %s", d.Id(), err)) } log.Printf("[DEBUG] Deleting bootstrap keypair") err = c.DeleteAPIKey(fmt.Sprintf("%d", key.ID), accountID, logicalClusters) if err != nil { log.Printf("[ERROR] Unable to delete bootstrap api key %s", err) } return nil } func clusterReady(client *ccloud.Client, clusterID, accountID, username, password string) resource.StateRefreshFunc { return func() (result interface{}, s string, err error) { cluster, err := client.GetCluster(clusterID, accountID) log.Printf("[DEBUG] Waiting for Cluster to be UP: current status %s %s:%s", cluster.Status, username, password) log.Printf("[DEBUG] cluster %v", cluster) if err != nil { return cluster, "UNKNOWN", err } log.Printf("[DEBUG] Attempting to connect to %s, created %s", cluster.Endpoint, cluster.Deployment.Created) if cluster.Status == "UP" { if canConnect(cluster.Endpoint, username, password) { return cluster, "Ready", nil } } return cluster, "Pending", nil } } func canConnect(connection, username, password string) bool { client, err := kafkaClient(connection, username, password) if err != nil { log.Printf("[ERROR] Could not build client %s", err) return false } err = client.RefreshMetadata() if err != nil { log.Printf("[ERROR] Could not refresh metadata %s", err) return false } log.Printf("[INFO] Success! Connected to %s", connection) return true } func clusterDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) accountID := d.Get("environment_id").(string) var diags diag.Diagnostics if err := c.DeleteCluster(d.Id(), accountID); err != nil { return diag.FromErr(err) } return diags } func clusterImport(_ context.Context, d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) { envIDAndClusterID := d.Id() parts := strings.Split(envIDAndClusterID, "/") var err error if len(parts) != 2 { return nil, fmt.Errorf("invalid format for cluster import: expected '<env ID>/<cluster ID>'") } d.SetId(parts[1]) err = d.Set("environment_id", parts[0]) if err != nil { return nil, err } return []*schema.ResourceData{d}, nil } func clusterRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) accountID := d.Get("environment_id").(string) cluster, err := c.GetCluster(d.Id(), accountID) if err == nil { err = d.Set("bootstrap_servers", cluster.Endpoint) } if err == nil { err = d.Set("name", cluster.Name) } if err == nil { err = d.Set("region", cluster.Region) } if err == nil { err = d.Set("service_provider", cluster.ServiceProvider) } if err == nil { err = d.Set("availability", cluster.Durability) } if err == nil { err = d.Set("deployment", map[string]interface{}{"sku": cluster.Deployment.Sku}) } if err == nil { err = d.Set("storage", cluster.Storage) } if err == nil { err = d.Set("network_ingress", cluster.NetworkIngress) } if err == nil { err = d.Set("network_egress", cluster.NetworkEgress) } if err == nil { err = d.Set("cku", cluster.Cku) } return diag.FromErr(err) } func kafkaClient(connection, username, password string) (sarama.Client, error) { bootstrapServers := strings.Replace(connection, "SASL_SSL://", "", 1) log.Printf("[INFO] Trying to connect to %s", bootstrapServers) cfg := sarama.NewConfig() cfg.Net.SASL.Enable = true cfg.Net.SASL.User = username cfg.Net.SASL.Password = <PASSWORD> cfg.Net.SASL.Handshake = true cfg.Net.TLS.Enable = true return sarama.NewClient([]string{bootstrapServers}, cfg) } <file_sep>/docs/resources/api_key.md --- page_title: "confluentcloud_api_key Resource - terraform-provider-confluentcloud" subcategory: "" description: |- --- # Resource `confluentcloud_api_key` ## Schema ### Required - **environment_id** (String) Environment ID ### Optional - **cluster_id** (String) - **description** (String) Description - **id** (String) The ID of this resource. - **logical_clusters** (List of String) Logical Cluster ID List to create API Key - **user_id** (Number) User ID ### Read-only - **key** (String) - **secret** (String, Sensitive) <file_sep>/main.go package main import ( c "github.com/Mongey/terraform-provider-confluentcloud/ccloud" "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" ) //go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs func main() { plugin.Serve(&plugin.ServeOpts{ProviderFunc: c.Provider}) } <file_sep>/docs/resources/kafka_cluster.md --- page_title: "confluentcloud_kafka_cluster Resource - terraform-provider-confluentcloud" subcategory: "" description: |- --- # Resource `confluentcloud_kafka_cluster` ## Schema ### Required - **availability** (String) LOW(single-zone) or HIGH(multi-zone) - **environment_id** (String) Environment ID - **name** (String) The name of the cluster - **region** (String) where - **service_provider** (String) AWS / GCP ### Optional - **cku** (Number) cku - **deployment** (Map of String) Deployment settings. Currently only `sku` is supported. - **id** (String) The ID of this resource. - **network_egress** (Number) Network egress limit(MBps) - **network_ingress** (Number) Network ingress limit(MBps) - **storage** (Number) Storage limit(GB) ### Read-only - **bootstrap_servers** (String) <file_sep>/ccloud/resource_schema_registry_test.go package ccloud import ( "fmt" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/go-uuid" r "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAcc_SchemaRegistry(t *testing.T) { u, err := uuid.GenerateUUID() if err != nil { t.Fatal(err) } r.ParallelTest(t, r.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: accProvider(), Steps: []r.TestStep{ { Config: fmt.Sprintf(testResourceSchemaRegistry_noConfig, u, u), }, { ResourceName: "confluentcloud_schema_registry.test", ImportState: true, ImportStateIdFunc: func(state *terraform.State) (string, error) { resources := state.RootModule().Resources schemaRegistryID := resources["confluentcloud_schema_registry.test"].Primary.ID envID := resources["confluentcloud_environment.test"].Primary.ID return (envID + "/" + schemaRegistryID), nil }, ImportStateVerify: true, ImportStateVerifyIgnore: []string{ "region", "service_provider", }, }, }, }) } //lintignore:AT004 const testResourceSchemaRegistry_noConfig = ` resource "confluentcloud_environment" "test" { name = "acc_test_environment-%s" } resource "confluentcloud_kafka_cluster" "test" { name = "provider-test-%s" service_provider = "aws" region = "eu-west-1" availability = "LOW" environment_id = confluentcloud_environment.test.id deployment = { sku = "BASIC" } network_egress = 100 network_ingress = 100 storage = 5000 } resource "confluentcloud_schema_registry" "test" { environment_id = confluentcloud_environment.test.id service_provider = "aws" region = "EU" # Requires at least one kafka cluster to enable the schema registry in the environment. depends_on = [confluentcloud_kafka_cluster.test] } ` <file_sep>/ccloud/resource_api_key.go package ccloud import ( "context" "fmt" "log" "time" ccloud "github.com/cgroschupp/go-client-confluent-cloud/confluentcloud" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func apiKeyResource() *schema.Resource { return &schema.Resource{ CreateContext: apiKeyCreate, ReadContext: apiKeyRead, DeleteContext: apiKeyDelete, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, Schema: map[string]*schema.Schema{ "cluster_id": { Type: schema.TypeString, Optional: true, ForceNew: true, Description: "", }, "logical_clusters": { Type: schema.TypeList, Elem: &schema.Schema{ Type: schema.TypeString, }, Optional: true, ForceNew: true, Description: "Logical Cluster ID List to create API Key", }, "user_id": { Type: schema.TypeInt, Optional: true, ForceNew: true, Description: "User ID", }, "environment_id": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Environment ID", }, "description": { Type: schema.TypeString, Optional: true, ForceNew: true, Description: "Description", }, "key": { Type: schema.TypeString, Computed: true, }, "secret": { Type: schema.TypeString, Computed: true, Sensitive: true, }, }, } } func apiKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) clusterID := d.Get("cluster_id").(string) logicalClusters := d.Get("logical_clusters").([]interface{}) accountID := d.Get("environment_id").(string) userID := d.Get("user_id").(int) description := d.Get("description").(string) logicalClustersReq := []ccloud.LogicalCluster{} if len(clusterID) > 0 { logicalClustersReq = append(logicalClustersReq, ccloud.LogicalCluster{ID: clusterID}) } for i := range logicalClusters { if clusterID != logicalClusters[i].(string) { logicalClustersReq = append(logicalClustersReq, ccloud.LogicalCluster{ ID: logicalClusters[i].(string), }) } } req := ccloud.ApiKeyCreateRequest{ AccountID: accountID, UserID: userID, LogicalClusters: logicalClustersReq, Description: description, } log.Printf("[DEBUG] Creating API key") key, err := c.CreateAPIKey(&req) if err == nil { d.SetId(fmt.Sprintf("%d", key.ID)) err = d.Set("key", key.Key) if err != nil { return diag.FromErr(err) } err = d.Set("secret", key.Secret) if err != nil { return diag.FromErr(err) } if len(clusterID) > 0 { log.Printf("[INFO] Created API Key, waiting for it become usable") stateConf := &resource.StateChangeConf{ Pending: []string{"Pending"}, Target: []string{"Ready"}, Refresh: clusterReady(c, clusterID, accountID, key.Key, key.Secret), Timeout: 300 * time.Second, Delay: 10 * time.Second, PollInterval: 5 * time.Second, MinTimeout: 20 * time.Second, } _, err = stateConf.WaitForStateContext(context.Background()) } else { log.Printf("[INFO] Created API Key") } if err != nil { return diag.FromErr(fmt.Errorf("Error waiting for API Key (%s) to be ready: %s", d.Id(), err)) } } else { log.Printf("[ERROR] Could not create API key: %s", err) } log.Printf("[INFO] API Key Created successfully: %s", err) return diag.FromErr(err) } func apiKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { return nil } func apiKeyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { c := meta.(*ccloud.Client) clusterID := d.Get("cluster_id").(string) logicalClusters := d.Get("logical_clusters").([]interface{}) accountID := d.Get("environment_id").(string) logicalClustersReq := []ccloud.LogicalCluster{} if len(clusterID) > 0 { logicalClustersReq = append(logicalClustersReq, ccloud.LogicalCluster{ID: clusterID}) } for i := range logicalClusters { if clusterID != logicalClusters[i].(string) { logicalClustersReq = append(logicalClustersReq, ccloud.LogicalCluster{ ID: logicalClusters[i].(string), }) } } id := d.Id() log.Printf("[INFO] Deleting API key %s in account %s", id, accountID) err := c.DeleteAPIKey(id, accountID, logicalClustersReq) return diag.FromErr(err) }
505ffa0dce9b15af3cae603e31659832fe02e7f8
[ "Markdown", "Go", "Shell" ]
17
Markdown
AmTote/terraform-provider-confluentcloud
7efbbe1c241d1d54c74ba9ff2eb5447b6c95f87a
b83e7131255d3ffbee2d465169e02983effc3e6f
refs/heads/master
<repo_name>maribelcuales/Testing<file_sep>/basic-javascript/project-1.spec.js const helpers = require('./project-1'); // start testing! //multiplyByTen describe('Multiply By 10', () => { it('returns NaN when given a type that is not a number', () => { expect(helpers.multiplyByTen(null)).toEqual(0); expect(helpers.multiplyByTen(undefined)).toBeNaN() }) it('return a number multiply by 10', () => { expect(helpers.multiplyByTen(3)).toEqual(30) expect(helpers.multiplyByTen(-2)).toEqual(-20); }) }) //subtractFive describe('Subtract by 5', () => { it('return a number that is subtracted by 5', () => { expect(helpers.subtractFive(10)).toEqual(5); expect(helpers.subtractFive(-6)).toEqual(-11); }) }) // areSameLength describe('return true if the length are the same false otherwise', () => { it('place holder text', () => { expect(helpers.areSameLength('abc', 'def')).toBeTruthy(); expect(helpers.areSameLength('this is a test', 'tset a si siht')).toBeTruthy(); }) it('return false if length is different', () => { expect(helpers.areSameLength('abc', 'def')).toBeFalsy(); expect(helpers.areSameLength('this is a test', 'tobe')).toBeFalsy(); }) // areEqual describe('areEqual', () => { it('return true when x and y are the same number and type', () => { expect(helpers.areEqual(10, 10)).toBeTruthy(); expect(helpers.areEqual('str', 'str')).toBeTruthy(); }) it('return false when x and y are not the same number and type', () => { expect(helpers.areEqual(10, 3)).toBeFalsy() expect(helpers.areEqual('str', 'str')).toBeFalsy() }) }) //lessThanNinety describe("Less than 90", () => { it('returns true if the number pass is less than 90 otherwise false', () => { expect(helpers.lessThanNinety(89)).toBeTruthy(); expect(helpers.lessThanNinety(100)).toBeFalsy(); }) }) // greaterThanFifty describe('Greater than 50', () => { it('returns true if the number pass is greater than 50 otherwise false', () => { expect(helpers.greaterThanFifty(65)).toBeTruthy(); expect(helpers.greaterThanFifty(25)).toBeFalsy(); }) }) // add describe('Add 2 numbers', () => { it('returns the sum of the 2 numbers pass in', () => { expect(helpers.add(2, 3)).toBe(5); expect(helpers.add(-5, -6)).toEqual(-11); }) }) //subtract describe('Subtract 2 numbers', () => { it('return the sum of the 2 numbers pass in', () => { expect(helpers.subtract(10,5)).toBe(5); expect(helpers.subtract(-7, -2)).toEqual(-5) }) }) //divide describe('Divide 2 numbers', () => { it('return the quotient of the 2 numbers pass in', () => { expect(helpers.divide(10,5)).toEqual(2); expect(helpers.divide(-18, 32)).toEqual(-6); }) }) //multiply describe('Multiply 2 numbers', () => { it('return the product of the 2 numbers pass in', () => { expect(helpers.multiply(10,2)).toEqual(20); expect(helpers.multiply(-5, 6)).toEqual(-30); }) }) // getRemainder describe('get the remainder of 2 numbers divided by each other', () => { it('returns the remainder of the 2 numbers pass in', () => { expect(helpers.getRemainder(10,3)).toEqual(1); }) }) //isEven describe('return true if the number is even otherwise false', () => { it('returns true when the number pass in is even', () => { expect(helpers.isEven(6)).toBeTruthy(); }) it('return false when the number pass in is odd', () => { expect(helpers.isEven(3)).toBeFalsy(); }) }) //isOdd describe('return true if the numbers is odd otherwise false', () => { it('returns true when the number pass in is odd', () => { expect(helpers.isOdd(3)).toBeTruthy(); }) it('return false when number is even', () => { expect(helpers.isOdd(4)).toBeFalsy(); }) }) // square describe('Square the number', () => { it('return the square of the number pass in', () => { expect(helpers.square(2)).toEqual(4); expect(helpers.square(-5)).toEqual(25); }) }) //cube describe('Cube the number', () => { it('return the cube of the number pass in', () => { expect(helpers.cube(3)).toEqual(27); expect(helpers.cube(-3)).toEqual(-27); }) }) // raiseToPower describe('raise to the power', () => { it('return the first number to the power of the second number', () => { expect(helpers.raiseToPower(3,3)).toEqual(27); expect(helpers.raiseToPower(-3,3)).toEqual(-27); }) }) //roundNumber describe('rounded number', () => { it('return the number rounded off to the nearest whole number', () => { expect(helpers.roundNumber(7.5)).toEqual(8); expect(helpers.roundNumber(7.1)).toEqual(7); }) }) //roundUp describe("round up number", () => { it("return the number rounded up to the nearest whole number", () => { expect(helpers.roundUp(8.2)).toEqual(9) expect(helpers.roundUp(8.6)).toEqual(9) }) }) //addExclamationPoint describe('add exclamation point to string', () => { it('return the string with an exclamation point append to it', () => { expect(helpers.addExclamationPoint('Hello')).toEqual('Hello!') expect(helpers.addExclamationPoint('test')).not.toEqual('test!') }) }) // combineNames describe('combine names', () => { it('return the combination of the two names pass in', () => { expect(helpers.combineNames('Xang', 'Thao')).toEqual('<NAME>') expect(helpers.combineNames('Xang', 'Thao')).not.toEqual('XangThao') }) }) // getGreeting describe('greet person', () => { it('return the greeting with the name pass in', () => { expect(helpers.getGreeting('Rome')).toEqual('Hello Rome!') expect(helpers.getGreeting('Rome')).not.toEqual('Rome!') }) }) //getRectangleArea describe('get rectangle area', () => { it('return the area of the rectangle', () => { expect(helpers.getRectangleArea(3,7)).toEqual(21) }) }) // getTriangleArea describe('get triangle area', () => { it('return the area of the triangle', () => { expect(helpers.getTriangleArea(2,10)).toEqual(10) }) }) // getCircleArea describe('get circle area', () => { it('return the area of the circle', () => { let num = 5; let area = num * num * Math.PI; expect(helpers.getCircleArea(num)).toEqual(area) }) }) //getRectangularPrismVolume describe('get rectangular prism volume', () => { it('return the prism volume of the rectangle', () => { expect(helpers.getRectangularPrismVolume(2,3,4)).toEqual(24) }) })<file_sep>/basic-javascript/project-2.spec.js const funcs = require('./project-2'); // whoops.. there is no test suite for this file. You'll simply just have to create one :/ it('should nor throw err', () => { expect(5).toEqual(5); }) <file_sep>/advanced-javascript/objects.spec.js const objectFunctions = require('./objects'); // whoops.. there is no test suite for this file. You'll simply just have to create one :/ describe('objects', () => { // keys describe("keys", () => { it("should return an array of the properties of an object", () => { expect(objectFunctions.keys({name: "Maribel", age: 18})).toEqual(['name', 'age']); }) }) //values describe("values", () => { it("should return an array if the values of an object", () => { expect(objectFunctions.values({name: "Maribel", age: 18})).toEqual(["Maribel", 18]); }) }) //mapObject describe("mapObject", () => { it("should return an object with the value increment by 1", () => { expect(objectFunctions.mapObject({num1: 5, num2: 7}, (x) => x + 1)) .toEqual({num1: 6, num2: 8}); }) }) //pairs describe("pairs", () => { it("should return 1 with arrays of key value pair", () => { expect(objectFunctions.pairs({name: "Ja", age: 23})) .toEqual([["name","Ja"],["age",23]]) }) }) //invert describe("invert", () => { it("should invert the key and value of the object", () => { expect(objectFunctions.invert({name: "Ja", age: 23})).toEqual({Ja:"name", "23": "age"}) }) }) //defaults describe("defaults", () => { it("should return the object's own property and value and properties that you don't have but is given to you from the default object", () => { expect(objectFunctions.defaults({name: "Ja", age: 23}, {name: "test", age: 5, lastName: "Navey"})) .toEqual({name: "Ja", age: 23, lastName: "Navey"}) }) }) });
fe95c851e9bfa424f2308a3dad434fd52bb80105
[ "JavaScript" ]
3
JavaScript
maribelcuales/Testing
b965246b019b0e1ee7070cb2fc2597d7c95ca493
40add47090d7704fc97168ad90bb9c3d3b52c66f
refs/heads/master
<repo_name>christherama/parking-rates-grpc<file_sep>/server/build.gradle apply plugin: 'com.google.protobuf' apply plugin: 'java' apply plugin: 'application' apply plugin: 'docker' buildscript { repositories { mavenCentral() jcenter() } dependencies { classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.5' classpath 'se.transmode.gradle:gradle-docker:1.2' } } group 'parking-rates' version '1.0' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { protobufVersion = '3.5.1' } dependencies { compile "com.google.protobuf:protobuf-java-util:${protobufVersion}" compile 'io.grpc:grpc-netty-shaded:1.16.1' compile 'io.grpc:grpc-protobuf:1.16.1' compile 'io.grpc:grpc-stub:1.16.1' compile 'commons-io:commons-io:2.6' compile 'org.projectlombok:lombok:1.18.4' testCompile "junit:junit:4.12" testCompile "org.mockito:mockito-core:2.23.0" } sourceSets { main { java { srcDirs 'build/generated/source/proto/main/grpc' srcDirs 'build/generated/source/proto/main/java' } } } protobuf { protoc { artifact = "com.google.protobuf:protoc:3.5.1-1" } plugins { grpc { artifact = 'io.grpc:protoc-gen-grpc-java:1.16.1' } } generateProtoTasks { all()*.plugins { grpc {} } } } mainClassName = 'io.rama.parking.ParkingRateServer' distDocker { exposePort 1234 }<file_sep>/server/src/test/java/io/rama/parking/RateFinderServiceTest.java package io.rama.parking; import io.grpc.stub.StreamObserver; import org.junit.Before; import org.junit.Test; import java.time.LocalTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; public class RateFinderServiceTest { private static final long DEC_18_2018_0800_UTC = 1545033600L; private static final long DEC_18_2018_1600_UTC = 1545062400L; private static final LocalTime EIGHT_AM = LocalTime.of(8,0,0); private static final LocalTime FOUR_PM = LocalTime.of(16,0,0); private List<Rate> rates; private RateFinderService rateFinderService; @Before public void setup() { rates = new ArrayList<>(); rates.add(Rate.builder().daysOfWeek(Arrays.asList(0,1,2)).rate(10).start(EIGHT_AM).end(FOUR_PM).build()); rateFinderService = new RateFinderService(rates); } @Test public void fallsWithin_whenUnderlyingRangeFallsWithinProvidedRange_returnsFalse() throws Exception { RateFinderService.DateTimeRange rangeToCheck = new RateFinderService.DateTimeRange(DEC_18_2018_0800_UTC, DEC_18_2018_1600_UTC); LocalTime start = LocalTime.of(8,0,0); LocalTime end = LocalTime.of(16,0,0); assertTrue(rangeToCheck.fallsWithin(start,end)); } @Test public void fallsWithin_whenUnderlyingRangeDoesNotFallWithinProvidedRange_returnsFalse() throws Exception { RateFinderService.DateTimeRange rangeToCheck = new RateFinderService.DateTimeRange(DEC_18_2018_0800_UTC, DEC_18_2018_1600_UTC + 1); LocalTime start = LocalTime.of(8,0,0); LocalTime end = LocalTime.of(16,0,0); assertFalse(rangeToCheck.fallsWithin(start,end)); } @Test public void find_whenMatchIsFound_returnsRate() throws Exception { MockRateResponseStreamObserver observer = new MockRateResponseStreamObserver(); ParkingRatesProtos.RateRequest request = ParkingRatesProtos.RateRequest.newBuilder().setStart(DEC_18_2018_0800_UTC).setEnd(DEC_18_2018_1600_UTC).build(); rateFinderService.find(request,observer); assertThat(observer.getRate(), is(10)); } @Test public void find_whenMatchIsNotFound_returnsZeroRate() throws Exception { MockRateResponseStreamObserver observer = new MockRateResponseStreamObserver(); ParkingRatesProtos.RateRequest request = ParkingRatesProtos.RateRequest.newBuilder().setStart(DEC_18_2018_0800_UTC).setEnd(1 + DEC_18_2018_1600_UTC).build(); rateFinderService.find(request,observer); assertThat(observer.getRate(), is(0)); } private static class MockRateResponseStreamObserver implements StreamObserver<ParkingRatesProtos.RateResponse> { private int rate; public int getRate() { return rate; } @Override public void onNext(ParkingRatesProtos.RateResponse value) { this.rate = value.getRate(); } @Override public void onError(Throwable t) { } @Override public void onCompleted() { } } } <file_sep>/integration/build.gradle plugins { id 'java' } sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { testCompile project(':client') testCompile project(':server') testCompile "com.sparkjava:spark-core:2.7.2" testCompile "com.fasterxml.jackson.core:jackson-databind:2.9.7" testCompile "org.projectlombok:lombok:1.18.4" testCompile "junit:junit:4.12" } <file_sep>/settings.gradle rootProject.name = 'parking-rates-grpc' include 'server' include 'client' include 'integration' <file_sep>/client/src/test/java/io/rama/parking/RateServiceTest.java package io.rama.parking; import io.rama.parking.exception.RateNotFoundException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.Optional; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class RateServiceTest { private RateService rateService; @Mock private RateClient rateClient; @Before public void setup() { rateService = new RateService(rateClient); } @Test public void service_whenRateIsAvailable_returnsAccurateRate() throws Exception { when(rateClient.getRate(anyLong(),anyLong())).thenReturn(Optional.of(1500)); DateTimeRange range = DateTimeRange.builder() .start("2018-11-08T10:00:00Z") .end("2018-11-08T12:00:00Z") .build(); assertThat(rateService.getRate(range),is(1500)); } @Test(expected = RateNotFoundException.class) public void service_whenRateIsUnavailable_throwsException() throws Exception { when(rateClient.getRate(anyLong(),anyLong())).thenReturn(Optional.empty()); DateTimeRange range = DateTimeRange.builder() .start("2018-11-08T08:00:00Z") .end("2018-11-08T12:00:00Z") .build(); rateService.getRate(range); } }<file_sep>/client/src/main/java/io/rama/parking/RateService.java package io.rama.parking; import io.rama.parking.exception.RateNotFoundException; import lombok.Data; @Data public class RateService { private final RateClient client; public RateService(RateClient client) { this.client = client; } public Integer getRate(DateTimeRange range) throws RateNotFoundException { long start = range.getStart().toInstant().getEpochSecond(); long end = range.getEnd().toInstant().getEpochSecond(); return client.getRate(start,end).orElseThrow(RateNotFoundException::new); } } <file_sep>/server/src/main/java/io/rama/parking/ParkingRateUtils.java package io.rama.parking; import com.google.gson.Gson; import lombok.extern.java.Log; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static java.lang.System.exit; @Log public class ParkingRateUtils { /** * Parses the JSON input file containing the list of features. */ public static List<Rate> parseFromJson(URI file) throws IOException { Gson gson = new Gson(); RateInput rateInput = gson.fromJson(getJsonString(file),RateInput.class); DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmm"); return rateInput.getRates().stream().map(in -> Rate.builder() .daysOfWeek( Arrays.stream(in.getDays().split(",")) .map(day -> 1 + Arrays.asList("mon", "tues", "wed", "thurs", "fri", "sat", "sun").indexOf(day.toLowerCase())) .collect(Collectors.toList()) ) .start(LocalTime.parse(in.getTimes().split("-")[0], timeFormatter)) .end(LocalTime.parse(in.getTimes().split("-")[1], timeFormatter)) .rate(in.getPrice()) .build() ).collect(Collectors.toList()); } private static String getJsonString(URI uri) { try { final Map<String, String> env = new HashMap<>(); final String[] array = uri.toString().split("!"); final FileSystem fs = FileSystems.newFileSystem(URI.create(array[0]), env); final Path path = fs.getPath(array[1]); return Files.lines(path).collect(Collectors.joining("\n")); } catch (IOException e) { log.severe("Unable to load parking rates from " + uri.getPath()); exit(-1); return null; } } public static URI getDefaultFilePath() { try { return ParkingRateUtils.class.getClassLoader().getResource("rates.json").toURI(); } catch (URISyntaxException e) { log.severe("Unable to load parking rates from rates.json"); exit(-1); return null; } } } <file_sep>/client/src/main/java/io/rama/parking/exception/InvalidDateRangeException.java package io.rama.parking.exception; public class InvalidDateRangeException extends RuntimeException { } <file_sep>/client/src/main/java/io/rama/parking/RateClient.java package io.rama.parking; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.Optional; public class RateClient { private final ManagedChannel channel; private final RateFinderGrpc.RateFinderBlockingStub blockingStub; public RateClient(String host, int port) { this(ManagedChannelBuilder.forAddress(host, port).usePlaintext()); } public RateClient(ManagedChannelBuilder<?> channelBuilder) { channel = channelBuilder.build(); blockingStub = RateFinderGrpc.newBlockingStub(channel); } public Optional<Integer> getRate(long start, long end) { ParkingRatesProtos.RateResponse rate = blockingStub.find( ParkingRatesProtos.RateRequest.newBuilder() .setStart(start) .setEnd(end) .build() ); return Optional.ofNullable(rate.getExists() ? rate.getRate() : null); } } <file_sep>/docker-compose.yml version: '3' services: server: image: parking-rates/server:1.0 client: image: parking-rates/client:1.0 ports: - "4567:4567"<file_sep>/README.md # Parking Rates API ## Setup Clone this repository ``` $ git clone https://github.com/christherama/parking-rates-grpc $ cd parking-rates-grpc ``` Run unit tests ``` $ ./gradlew server:test client:test ``` Build Docker images ``` $ ./gradlew distDocker ``` Start containers ``` $ docker-compose up -d ``` Run integration tests ``` $ ./gradlew integration:test ``` Make a request ``` $ curl -X GET 'http://localhost:4567/rate?start=2015-07-01T07:00:00Z&end=2015-07-01T08:00:00Z' ``` ## References - Being that this was my first experience with gRPC, code inspiration was taken from [github.com/grpc/grpc-java](https://github.com/grpc/grpc-java).<file_sep>/client/src/main/java/io/rama/parking/response/ApiResponse.java package io.rama.parking.response; public interface ApiResponse { default String getStatus() { return "success"; } default Integer getRate() { return null; } } <file_sep>/client/build.gradle apply plugin: 'java' apply plugin: 'application' apply plugin: 'docker' group 'parking-rates' version '1.0' sourceCompatibility = 1.8 buildscript { repositories { jcenter() } dependencies { classpath 'se.transmode.gradle:gradle-docker:1.2' } } repositories { mavenCentral() } ext { protobufVersion = '3.5.1' } dependencies { compile project(':server') compile "com.sparkjava:spark-core:2.7.2" compile "com.google.protobuf:protobuf-java-util:${protobufVersion}" compile "io.grpc:grpc-netty-shaded:1.16.1" compile "io.grpc:grpc-protobuf:1.16.1" compile "io.grpc:grpc-stub:1.16.1" compile "com.fasterxml.jackson.core:jackson-databind:2.9.7" compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.7" compile "io.dropwizard.metrics:metrics-core:4.0.0" compile "org.projectlombok:lombok:1.18.4" testCompile "junit:junit:4.12" testCompile "com.despegar:spark-test:1.1.8" testCompile "org.mockito:mockito-core:2.23.0" } sourceSets { main { java { srcDirs '../server/build/generated/source/proto/main/grpc' srcDirs '../server/build/generated/source/proto/main/java' } } } mainClassName = 'io.rama.parking.RatesApi' distDocker { exposePort 4567 }<file_sep>/client/src/main/java/io/rama/parking/response/ErrorResponse.java package io.rama.parking.response; public class ErrorResponse implements ApiResponse { private String status; public ErrorResponse(String status) { this.status = status; } @Override public String getStatus() { return status; } } <file_sep>/server/src/main/java/io/rama/parking/RateInput.java package io.rama.parking; import lombok.Data; import java.util.List; @Data public class RateInput { private List<RateDto> rates; } <file_sep>/integration/src/test/java/io/rama/parking/RatesApiIntTest.java package io.rama.parking; import org.junit.Before; import org.junit.Test; import static io.rama.parking.ApiClient.ApiRateResponse; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class RatesApiIntTest { private ApiClient apiClient; @Before public void setup() { apiClient = new ApiClient("http://localhost:4567"); } @Test public void rateEndpoint_whenDateRangeHasRate_respondsWithRate() throws Exception{ ApiRateResponse response = apiClient.get("/rate?start=2018-11-13T09:00:00Z&end=2018-11-13T10:01:02Z"); assertThat(response.getCode(),is(200)); assertThat(response.getRate().getRate(),is(1500)); } @Test public void rateEndpoint_whenDateIsInvalid_respondsWith400() throws Exception { ApiRateResponse response = apiClient.get("/rate?start=2018-11-13T09:00:00Z&end=hello"); assertThat(response.getCode(),is(400)); } @Test public void rateEndpoint_whenRateIsNotFound_respondsWith404() throws Exception { ApiRateResponse response = apiClient.get("/rate?start=2018-11-13T09:00:00Z&end=2018-11-13T23:01:02Z"); assertThat(response.getCode(),is(404)); } } <file_sep>/client/src/test/java/io/rama/parking/RatesApiTest.java package io.rama.parking; import com.despegar.http.client.GetMethod; import com.despegar.http.client.HttpResponse; import com.despegar.sparkjava.test.SparkServer; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.ClassRule; import org.junit.Test; import spark.servlet.SparkApplication; import java.util.HashMap; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RatesApiTest { public static class ParkingRatesApiTestApplication implements SparkApplication { private RateService rateService = mock(RateService.class); public RateService getRateService() { return rateService; } @Override public void init() { new RatesApi(rateService); } } @ClassRule public static SparkServer<ParkingRatesApiTestApplication> testServer = new SparkServer<>(ParkingRatesApiTestApplication.class, 4567); @Test public void rateEndpoint_servesJson() throws Exception { GetMethod getRates = testServer.get("/rate?start=2015-07-01T07:00:00Z&end=2015-07-01T12:00:00Z", false); getRates.addHeader("Accept","application/json"); HttpResponse response = testServer.execute(getRates); assertThat(response.headers().get("Content-Type").get(0), is("application/json")); } @Test public void rateEndpoint_servesXml() throws Exception { GetMethod getRates = testServer.get("/rate?start=2015-07-01T07:00:00Z&end=2015-07-01T12:00:00Z", false); getRates.addHeader("Accept","application/xml"); HttpResponse response = testServer.execute(getRates); assertThat(response.headers().get("Content-Type").get(0), is("application/xml")); } @Test public void rateEndpoint_whenDateRangeHasRate_respondsWithRate() throws Exception{ when(testServer.getApplication().getRateService().getRate(any())).thenReturn(1500); GetMethod getRates = testServer.get("/rate?start=2018-11-13T09:00:00Z&end=2018-11-13T10:01:02Z", false); getRates.addHeader("Accept","application/json"); HttpResponse response = testServer.execute(getRates); RateDto dto = new ObjectMapper().readValue(response.body(), RateDto.class); assertThat(response.code(),is(200)); assertThat(dto.getRate(),is(1500)); } @Test public void rateEndpoint_whenDateIsInvalid_respondsWith400() throws Exception { GetMethod getRates = testServer.get("/rate?start=2015-07-01T07:00:00Z&end=hello", false); HttpResponse response = testServer.execute(getRates); assertThat(response.code(),is(400)); } @Test public void rateEndpoint_whenDateRangeSpansMultipleDays_respondsWith400() throws Exception { GetMethod getRates = testServer.get("/rate?start=2018-07-01T07:00:00Z&end=2018-07-02T09:00:00Z", false); HttpResponse response = testServer.execute(getRates); assertThat(response.code(), is(400)); } @Test public void metricsEndpoint_respondsWithMetrics() throws Exception { GetMethod getRates = testServer.get("/metrics", false); getRates.addHeader("Accept","application/json"); HttpResponse response = testServer.execute(getRates); TypeReference<HashMap<String, Object>> mapTypeRef = new TypeReference<HashMap<String, Object>>() {}; HashMap<String,Object> responseMap = new ObjectMapper().readValue(response.body(),mapTypeRef); assertThat(response.code(),is(200)); assertThat(responseMap.containsKey("metrics"),is(true)); } }
6e926ec9aba80c5c3bf18897659b3d70b12b368b
[ "Markdown", "Java", "YAML", "Gradle" ]
17
Gradle
christherama/parking-rates-grpc
19483f3c634b588959d8dbb5194836d01be3f417
bcfc66adcb085a9ad4dc8f2b715f5960a9242c6b
refs/heads/master
<file_sep>package com.thecloudyco.arcade; import java.util.ArrayList; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; public abstract class Game { private World world; private int minPlayersToStart; private int maxPlayers; protected boolean isRunning; protected boolean isStarting; private ArrayList<Player> Players = new ArrayList<Player>(); private ArrayList<Player> Spectators = new ArrayList<Player>(); public Game(int minPlayersToStart, int maxPlayers) { this.minPlayersToStart = minPlayersToStart; this.maxPlayers = maxPlayers; isRunning = false; } public int getMinPlayersToStart() { return minPlayersToStart; } public int getMaxPlayers() { return maxPlayers; } public boolean isGameRunning() { return isRunning; } public boolean isGameStarting() { return isStarting; } public void setGameStarting(boolean a) { isStarting = a; } public ArrayList<Player> getPlayers() { return Players; } public ArrayList<Player> getSpectators() { return Spectators; } public void addPlayer(Player player) { Players.add(player); } public void removePlayer(Player player) { Players.remove(player); } public void addSpectator(Player spec) { Spectators.add(spec); } public void removeSpectator(Player spec) { Spectators.remove(spec); } public abstract void startGame(); public abstract void stopGame(); public abstract void resetGame(); public void startCountdown() { for(Player pl : Bukkit.getOnlinePlayers()) { addPlayer(pl); } startGame(); isRunning = true; } public void setWorld(World w) { this.world = w; } public World getWorld() { return world; } } <file_sep>package com.thecloudyco.bw.cmd; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.thecloudyco.bw.Starter; import net.md_5.bungee.api.ChatColor; public class SetTeamSpawnCommand implements CommandExecutor { // /setgenspawn @Override public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] args) { if(!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "You must run this command in-game!"); return false; } Player pl = (Player) sender; String generator = args[0]; if(!Starter.getInstance().getConfig().getBoolean(pl.getWorld().getName() + ".active")) { sender.sendMessage(ChatColor.RED + "The map you are in is disabled from running the game!"); return false; } // // if(Starter.getInstance().getConfig().getDouble(pl.getWorld().getName() + ".generators." + generator + ".x") == 0) { // sender.sendMessage(ChatColor.RED + "The generator you requested, does not exist!"); // return false; // } Starter.getInstance().getConfig().set(pl.getWorld().getName() + ".spawnpoints." + generator + ".x", pl.getLocation().getX()); Starter.getInstance().getConfig().set(pl.getWorld().getName() + ".spawnpoints." + generator + ".y", pl.getLocation().getY()); Starter.getInstance().getConfig().set(pl.getWorld().getName() + ".spawnpoints." + generator + ".z", pl.getLocation().getZ()); sender.sendMessage(ChatColor.GREEN + "Done."); Starter.getInstance().saveConfig(); return true; } } <file_sep>package com.thecloudyco.bw.listener; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; public class BlockProtectionListener implements Listener { @EventHandler public void onBlockBreak(BlockBreakEvent event) { } } <file_sep>package com.thecloudyco.bw.cmd; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; public class GameStateCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] args) { return false; } } <file_sep>package com.thecloudyco.bw.listener; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; public class BedBreakListener implements Listener { @EventHandler public void onBedBreak(BlockBreakEvent ev) { if(!(ev.getBlock().getType() == Material.RED_BED)) { return; } // Figure out which team this bed belongs to } } <file_sep># Atticus' BedWars This project is a very much work-in-progress!! This is my custom version of Hypixel's BedWars I've been working on this as a personal project for a little while now, and I decided I'd release the source code to the public :) THIS IS MY FIRST TIME WRITING A MINIGAME BASED PLUGIN! I KNOW ITS BAD DONT JUDGE ME :)
5bf0418ebbd1750154d15adc26009f6cab1b7fb0
[ "Markdown", "Java" ]
6
Java
Aduhkiss/BedWarsGame
af4cb5b06af88499e93a5764d7494bde893aa5d1
acfcdd2d6f658705a7e0745e4b04eb87d45477fd
refs/heads/master
<file_sep>const io = require('socket.io'), server = io.listen(8000); let sequenceNumberByClient = new Map(); const alert = { incidentId: '109', event: 'nonErgant', category: 'security', areaDescription: 'cities', polygon: [1, 2, 3, 4], }; // event fired every time a new client connects: server.on('connection', socket => { console.info(`Client connected [id=${socket.id}]`); // initialize this client's sequence number sequenceNumberByClient.set(socket, 1); //socket.emit('missile', 'you are connected!'); // when socket disconnects, remove it from the list: socket.on('disconnect', () => { sequenceNumberByClient.delete(socket); console.info(`Client gone [id=${socket.id}]`); }); }); // sends each client its current sequence number setInterval(() => { for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) { client.emit(alert.event, alert); sequenceNumberByClient.set(client, sequenceNumber + 1); } }, 30000); <file_sep># hatraa-chrome_extension
5fbd5a615ce7a2207601c2db22fba6bb86510d44
[ "JavaScript", "Markdown" ]
2
JavaScript
danatsi/hatraa-chrome_extension
b2a2a300773bf9d536044bcd8e61e3f52b321982
55713b7b4d06c2542484d02d3a338fbe44c3a30d
refs/heads/master
<file_sep>json.extract! @saving, :id, :title, :description, :created_at, :updated_at <file_sep>class MasterCardMaping < ActiveRecord::Base # require_relative '../../../services/moneysend/services/CardMappingService' # require_relative '../../../services/moneysend/domain/card_mapping/CreateMapping' # require_relative '../../../services/moneysend/domain/card_mapping/CreateMappingRequest' # require_relative '../../../services/moneysend/domain/common/Address' # require_relative '../../../services/moneysend/domain/common/CardholderFullName' def self.service CardMappingService.new(SANDBOX_CONSUMER_KEY, TestUtils.new.get_private_key(SANDBOX), SANDBOX) end def get_private_key(environment) if environment.upcase == 'PRODUCTION' OpenSSL::PKCS12.new(File.open(PRODUCTION_PRIVATE_KEY_PATH),PRODUCTION_PRIVATE_KEY_PASSWORD).key else OpenSSL::PKCS12.new(File.open(SANDBOX_PRIVATE_KEY_PATH),SANDBOX_PRIVATE_KEY_PASSWORD).key end end def self.create_mapping_request(params) CreateMappingRequest.new end def self.inquire_mapping_request InquireMappingRequest.new end def self.update_mapping_request options = UpdateMappingRequestOptions.new options.mapping_id = inquire_mapping.mappings.mapping[0].mapping_id end end <file_sep>class StaticPagesController < ApplicationController def save end def spend end def earn end def askforfund @wallet = Wallet.all #MASTERCARD API # @create_mapping_request = MasterCardMaping.create_mapping_request(params) # @inquire_mapping_request = MasterCardMaping.inquire_mapping_request(params) # @update_mapping_request = MasterCardMaping.update_mapping_request(params) # payment_request = Transfer.payment_request(@create_mapping_request) # transfer_reversal = Transfer.transer_reversal_request(payment_request) end end <file_sep>require 'rubygems' require 'nokogiri' require 'open-uri' url = "http://www.lifehack.org/articles/money/22-simple-and-creative-ways-earn-money.html" doc = Nokogiri::HTML(open(url)) puts doc.at_css("title").text doc.css(".post-content").each do |post| puts post.at_css("h2").text end<file_sep># require 'mastercard_api' # SANDBOX_CONSUMER_KEY = '<KEY>' # # Path to the private key in .p12 format. # SANDBOX_PRIVATE_KEY_PATH = 'cacert.pem' # private_key = OpenSSL::PKCS12.new(File.open(SANDBOX_PRIVATE_KEY_PATH), '<password>').key # service = # Mastercard::Services::LostStolen::LostStolenService.new(SANDBOX_CONSUMER_KEY, # private_key, 'SANDBOX') # account = service.get_account('5343434343434343') # puts account.listed # puts account.reason<file_sep> class Transfer < ActiveRecord::Base # require_relative '../../../common/Environment' # require_relative '../../../services/moneysend/services/TransferService' # require_relative '../../../services/moneysend/domain/transfer/Transfer' # require_relative '../../../services/moneysend/domain/transfer/SenderAddress' # require_relative '../../../services/moneysend/domain/transfer/FundingCard' # require_relative '../../../services/moneysend/domain/transfer/FundingAmount' # require_relative '../../../services/moneysend/domain/transfer/ReceiverAddress' # require_relative '../../../services/moneysend/domain/transfer/ReceivingAmount' # require_relative '../../../services/moneysend/domain/transfer/CardAcceptor' # require_relative '../../../services/moneysend/domain/transfer/FundingMapped' # require_relative '../../../services/moneysend/domain/transfer/FundingAmount' # require_relative '../../../services/moneysend/domain/transfer/ReceivingMapped' # require_relative '../../../services/moneysend/domain/transfer/ReceivingCard' def self.service TransferService.new(SANDBOX_CONSUMER_KEY, TestUtils.new.get_private_key(SANDBOX), SANDBOX) end def get_private_key(environment) if environment.upcase == 'PRODUCTION' OpenSSL::PKCS12.new(File.open(PRODUCTION_PRIVATE_KEY_PATH),PRODUCTION_PRIVATE_KEY_PASSWORD).get_private_key else OpenSSL::PKCS12.new(File.open(SANDBOX_PRIVATE_KEY_PATH),SANDBOX_PRIVATE_KEY_PASSWORD).key end end def self.transfer_request_card TransferRequest.new end def self.payment_request_card PaymentRequest.new end def self.transaction_ref_generator a = 0 loop do p a = rand(2\**32..2*\*64-1).to_s a = a[0..a.length-1|0..a.length-1] break if a.length == 19 end a end def self.transfer_reversal_request transfer_reversal_request = TransferReversalRequest.new transfer_reversal_request.ica = '009674' transfer_reversal_request.transaction_reference = transfer.transaction_reference transfer_reversal_request.reversal_reason = 'FAILURE IN PROCESSING' end end
6117366826ba24c5ab6b8a5e30642a41ab96dbf3
[ "Ruby" ]
6
Ruby
purnima23/broq
b7a559160360dce0677918bee689d3f3910ec5f9
c969a4cbaa641d45dc125f790f5645f1d4060081
refs/heads/master
<file_sep>package server import ( "bytes" "crypto/rand" "crypto/tls" "encoding/gob" "github.com/gnicod/aion/scheduler" "log" "net" ) type Server struct { l net.Listener sch scheduler.Scheduler } func NewServer(sch scheduler.Scheduler) Server { // TODO path need to be read from a config cert, err := tls.LoadX509KeyPair("/home/ovski/certs/server.pem", "/home/ovski/certs/server.key") if err != nil { log.Fatalf("server: loadkeys: %s", err) } config := tls.Config{Certificates: []tls.Certificate{cert}} config.Rand = rand.Reader service := "0.0.0.0:8000" l, err := tls.Listen("tcp", service, &config) if err != nil { log.Fatalf("server: listen: %s", err) } log.Print("server: listening") serv := Server{l, sch} return serv } func (s *Server) Listen() { for { conn, err := s.l.Accept() if err != nil { log.Printf("server: accept: %s", err) break } defer conn.Close() log.Printf("server: accepted from %s", conn.RemoteAddr()) _, ok := conn.(*tls.Conn) if ok { log.Print("ok=true") } go s.serve(conn) } } func (s *Server) serve(c net.Conn) { dec := gob.NewDecoder(c) //t := &scheduler.Task{} t := Command{} dec.Decode(t) //s.sch.AddTask(t) //println("Command:", string(t.Command)) //println("Expression:", string(t.Expression)) res := Response{Content: "list"} var network bytes.Buffer enc := gob.NewEncoder(&network) err := enc.Encode(res) if err != nil { log.Fatal("encode error:", err) } _, err = c.Write(network.Bytes()) defer c.Close() if err != nil { log.Fatal("write error:", err) } } <file_sep>package client import ( "bytes" "crypto/tls" "encoding/gob" "github.com/gnicod/aion/scheduler" "github.com/gnicod/aion/server" "log" "net" ) type Client struct { conn net.Conn } func NewClient() Client { cert, err := tls.LoadX509KeyPair("/home/ovski/certs/client.pem", "/home/ovski/certs/client.key") if err != nil { log.Fatalf("server: loadkeys: %s", err) } config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true} conn, err := tls.Dial("tcp", "127.0.0.1:8000", &config) if err != nil { log.Fatalf("client: dial: %s", err) } log.Println("client: connected to: ", conn.RemoteAddr()) /* state := conn.ConnectionState() for _, v := range state.PeerCertificates { fmt.Println(x509.MarshalPKIXPublicKey(v.PublicKey)) fmt.Println(v.Subject) } */ client := Client{conn} go client.reader() return client } func (c *Client) reader() { reply := make([]byte, 256) n, err := c.conn.Read(reply) if err != nil { log.Fatal("write error:", err) } log.Printf("client: got %q (%d bytes)", string(reply[:n]), n) log.Print("client: exiting") } func (c *Client) AddTask(t scheduler.Task) { var network bytes.Buffer enc := gob.NewEncoder(&network) err := enc.Encode(t) if err != nil { log.Fatal("encode error:", err) } _, err = c.conn.Write(network.Bytes()) defer c.conn.Close() if err != nil { log.Fatal("add task write error:", err) } } func (c *Client) SendCommand(command server.Command) { var network bytes.Buffer enc := gob.NewEncoder(&network) err := enc.Encode(command) if err != nil { log.Fatal("encode error:", err) } _, err = c.conn.Write(network.Bytes()) dec := gob.NewDecoder(c.conn) //t := &scheduler.Task{} resp := server.Response{} dec.Decode(resp) log.Print(resp) c.reader() defer c.conn.Close() if err != nil { log.Fatal("add task write error:", err) } } <file_sep>package scheduler import ( "fmt" "github.com/gorhill/cronexpr" "time" ) type Scheduler struct { Tasks []*Task } func NewScheduler() Scheduler { //read the crontab file scheduler := Scheduler{[]*Task{}} return scheduler } func (s *Scheduler) AddTask(task *Task) { nextTime := cronexpr.MustParse(task.Expression).Next(time.Now()) nowTime := time.Now().UTC() var duration time.Duration = nextTime.Sub(nowTime) ticker := time.NewTicker(duration) fmt.Println(duration) task.Id = len(s.Tasks) s.Tasks = append(s.Tasks, task) fmt.Println(ticker.C) go func() { for t := range ticker.C { fmt.Println("tick at", t) fmt.Println("Task", task.Id) fmt.Println(task.Command) ticker.Stop() s.AddTask(task) } }() } <file_sep>package server var ADDTASK = 0 var LISTTASKS = 1 type Command struct { Name int Optionals struct{} } type Response struct { Content string } <file_sep>aion ==== Start the server ``` aion --start ``` <file_sep>package scheduler import ( "time" ) type Task struct { Expression string Command string Id int ticker time.Ticker } func NewTask(Expression string, Command string) Task { t := Task{Expression, Command, 0, time.Ticker{}} return t } <file_sep>package main import ( "flag" "fmt" "github.com/gnicod/aion/client" "github.com/gnicod/aion/scheduler" "github.com/gnicod/aion/server" ) func main() { f_start := flag.Bool("start", false, "a bool") f_list := flag.Bool("list", false, "list tasks") flag.Parse() if *f_start { sch := scheduler.NewScheduler() startServer(sch) return } client := client.NewClient() if *f_list { fmt.Println("connect to the server and list tasks") client.SendCommand(server.Command{Name: server.LISTTASKS}) return } //TODO send a command containing a task t1 := scheduler.NewTask("*/1 * * * *", "ls /tmp") client.AddTask(t1) } func startServer(sch scheduler.Scheduler) { fmt.Println("start server") server := server.NewServer(sch) for { server.Listen() } }
9d09422a9b4fc90bef83868641216c2ee1b5a341
[ "Markdown", "Go" ]
7
Go
gnicod/aion
548bc3806c69b5b9e5617adc30c74512ef341b7b
c1359ccaf3acdc9f982626c1148e53d4a5e8c789
refs/heads/master
<file_sep>import OAuth from "oauth-1.0a"; import crypto from "crypto"; import fetch, { Response } from "node-fetch"; import strictUriEncode from "strict-uri-encode"; export async function tweet( msg: string, consumerKey: string, consumerSecret: string, tokenKey: string, tokenSecret: string ): Promise<Response> { const requestData = { url: `https://api.twitter.com/1.1/statuses/update.json?status=${strictUriEncode( msg )}`, method: "POST", }; const oauth = new OAuth({ consumer: { key: consumerKey, secret: consumerSecret, }, // eslint-disable-next-line @typescript-eslint/camelcase signature_method: "HMAC-SHA1", // eslint-disable-next-line @typescript-eslint/camelcase hash_function(base_string, key) { return crypto .createHmac("sha1", key) .update(base_string) .digest("base64"); }, }); return fetch(requestData.url, { method: requestData.method, headers: { ...oauth.toHeader( oauth.authorize(requestData, { key: tokenKey, secret: tokenSecret, }) ), }, }); } // test // tweet( // `how are you I am OK ? ${new Date().toTimeString()}`, // ) // .then(res => { // console.log(res.status); // return res.text(); // }) // .then(res => console.log(res)) // .catch(err => { // console.log(err); // }); <file_sep>import path from "node:path"; import url from "node:url"; const __dirname = path.dirname(url.fileURLToPath(import.meta.url)); export default { mode: "development", target: "node16", entry: { PullShareAction: "./src/PullShareAction.ts", ConfirmationAction: "./src/ConfirmationAction.ts", }, devtool: "inline-source-map", module: { rules: [ { test: /\.tsx?$/, use: "ts-loader", exclude: /node_modules/, }, ], }, resolve: { extensions: [".ts", ".js", ".tsx"], extensionAlias: { '.js': ['.ts', '.js'], }, alias: { "universal-user-agent": path.resolve( __dirname, "node_modules/universal-user-agent/dist-node/index.js" ), }, }, experiments: { outputModule: true, // Linked with `output.library.type = 'module'` }, output: { path: path.resolve(__dirname, "dist"), filename: "[name].js", library: { type: 'module', }, }, devServer: { contentBase: path.join(__dirname, "dist"), port: 8000, }, }; <file_sep>// searched papers, which is used in several purpose export type SearchedPaper = { id: string; title: string; summary: string; }; export type ArXivSearchResults = SearchedPaper[]; // points: this is merely arXiv search result storage (status is for refined search) export type candidate = "candidate"; export type resolved = "confirmed" | "excluded"; export type Identity = { repository: "arXiv"; article: string; version: string; }; export type ArXivRecord = { id: Identity; status: candidate | resolved; }; export type ArXivStorage = ArXivRecord[]; <file_sep># Voice Conversion Lab Collect "Voice Conversion" researches ## Contents - VC Paper Introduction in [Twitter@VoiceConversion](https://twitter.com/VoiceConversion) - new VC paper candidate: offer you "latest" ArXiv VC paper candidates (within 1-hour after publication) - VC paper: confirmed to be "VC" paper by human eye ## System Overview **Autonomous paper candidate collection + community paper review/confirmation** Paper information is automatically and routinely collected by ArXiv Search through ArXiv api in GitHub Actions. This information is published as "candidate" in Twitter. Candidate information is collected in Issue of this repository, and community can comment "whether the paper is VC or not." Bot autonomously detect comment by community, then process the confirmation. ## Developments 1st gen. established. <file_sep>import { updateArticleStatus } from "./updateArticles.js"; import type { ArXivStorage } from "./domain.js"; test("updateArticles", () => { const input: ArXivStorage = [ { id: { repository: "arXiv", article: "1", version: "1" }, status: "candidate", }, { id: { repository: "arXiv", article: "2", version: "2" }, status: "candidate", }, ]; // replace based on index const expected: ArXivStorage = [ { id: { repository: "arXiv", article: "1", version: "1" }, status: "candidate", }, { id: { repository: "arXiv", article: "2", version: "2" }, status: "confirmed", }, ]; expect(updateArticleStatus(input, "2", "confirmed")).toStrictEqual(expected); }); <file_sep>import type { JestConfigWithTsJest } from 'ts-jest'; const jestConfig: JestConfigWithTsJest = { preset: "ts-jest/presets/js-with-ts", resolver: "ts-jest-resolver", testEnvironment: "node", testPathIgnorePatterns: ["/node_modules/", "<rootDir>/dist/"], extensionsToTreatAsEsm: ['.ts'], // TypeScript ESmodule transform: { '^.+\\.[tj]sx?$': [ 'ts-jest', { useESM: true, }, ], }, }; export default jestConfig; <file_sep>import fetch from "node-fetch"; import { xml2json } from "xml-js"; import type { ArXivSearchResults, SearchedPaper } from "./domain.js"; /** * Remove new lines and long white spaces after them. */ export function removeNewline(str: string): string { const regex = /\n +/g; return str.replaceAll(regex, ' '); } export async function searchArXiv(): Promise<ArXivSearchResults> { const res = await fetch( 'http://export.arxiv.org/api/query?search_query="voice+conversion"&max_results=1000' ); const resTxt = await res.text(); const resJson = JSON.parse( xml2json(resTxt, { compact: true, }) ); return resJson.feed.entry.map( //@ts-ignore (result): SearchedPaper => ({ id: result.id._text, title: removeNewline(result.title._text), summary: result.summary._text, }) ); } export async function searchArXivByID(id: string): Promise<SearchedPaper> { const res = await fetch( `http://export.arxiv.org/api/query?id_list=${id}&max_results=1000` ); const resTxt = await res.text(); const resJson = JSON.parse( xml2json(resTxt, { compact: true, }) ); return { id: resJson.feed.entry.id._text, title: removeNewline(resJson.feed.entry.title._text), summary: resJson.feed.entry.summary._text, }; } import * as url from 'node:url'; if (import.meta.url.startsWith('file:') && process.argv[1] === url.fileURLToPath(import.meta.url)) { (async () => { const res = await searchArXivByID("2302.08296v1"); console.log(res) })(); } <file_sep>import { removeNewline } from "./arXivSearch.js"; test("removeNewline", () => { const source = 'hello.\n I am Panda.'; const target = 'hello. I am Panda.'; expect(removeNewline(source)).toStrictEqual(target); }); <file_sep>{ "extends": "@tsconfig/node16-strictest-esm/tsconfig.json", "compilerOptions": { "outDir": "./dist/", "sourceMap": true, // ESModules "module": "node16", "moduleResolution": "node16", // Loose type checking "allowUnreachableCode": true, "noUnusedLocals": false, "noUnusedParameters": false, } } <file_sep>import type { ArXivStorage, resolved, Identity } from "./domain.js"; import { produce } from "immer"; export function arXivID2identity(arXivID: string): Identity { const result = /http:\/\/arxiv.org\/abs\/(\d+\.\d+)v(\d+)/.exec(arXivID); if (result && result.length >= 3) { if (result[1] === undefined || result[2] === undefined) throw new Error("Must correct, for Type checking"); return { repository: "arXiv", article: result[1], version: result[2], }; } else { throw new Error("arXivID parse error"); } } export function updateArticleStatus( storage: ArXivStorage, articleID: string, status: resolved ): ArXivStorage { return produce(storage, (draft) => { // find index const index = draft.findIndex((paper) => paper.id.article === articleID); const paper = draft[index]; if (paper === undefined) throw new Error("Must correct, for Type checking"); paper.status = status; }); } <file_sep>import * as core from "@actions/core"; import * as github from "@actions/github"; import { searchArXiv } from "./arXivSearch.js"; import type { ArXivStorage, ArXivSearchResults, ArXivRecord, SearchedPaper, Identity, } from "./domain.js"; import { tweet } from "./twitter.js"; import { arXivID2identity } from "./updateArticles.js"; function findNewPaper( searchResults: ArXivSearchResults, storage: ArXivStorage ): [SearchedPaper, ArXivRecord] | undefined { // find non-match (==new) arXivPaper (version update is excluded) const newPapers = searchResults.filter((paper) => { const articleID = arXivID2identity(paper.id).article; return storage.every((record) => record.id.article !== articleID); }); if (newPapers.length === 0) { return undefined; } else { const theNewPaper = newPapers[0]; if (theNewPaper === undefined) throw new Error("Must correct, for Type checking"); const identity = arXivID2identity(theNewPaper.id); return [ theNewPaper, { id: identity, status: "candidate", }, ]; } } /** * Find versionUp-ed paper in arXiv */ function findUpdatedPaper( searchResults: ArXivSearchResults, storage: ArXivStorage ): [SearchedPaper, Identity] | undefined { // const updatedPaperCand = searchResults.find((paper) => { const paperID = arXivID2identity(paper.id); // There is a record which match the articleID but not match version in storage return storage.some( (record) => record.id.article === paperID.article && record.id.version !== paperID.version ); }); if (updatedPaperCand === undefined) { return undefined; } else { const identity = arXivID2identity(updatedPaperCand.id); return [updatedPaperCand, identity]; } } async function run(): Promise<void> { /* Run */ // fetch search result const searchResults = await searchArXiv(); // fetch storage const octokit = github.getOctokit(core.getInput("token")); const contents = await octokit.rest.repos.getContent({ ...github.context.repo, path: "arXivSearches.json", }); const storage: ArXivStorage = JSON.parse( Buffer.from( //@ts-ignore contents.data.content, //@ts-ignore contents.data.encoding ).toString() ); /*Check new VC paper candidate: - Search new paper - Update storage - Commit to database - Open review issue - Tweet new candidate */ // Search new paper const newPaperCand = findNewPaper(searchResults, storage); if (newPaperCand !== undefined) { // Update storage - updated const theNewPaper = newPaperCand[0]; const newRecord = newPaperCand[1]; storage.push(newPaperCand[1]); // Commit to database - commit updated storage to the VCLab repository on GitHub const storageBlob = Buffer.from(JSON.stringify(storage, undefined, 2)); await octokit.rest.repos .createOrUpdateFileContents({ ...github.context.repo, path: "arXivSearches.json", message: `Add new arXiv search result ${newRecord.id.article}`, content: storageBlob.toString("base64"), // @ts-ignore sha: contents.data.sha, }) .catch((err) => core.setFailed(err)); console.log("storage updated."); // Open review issue - open candidate check issue in VCLab repository await octokit.rest.issues .create({ ...github.context.repo, title: `'Voice Conversion' paper candidate ${newRecord.id.article}`, body: `Please check whether this paper is about 'Voice Conversion' or not.\n## article info.\n- title: **${theNewPaper.title}**\n- summary: ${theNewPaper.summary}\n- id: ${theNewPaper.id}\n## judge\nWrite [vclab::confirmed] or [vclab::excluded] in comment.`, }) .catch((err) => core.setFailed(err)); console.log("issue created."); // Tweet new candidate - tweet candidate info on Twitter@VoiceConversion await tweet( `[new VC paper candidate]\n"${theNewPaper.title}"\narXiv: arxiv.org/abs/${newRecord.id.article}`, core.getInput("twi-cons-key"), core.getInput("twi-cons-secret"), core.getInput("twi-token-key"), core.getInput("twi-token-secret") ) .then((res) => { console.log(res.status); return res.text(); }) .catch((err) => { core.setFailed(err); }); console.log("tweet created."); // Finish this action return; } // paper update (if newPaper, already returned after Tweet) const updatedPaperCand = findUpdatedPaper(searchResults, storage); if (updatedPaperCand !== undefined) { const updatedPaper = updatedPaperCand[0]; const paperID = updatedPaperCand[1]; // storage update (version only update) const indexInStorage = storage.findIndex( (record) => record.id.article === paperID.article ); if (indexInStorage === -1) { throw new Error("this should exist"); } const record = storage[indexInStorage]; if(record === undefined){ throw new Error("this should exist"); } record.id.version = paperID.version; // commit storage update const blob = Buffer.from(JSON.stringify(storage, undefined, 2)); await octokit.rest.repos .createOrUpdateFileContents({ ...github.context.repo, path: "arXivSearches.json", message: `Update arXiv search result ${paperID.article}@${paperID.version}`, content: blob.toString("base64"), // @ts-ignore sha: contents.data.sha, }) .catch((err) => core.setFailed(err)); console.log("storage updated (version update)"); // do NOT open issue because version up do not change "VC paper or not" // tweet candidate info await tweet( `[paper version up]\n"${updatedPaper.title}"\narXiv: arxiv.org/abs/${paperID.article}`, core.getInput("twi-cons-key"), core.getInput("twi-cons-secret"), core.getInput("twi-token-key"), core.getInput("twi-token-secret") ) .then((res) => { console.log(res.status); return res.text(); }) .catch((err) => { core.setFailed(err); }); console.log("tweet created."); return; } } run(); <file_sep>import * as core from "@actions/core"; import * as github from "@actions/github"; import { searchArXivByID } from "./arXivSearch.js"; import type { ArXivStorage } from "./domain.js"; import { tweet } from "./twitter.js"; import type * as WebhooksApi from "@octokit/webhooks"; import { updateArticleStatus, arXivID2identity } from "./updateArticles.js"; async function run(): Promise<void> { //@ts-ignore const issueCommentPayload: WebhooksApi.WebhookPayloadIssueComment = github.context.payload; // extract id const idRegExp = /id: ([a-z\d.:\/]+)/; const regResult = idRegExp.exec(issueCommentPayload.issue.body); // regResult == null means the issue is not for article confirmation if (regResult != null) { const arXivID = regResult[1]; if(arXivID === undefined) throw new Error("Must correct, for Type checking"); // extract judge const c = /\[vclab::confirmed\]|\[confirmed\]|vclab::confirmed/; const e = /\[vclab::excluded\]|\[excluded\]|vclab::excluded/; const isC = c.exec(issueCommentPayload.comment.body); const isE = e.exec(issueCommentPayload.comment.body); // make thanks toward contribution if (isC !== null || isE !== null) { const octokit = github.getOctokit(core.getInput("token")); // reply thunks in comment await octokit.rest.issues .createComment({ ...github.context.repo, // eslint-disable-next-line @typescript-eslint/camelcase issue_number: issueCommentPayload.issue.number, body: `Thunk you very much for contribution!\nYour judgement is refrected in [arXivSearches.json](https://github.com/tarepan/VoiceConversionLab/blob/master/arXivSearches.json), and is going to be used for VCLab's activity.\nThunk you so much.`, }) .catch((err) => core.setFailed(err)); // close the issue octokit.rest.issues.update({ ...github.context.repo, // eslint-disable-next-line @typescript-eslint/camelcase issue_number: issueCommentPayload.issue.number, state: "closed", }); // update store //// fetch storage const contents = await octokit.rest.repos.getContent({ ...github.context.repo, path: "arXivSearches.json", }); const storage: ArXivStorage = JSON.parse( Buffer.from( //@ts-ignore contents.data.content, //@ts-ignore contents.data.encoding ).toString() ); //// update storage const judgeResult = isC !== null ? "confirmed" : "excluded"; const identity = arXivID2identity(arXivID); const newStorage = updateArticleStatus( storage, identity.article, judgeResult ); //// commit storage update const blob = Buffer.from(JSON.stringify(newStorage, undefined, 2)); await octokit.rest.repos .createOrUpdateFileContents({ ...github.context.repo, path: "arXivSearches.json", message: `Add arXiv paper confirmation ${identity.repository}-${identity.article}`, content: blob.toString("base64"), // @ts-ignore sha: contents.data.sha, }) .catch((err) => core.setFailed(err)); // Tweet if "confirmed" (== VC paper) if (isC !== null) { console.log("is [vclab::confirmed]"); const identity = arXivID2identity(arXivID); const arXivSearchID = `${identity.article}v${identity.version}`; const paper = await searchArXivByID(arXivSearchID); const content = `[[VC paper]]\n"${paper.title}"\narXiv: arxiv.org/abs/${identity.article}`; // tweet confirmed paper await tweet( content, core.getInput("twi-cons-key"), core.getInput("twi-cons-secret"), core.getInput("twi-token-key"), core.getInput("twi-token-secret") ) .then((res) => { console.log(res.status); return res.text(); }) .catch((err) => { core.setFailed(err); }); console.log("tweet created."); } else if (isE !== null) { console.log("is [vclab::excluded]"); } } else { console.log("non confirmation comment"); } } } run();
d1cda562532688d7c157225eb6c683c0493e7aa5
[ "JavaScript", "TypeScript", "JSON with Comments", "Markdown" ]
12
TypeScript
tarepan/VoiceConversionLab
3c25043ba18e815e210cc60283e875bc25fd6447
24923282da0856d01dca739caba1db3cd8832fd4
refs/heads/master
<repo_name>dimdum354/Algoritma-Lingkaran<file_sep>/Lingkaran/Source.cpp // Algoritma lingkaran #include<GL\freeglut.h> // Prosedur void init(); void display(); void lingkaran(); // Posisi pada window int window_x; int window_y; // Ukuran pada window int window_width = 500; int window_height = 500; // Judul pada window char *judul_window = "Algoritma Lingkaran"; void main(int argc, char **argv) { // Inisialisasi Graphic Library Utility Toolkit glutInit(&argc, argv); // Set posisi window supaya berada di tengah window_x = (glutGet(GLUT_SCREEN_WIDTH) - window_width) / 2; window_y = (glutGet(GLUT_SCREEN_HEIGHT) - window_height) / 2; glutInitWindowSize(window_width, window_height); // Set ukuran window glutInitWindowPosition(window_x, window_y); // Set posisi window glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); // Set display RGB dan double buffer glutCreateWindow(judul_window); init(); // Menjalankan fungsi init glutDisplayFunc(display); // Set fungsi display glutMainLoop(); // Set loop pemrosesan GLUT } void init() { glClearColor(0.0, 0.0, 0.0, 0.0); // Set warna background glColor3f(1.0, 1.0, 1.0); // Set warna titik glPointSize(2.0); // Set ukuran titik glMatrixMode(GL_PROJECTION); // Set mode matriks yang digunakan glLoadIdentity(); // Load matriks identitas gluOrtho2D(0.0, 600.0, 0.0, 600.0); // Set ukuran viewing window } void display() { glClear(GL_COLOR_BUFFER_BIT); // Clear color lingkaran(); // Menjalankan fungsi lingkaran glutSwapBuffers(); // Swap buffer } void lingkaran() { // Menentukan titik pusat dan jari-jari int r = 150, xc = 200, yc = 200, p, x_lingkaran = 0, y_lingkaran, i; // Menghitung p awal dan set nilai awal untuk x dan y p = 1 - r; y_lingkaran = r; glBegin(GL_POINTS); // Untuk mendeklarasikan titik awal for(i = x_lingkaran; i < y_lingkaran; i++) { if(p < 0) // Kondisi jika p lebih kecil dari 0 { x_lingkaran = x_lingkaran + 1; y_lingkaran; p = p + 2 * x_lingkaran + 1; } else // Kondisi jika p lebih besar sama dengan 0 { x_lingkaran = x_lingkaran + 1; y_lingkaran = y_lingkaran - 1; p = p + 2 * (x_lingkaran - y_lingkaran) + 1; } glVertex2i(xc + x_lingkaran, yc + y_lingkaran); glVertex2i(xc - x_lingkaran, yc + y_lingkaran); glVertex2i(xc + x_lingkaran, yc - y_lingkaran); glVertex2i(xc - x_lingkaran, yc - y_lingkaran); glVertex2i(xc + y_lingkaran, yc + x_lingkaran); glVertex2i(xc - y_lingkaran, yc + x_lingkaran); glVertex2i(xc + y_lingkaran, yc - x_lingkaran); glVertex2i(xc - y_lingkaran, yc - x_lingkaran); } glEnd(); glFlush(); }
2f84e40183705ac264db411ae9f433e43dd56e2e
[ "C++" ]
1
C++
dimdum354/Algoritma-Lingkaran
f7ad7656e43c9df8d67b3bf814bdc3c7452b515f
763a7104e081c35d1228ebc00bdb0287b7226d5c
refs/heads/master
<repo_name>bratsche/clang<file_sep>/test/CodeGen/array.c // RUN: clang-cc -emit-llvm %s -o %t int f() { int a[2]; a[0] = 0; } int f2() { int x = 0; int y = 1; int a[10] = { y, x, 2, 3}; int b[10] = { 2,4,x,6,y,8}; int c[5] = { 0,1,2,3}; } <file_sep>/include/clang/Makefile LEVEL = ../../../.. DIRS := Basic include $(LEVEL)/Makefile.common <file_sep>/test/CodeGen/func-return-member.c // RUN: clang-cc -emit-llvm < %s 2>&1 | not grep 'cannot codegen this l-value expression yet' struct frk { float _Complex c; int x; }; struct faz { struct frk f; }; struct fuz { struct faz f; }; extern struct fuz foo(void); int X; struct frk F; float _Complex C; void bar(void) { X = foo().f.f.x; } void bun(void) { F = foo().f.f; } void ban(void) { C = foo().f.f.c; } <file_sep>/test/Preprocessor/expr_comma.c // Comma is not allowed in C89 // RUN: not clang-cc -E %s -std=c89 -pedantic-errors && // Comma is allowed if unevaluated in C99 // RUN: clang-cc -E %s -std=c99 -pedantic-errors // PR2279 #if 0? 1,2:3 #endif <file_sep>/test/Preprocessor/pragma_unknown.c // RUN: clang-cc -E %s | grep '#pragma foo bar' // GCC doesn't expand macro args for unrecognized pragmas. #define bar xX #pragma foo bar <file_sep>/test/Analysis/uninit-vals-ps.c // RUN: clang-cc -analyze -checker-cfref -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify %s struct FPRec { void (*my_func)(int * x); }; int bar(int x); int f1_a(struct FPRec* foo) { int x; (*foo->my_func)(&x); return bar(x)+1; // no-warning } int f1_b() { int x; return bar(x)+1; // expected-warning{{Pass-by-value argument in function call is undefined.}} } int f2() { int x; if (x+1) // expected-warning{{Branch}} return 1; return 2; } int f2_b() { int x; return ((x+1)+2+((x))) + 1 ? 1 : 2; // expected-warning{{Branch}} } int f3(void) { int i; int *p = &i; if (*p > 0) // expected-warning{{Branch condition evaluates to an uninitialized value}} return 0; else return 1; } void f4_aux(float* x); float f4(void) { float x; f4_aux(&x); return x; // no-warning } struct f5_struct { int x; }; void f5_aux(struct f5_struct* s); int f5(void) { struct f5_struct s; f5_aux(&s); return s.x; // no-warning } int ret_uninit() { int i; int *p = &i; return *p; // expected-warning{{Uninitialized or undefined return value returned to caller.}} } // <rdar://problem/6451816> typedef unsigned char Boolean; typedef const struct __CFNumber * CFNumberRef; typedef signed long CFIndex; typedef CFIndex CFNumberType; typedef unsigned long UInt32; typedef UInt32 CFStringEncoding; typedef const struct __CFString * CFStringRef; extern Boolean CFNumberGetValue(CFNumberRef number, CFNumberType theType, void *valuePtr); extern CFStringRef CFStringConvertEncodingToIANACharSetName(CFStringEncoding encoding); CFStringRef rdar_6451816(CFNumberRef nr) { CFStringEncoding encoding; // &encoding is casted to void*. This test case tests whether or not // we properly invalidate the value of 'encoding'. CFNumberGetValue(nr, 9, &encoding); return CFStringConvertEncodingToIANACharSetName(encoding); // no-warning } <file_sep>/test/Sema/block-syntax-error.c // RUN: clang-cc %s -fsyntax-only -verify -fblocks void (^noop)(void); void somefunction() { noop = ^noop; // expected-error {{type name requires a specifier or qualifier}} expected-error {{expected expression}} } <file_sep>/test/SemaCXX/aggregate-initialization.cpp // RUN: clang-cc -fsyntax-only -verify -std=c++98 %s // Verify that we can't initialize non-aggregates with an initializer // list. struct NonAggr1 { NonAggr1(int) { } int m; }; struct Base { }; struct NonAggr2 : public Base { int m; }; class NonAggr3 { int m; }; struct NonAggr4 { int m; virtual void f(); }; NonAggr1 na1 = { 17 }; // expected-error{{initialization of non-aggregate type 'struct NonAggr1' with an initializer list}} NonAggr2 na2 = { 17 }; // expected-error{{initialization of non-aggregate type 'struct NonAggr2' with an initializer list}} NonAggr3 na3 = { 17 }; // expected-error{{initialization of non-aggregate type 'class NonAggr3' with an initializer list}} NonAggr4 na4 = { 17 }; // expected-error{{initialization of non-aggregate type 'struct NonAggr4' with an initializer list}} <file_sep>/test/Sema/deref.c // RUN: clang-cc -fsyntax-only -verify -std=c90 %s void foo (void) { struct b; struct b* x = 0; struct b* y = &*x; } void foo2 (void) { typedef int (*arrayptr)[]; arrayptr x = 0; arrayptr y = &*x; } void foo3 (void) { void* x = 0; void* y = &*x; // expected-error{{address expression must be an lvalue or a function designator}} } extern const void cv1; const void *foo4 (void) { return &cv1; } extern void cv2; void *foo5 (void) { return &cv2; // expected-error{{address expression must be an lvalue or a function designator}} } typedef const void CVT; extern CVT cv3; const void *foo6 (void) { return &cv3; } <file_sep>/test/CodeGen/2008-07-30-implicit-initialization.c // RUN: clang-cc -triple i386-unknown-unknown --emit-llvm-bc -o - %s | opt --std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32" %t | count 2 && // RUN: grep "ret i32 0" %t | count 2 // <rdar://problem/6113085> struct s0 { int x, y; }; int f0() { struct s0 x = {0}; return x.y; } #if 0 /* Optimizer isn't smart enough to reduce this since we use memset. Hrm. */ int f1() { struct s0 x[2] = { {0} }; return x[1].x; } #endif int f2() { int x[2] = { 0 }; return x[1]; } <file_sep>/test/Parser/cxx-try.cpp // RUN: clang-cc -fsyntax-only -verify %s void f() { try { ; } catch(int i) { ; } catch(...) { } } void g() { try; // expected-error {{expected '{'}} try {} catch; // expected-error {{expected '('}} try {} catch (...); // expected-error {{expected '{'}} try {} catch {} // expected-error {{expected '('}} } <file_sep>/test/CodeGen/PR3613-static-decl.c // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm -o %t %s && // RUN: grep '@g0 = internal global .struct.s0 <{ i32 3 }>' %t | count 1 struct s0 { int a; }; static struct s0 g0; static int f0(void) { return g0.a; } static struct s0 g0 = {3}; void *g1 = f0; <file_sep>/test/SemaCXX/new-delete.cpp // RUN: clang-cc -fsyntax-only -verify %s #include <stddef.h> struct S // expected-note {{candidate}} { S(int, int, double); // expected-note {{candidate}} S(double, int); // expected-note 2 {{candidate}} S(float, int); // expected-note 2 {{candidate}} }; struct T; // expected-note{{forward declaration of 'struct T'}} struct U { // A special new, to verify that the global version isn't used. void* operator new(size_t, S*); }; struct V : U { }; void* operator new(size_t); // expected-note 2 {{candidate}} void* operator new(size_t, int*); // expected-note 3 {{candidate}} void* operator new(size_t, float*); // expected-note 3 {{candidate}} void good_news() { int *pi = new int; float *pf = new (pi) float(); pi = new int(1); pi = new int('c'); const int *pci = new const int(); S *ps = new S(1, 2, 3.4); ps = new (pf) (S)(1, 2, 3.4); S *(*paps)[2] = new S*[*pi][2]; ps = new (S[3])(1, 2, 3.4); typedef int ia4[4]; ia4 *pai = new (int[3][4]); pi = ::new int; U *pu = new (ps) U; // This is xfail. Inherited functions are not looked up currently. //V *pv = new (ps) V; } struct abstract { virtual ~abstract() = 0; }; void bad_news(int *ip) { int i = 1; (void)new; // expected-error {{missing type specifier}} (void)new 4; // expected-error {{missing type specifier}} (void)new () int; // expected-error {{expected expression}} (void)new int[1.1]; // expected-error {{array size expression must have integral or enumerated type, not 'double'}} (void)new int[1][i]; // expected-error {{only the first dimension}} (void)new (int[1][i]); // expected-error {{only the first dimension}} (void)new int(*(S*)0); // expected-error {{incompatible type initializing}} (void)new int(1, 2); // expected-error {{initializer of a builtin type can only take one argument}} (void)new S(1); // expected-error {{no matching constructor}} (void)new S(1, 1); // expected-error {{call to constructor of 'S' is ambiguous}} (void)new const int; // expected-error {{must provide an initializer}} (void)new float*(ip); // expected-error {{incompatible type initializing 'int *', expected 'float *'}} // Undefined, but clang should reject it directly. (void)new int[-1]; // expected-error {{array size is negative}} (void)new int[*(S*)0]; // expected-error {{array size expression must have integral or enumerated type, not 'struct S'}} (void)::S::new int; // expected-error {{expected unqualified-id}} (void)new (0, 0) int; // expected-error {{no matching function for call to 'operator new'}} (void)new (0L) int; // expected-error {{call to 'operator new' is ambiguous}} // This must fail, because the member version shouldn't be found. (void)::new ((S*)0) U; // expected-error {{no matching function for call to 'operator new'}} (void)new (int[]); // expected-error {{array size must be specified in new expressions}} (void)new int&; // expected-error {{cannot allocate reference type 'int &' with new}} // Some lacking cases due to lack of sema support. } void good_deletes() { delete (int*)0; delete [](int*)0; delete (S*)0; ::delete (int*)0; } void bad_deletes() { delete 0; // expected-error {{cannot delete expression of type 'int'}} delete [0] (int*)0; // expected-error {{expected ']'}} \ // expected-note {{to match this '['}} delete (void*)0; // expected-error {{cannot delete expression}} delete (T*)0; // expected-warning {{deleting pointer to incomplete type}} ::S::delete (int*)0; // expected-error {{expected unqualified-id}} } <file_sep>/include/clang/Analysis/PathSensitive/Environment.h //== Environment.h - Map from Stmt* to Locations/Values ---------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defined the Environment and EnvironmentManager classes. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_ENVIRONMENT_H #define LLVM_CLANG_ANALYSIS_ENVIRONMENT_H // For using typedefs in StoreManager. Should find a better place for these // typedefs. #include "clang/Analysis/PathSensitive/Store.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/SmallVector.h" #include "clang/Analysis/PathSensitive/SVals.h" #include "llvm/Support/Allocator.h" #include "llvm/ADT/FoldingSet.h" namespace clang { class EnvironmentManager; class BasicValueFactory; class LiveVariables; class Environment : public llvm::FoldingSetNode { private: friend class EnvironmentManager; // Type definitions. typedef llvm::ImmutableMap<Stmt*,SVal> BindingsTy; // Data. BindingsTy SubExprBindings; BindingsTy BlkExprBindings; Environment(BindingsTy seb, BindingsTy beb) : SubExprBindings(seb), BlkExprBindings(beb) {} public: typedef BindingsTy::iterator seb_iterator; seb_iterator seb_begin() const { return SubExprBindings.begin(); } seb_iterator seb_end() const { return SubExprBindings.end(); } typedef BindingsTy::iterator beb_iterator; beb_iterator beb_begin() const { return BlkExprBindings.begin(); } beb_iterator beb_end() const { return BlkExprBindings.end(); } SVal LookupSubExpr(Stmt* E) const { const SVal* X = SubExprBindings.lookup(cast<Expr>(E)); return X ? *X : UnknownVal(); } SVal LookupBlkExpr(Stmt* E) const { const SVal* X = BlkExprBindings.lookup(E); return X ? *X : UnknownVal(); } SVal LookupExpr(Stmt* E) const { const SVal* X = SubExprBindings.lookup(E); if (X) return *X; X = BlkExprBindings.lookup(E); return X ? *X : UnknownVal(); } SVal GetSVal(Stmt* Ex, BasicValueFactory& BasicVals) const; SVal GetBlkExprSVal(Stmt* Ex, BasicValueFactory& BasicVals) const; /// Profile - Profile the contents of an Environment object for use /// in a FoldingSet. static void Profile(llvm::FoldingSetNodeID& ID, const Environment* E) { E->SubExprBindings.Profile(ID); E->BlkExprBindings.Profile(ID); } /// Profile - Used to profile the contents of this object for inclusion /// in a FoldingSet. void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, this); } bool operator==(const Environment& RHS) const { return SubExprBindings == RHS.SubExprBindings && BlkExprBindings == RHS.BlkExprBindings; } }; class EnvironmentManager { private: typedef Environment::BindingsTy::Factory FactoryTy; FactoryTy F; public: EnvironmentManager(llvm::BumpPtrAllocator& Allocator) : F(Allocator) {} ~EnvironmentManager() {} /// RemoveBlkExpr - Return a new environment object with the same bindings as /// the provided environment except with any bindings for the provided Stmt* /// removed. This method only removes bindings for block-level expressions. /// Using this method on a non-block level expression will return the /// same environment object. Environment RemoveBlkExpr(const Environment& Env, Stmt* E) { return Environment(Env.SubExprBindings, F.Remove(Env.BlkExprBindings, E)); } Environment RemoveSubExpr(const Environment& Env, Stmt* E) { return Environment(F.Remove(Env.SubExprBindings, E), Env.BlkExprBindings); } Environment AddBlkExpr(const Environment& Env, Stmt* E, SVal V) { return Environment(Env.SubExprBindings, F.Add(Env.BlkExprBindings, E, V)); } Environment AddSubExpr(const Environment& Env, Stmt* E, SVal V) { return Environment(F.Add(Env.SubExprBindings, E, V), Env.BlkExprBindings); } /// RemoveSubExprBindings - Return a new environment object with /// the same bindings as the provided environment except with all the /// subexpression bindings removed. Environment RemoveSubExprBindings(const Environment& Env) { return Environment(F.GetEmptyMap(), Env.BlkExprBindings); } Environment getInitialEnvironment() { return Environment(F.GetEmptyMap(), F.GetEmptyMap()); } Environment BindExpr(const Environment& Env, Stmt* E, SVal V, bool isBlkExpr, bool Invalidate); Environment RemoveDeadBindings(Environment Env, Stmt* Loc, SymbolReaper& SymReaper, GRStateManager& StateMgr, const GRState *state, llvm::SmallVectorImpl<const MemRegion*>& DRoots); }; } // end clang namespace #endif <file_sep>/test/Preprocessor/macro_paste_simple.c // RUN: clang-cc %s -E | grep "barbaz123" #define FOO bar ## baz ## 123 FOO <file_sep>/test/Preprocessor/poison_expansion.c // RUN: clang-cc %s -E 2>&1 | not grep error #define strrchr rindex #pragma GCC poison rindex // Can poison multiple times. #pragma GCC poison rindex strrchr(some_string, 'h'); <file_sep>/include/clang/Parse/Ownership.h //===--- Ownership.h - Parser Ownership Helpers -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains classes for managing ownership of Stmt and Expr nodes. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_OWNERSHIP_H #define LLVM_CLANG_PARSE_OWNERSHIP_H #include "llvm/ADT/PointerIntPair.h" //===----------------------------------------------------------------------===// // OpaquePtr //===----------------------------------------------------------------------===// namespace clang { class ActionBase; /// OpaquePtr - This is a very simple POD type that wraps a pointer that the /// Parser doesn't know about but that Sema or another client does. The UID /// template argument is used to make sure that "Decl" pointers are not /// compatible with "Type" pointers for example. template<int UID> class OpaquePtr { void *Ptr; public: OpaquePtr() : Ptr(0) {} template <typename T> T* getAs() const { return llvm::PointerLikeTypeTraits<T*>::getFromVoidPointer(Ptr); } template <typename T> T getAsVal() const { return llvm::PointerLikeTypeTraits<T>::getFromVoidPointer(Ptr); } void *get() const { return Ptr; } template<typename T> static OpaquePtr make(T P) { OpaquePtr R; R.set(P); return R; } template<typename T> void set(T P) { Ptr = llvm::PointerLikeTypeTraits<T>::getAsVoidPointer(P); } operator bool() const { return Ptr != 0; } }; } namespace llvm { template <int UID> class PointerLikeTypeTraits<clang::OpaquePtr<UID> > { public: static inline void *getAsVoidPointer(clang::OpaquePtr<UID> P) { // FIXME: Doesn't work? return P.getAs< void >(); return P.get(); } static inline clang::OpaquePtr<UID> getFromVoidPointer(void *P) { return clang::OpaquePtr<UID>::make(P); } enum { NumLowBitsAvailable = 3 }; }; } // -------------------------- About Move Emulation -------------------------- // // The smart pointer classes in this file attempt to emulate move semantics // as they appear in C++0x with rvalue references. Since C++03 doesn't have // rvalue references, some tricks are needed to get similar results. // Move semantics in C++0x have the following properties: // 1) "Moving" means transferring the value of an object to another object, // similar to copying, but without caring what happens to the old object. // In particular, this means that the new object can steal the old object's // resources instead of creating a copy. // 2) Since moving can modify the source object, it must either be explicitly // requested by the user, or the modifications must be unnoticeable. // 3) As such, C++0x moving is only allowed in three contexts: // * By explicitly using std::move() to request it. // * From a temporary object, since that object cannot be accessed // afterwards anyway, thus making the state unobservable. // * On function return, since the object is not observable afterwards. // // To sum up: moving from a named object should only be possible with an // explicit std::move(), or on function return. Moving from a temporary should // be implicitly done. Moving from a const object is forbidden. // // The emulation is not perfect, and has the following shortcomings: // * move() is not in namespace std. // * move() is required on function return. // * There are difficulties with implicit conversions. // * Microsoft's compiler must be given the /Za switch to successfully compile. // // -------------------------- Implementation -------------------------------- // // The move emulation relies on the peculiar reference binding semantics of // C++03: as a rule, a non-const reference may not bind to a temporary object, // except for the implicit object parameter in a member function call, which // can refer to a temporary even when not being const. // The moveable object has five important functions to facilitate moving: // * A private, unimplemented constructor taking a non-const reference to its // own class. This constructor serves a two-fold purpose. // - It prevents the creation of a copy constructor that takes a const // reference. Temporaries would be able to bind to the argument of such a // constructor, and that would be bad. // - Named objects will bind to the non-const reference, but since it's // private, this will fail to compile. This prevents implicit moving from // named objects. // There's also a copy assignment operator for the same purpose. // * An implicit, non-const conversion operator to a special mover type. This // type represents the rvalue reference of C++0x. Being a non-const member, // its implicit this parameter can bind to temporaries. // * A constructor that takes an object of this mover type. This constructor // performs the actual move operation. There is an equivalent assignment // operator. // There is also a free move() function that takes a non-const reference to // an object and returns a temporary. Internally, this function uses explicit // constructor calls to move the value from the referenced object to the return // value. // // There are now three possible scenarios of use. // * Copying from a const object. Constructor overload resolution will find the // non-const copy constructor, and the move constructor. The first is not // viable because the const object cannot be bound to the non-const reference. // The second fails because the conversion to the mover object is non-const. // Moving from a const object fails as intended. // * Copying from a named object. Constructor overload resolution will select // the non-const copy constructor, but fail as intended, because this // constructor is private. // * Copying from a temporary. Constructor overload resolution cannot select // the non-const copy constructor, because the temporary cannot be bound to // the non-const reference. It thus selects the move constructor. The // temporary can be bound to the implicit this parameter of the conversion // operator, because of the special binding rule. Construction succeeds. // Note that the Microsoft compiler, as an extension, allows binding // temporaries against non-const references. The compiler thus selects the // non-const copy constructor and fails, because the constructor is private. // Passing /Za (disable extensions) disables this behaviour. // The free move() function is used to move from a named object. // // Note that when passing an object of a different type (the classes below // have OwningResult and OwningPtr, which should be mixable), you get a problem. // Argument passing and function return use copy initialization rules. The // effect of this is that, when the source object is not already of the target // type, the compiler will first seek a way to convert the source object to the // target type, and only then attempt to copy the resulting object. This means // that when passing an OwningResult where an OwningPtr is expected, the // compiler will first seek a conversion from OwningResult to OwningPtr, then // copy the OwningPtr. The resulting conversion sequence is: // OwningResult object -> ResultMover -> OwningResult argument to // OwningPtr(OwningResult) -> OwningPtr -> PtrMover -> final OwningPtr // This conversion sequence is too complex to be allowed. Thus the special // move_* functions, which help the compiler out with some explicit // conversions. // Flip this switch to measure performance impact of the smart pointers. //#define DISABLE_SMART_POINTERS namespace llvm { template<> class PointerLikeTypeTraits<clang::ActionBase*> { typedef clang::ActionBase* PT; public: static inline void *getAsVoidPointer(PT P) { return P; } static inline PT getFromVoidPointer(void *P) { return static_cast<PT>(P); } enum { NumLowBitsAvailable = 2 }; }; } namespace clang { // Basic class DiagnosticBuilder; // Determines whether the low bit of the result pointer for the // given UID is always zero. If so, ActionResult will use that bit // for it's "invalid" flag. template<unsigned UID> struct IsResultPtrLowBitFree { static const bool value = false; }; /// ActionBase - A small part split from Action because of the horrible /// definition order dependencies between Action and the smart pointers. class ActionBase { public: /// Out-of-line virtual destructor to provide home for this class. virtual ~ActionBase(); // Types - Though these don't actually enforce strong typing, they document // what types are required to be identical for the actions. typedef OpaquePtr<0> DeclPtrTy; typedef OpaquePtr<1> DeclGroupPtrTy; typedef OpaquePtr<2> TemplateTy; typedef void AttrTy; typedef void BaseTy; typedef void MemInitTy; typedef void ExprTy; typedef void StmtTy; typedef void TemplateParamsTy; typedef void CXXScopeTy; typedef void TypeTy; // FIXME: Change TypeTy to use OpaquePtr<N>. /// ActionResult - This structure is used while parsing/acting on /// expressions, stmts, etc. It encapsulates both the object returned by /// the action, plus a sense of whether or not it is valid. /// When CompressInvalid is true, the "invalid" flag will be /// stored in the low bit of the Val pointer. template<unsigned UID, typename PtrTy = void*, bool CompressInvalid = IsResultPtrLowBitFree<UID>::value> class ActionResult { PtrTy Val; bool Invalid; public: ActionResult(bool Invalid = false) : Val(PtrTy()), Invalid(Invalid) {} template<typename ActualExprTy> ActionResult(ActualExprTy val) : Val(val), Invalid(false) {} ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {} PtrTy get() const { return Val; } void set(PtrTy V) { Val = V; } bool isInvalid() const { return Invalid; } const ActionResult &operator=(PtrTy RHS) { Val = RHS; Invalid = false; return *this; } }; // This ActionResult partial specialization places the "invalid" // flag into the low bit of the pointer. template<unsigned UID, typename PtrTy> class ActionResult<UID, PtrTy, true> { // A pointer whose low bit is 1 if this result is invalid, 0 // otherwise. uintptr_t PtrWithInvalid; typedef llvm::PointerLikeTypeTraits<PtrTy> PtrTraits; public: ActionResult(bool Invalid = false) : PtrWithInvalid(static_cast<uintptr_t>(Invalid)) { } template<typename ActualExprTy> ActionResult(ActualExprTy *val) { PtrTy V(val); void *VP = PtrTraits::getAsVoidPointer(V); PtrWithInvalid = reinterpret_cast<uintptr_t>(VP); assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"); } ActionResult(PtrTy V) { void *VP = PtrTraits::getAsVoidPointer(V); PtrWithInvalid = reinterpret_cast<uintptr_t>(VP); assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"); } ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) { } PtrTy get() const { void *VP = reinterpret_cast<void *>(PtrWithInvalid & ~0x01); return PtrTraits::getFromVoidPointer(VP); } void set(PtrTy V) { void *VP = PtrTraits::getAsVoidPointer(V); PtrWithInvalid = reinterpret_cast<uintptr_t>(VP); assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"); } bool isInvalid() const { return PtrWithInvalid & 0x01; } const ActionResult &operator=(PtrTy RHS) { void *VP = PtrTraits::getAsVoidPointer(RHS); PtrWithInvalid = reinterpret_cast<uintptr_t>(VP); assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"); return *this; } }; /// Deletion callbacks - Since the parser doesn't know the concrete types of /// the AST nodes being generated, it must do callbacks to delete objects /// when recovering from errors. These are in ActionBase because the smart /// pointers need access to them. virtual void DeleteExpr(ExprTy *E) {} virtual void DeleteStmt(StmtTy *S) {} virtual void DeleteTemplateParams(TemplateParamsTy *P) {} }; /// ASTDestroyer - The type of an AST node destruction function pointer. typedef void (ActionBase::*ASTDestroyer)(void *); /// For the transition phase: translate from an ASTDestroyer to its /// ActionResult UID. template <ASTDestroyer Destroyer> struct DestroyerToUID; template <> struct DestroyerToUID<&ActionBase::DeleteExpr> { static const unsigned UID = 0; }; template <> struct DestroyerToUID<&ActionBase::DeleteStmt> { static const unsigned UID = 1; }; /// ASTOwningResult - A moveable smart pointer for AST nodes that also /// has an extra flag to indicate an additional success status. template <ASTDestroyer Destroyer> class ASTOwningResult; /// ASTMultiPtr - A moveable smart pointer to multiple AST nodes. Only owns /// the individual pointers, not the array holding them. template <ASTDestroyer Destroyer> class ASTMultiPtr; #if !defined(DISABLE_SMART_POINTERS) namespace moving { /// Move emulation helper for ASTOwningResult. NEVER EVER use this class /// directly if you don't know what you're doing. template <ASTDestroyer Destroyer> class ASTResultMover { ASTOwningResult<Destroyer> &Moved; public: ASTResultMover(ASTOwningResult<Destroyer> &moved) : Moved(moved) {} ASTOwningResult<Destroyer> * operator ->() { return &Moved; } }; /// Move emulation helper for ASTMultiPtr. NEVER EVER use this class /// directly if you don't know what you're doing. template <ASTDestroyer Destroyer> class ASTMultiMover { ASTMultiPtr<Destroyer> &Moved; public: ASTMultiMover(ASTMultiPtr<Destroyer> &moved) : Moved(moved) {} ASTMultiPtr<Destroyer> * operator ->() { return &Moved; } /// Reset the moved object's internal structures. void release(); }; } #else /// Kept only as a type-safe wrapper for a void pointer, when smart pointers /// are disabled. When they are enabled, ASTOwningResult takes over. template <ASTDestroyer Destroyer> class ASTOwningPtr { void *Node; public: explicit ASTOwningPtr(ActionBase &) : Node(0) {} ASTOwningPtr(ActionBase &, void *node) : Node(node) {} // Normal copying operators are defined implicitly. ASTOwningPtr(const ASTOwningResult<Destroyer> &o); ASTOwningPtr & operator =(void *raw) { Node = raw; return *this; } /// Access to the raw pointer. void * get() const { return Node; } /// Release the raw pointer. void * take() { return Node; } /// Alias for interface familiarity with unique_ptr. void * release() { return take(); } }; #endif // Important: There are two different implementations of // ASTOwningResult below, depending on whether // DISABLE_SMART_POINTERS is defined. If you make changes that // affect the interface, be sure to compile and test both ways! #if !defined(DISABLE_SMART_POINTERS) template <ASTDestroyer Destroyer> class ASTOwningResult { llvm::PointerIntPair<ActionBase*, 1, bool> ActionInv; void *Ptr; friend class moving::ASTResultMover<Destroyer>; ASTOwningResult(ASTOwningResult&); // DO NOT IMPLEMENT ASTOwningResult& operator =(ASTOwningResult&); // DO NOT IMPLEMENT void destroy() { if (Ptr) { assert(ActionInv.getPointer() && "Smart pointer has node but no action."); (ActionInv.getPointer()->*Destroyer)(Ptr); Ptr = 0; } } public: typedef ActionBase::ActionResult<DestroyerToUID<Destroyer>::UID> DumbResult; explicit ASTOwningResult(ActionBase &actions, bool invalid = false) : ActionInv(&actions, invalid), Ptr(0) {} ASTOwningResult(ActionBase &actions, void *node) : ActionInv(&actions, false), Ptr(node) {} ASTOwningResult(ActionBase &actions, const DumbResult &res) : ActionInv(&actions, res.isInvalid()), Ptr(res.get()) {} /// Move from another owning result ASTOwningResult(moving::ASTResultMover<Destroyer> mover) : ActionInv(mover->ActionInv), Ptr(mover->Ptr) { mover->Ptr = 0; } ~ASTOwningResult() { destroy(); } /// Move assignment from another owning result ASTOwningResult &operator=(moving::ASTResultMover<Destroyer> mover) { destroy(); ActionInv = mover->ActionInv; Ptr = mover->Ptr; mover->Ptr = 0; return *this; } /// Assignment from a raw pointer. Takes ownership - beware! ASTOwningResult &operator=(void *raw) { destroy(); Ptr = raw; ActionInv.setInt(false); return *this; } /// Assignment from an ActionResult. Takes ownership - beware! ASTOwningResult &operator=(const DumbResult &res) { destroy(); Ptr = res.get(); ActionInv.setInt(res.isInvalid()); return *this; } /// Access to the raw pointer. void *get() const { return Ptr; } bool isInvalid() const { return ActionInv.getInt(); } /// Does this point to a usable AST node? To be usable, the node must be /// valid and non-null. bool isUsable() const { return !isInvalid() && get(); } /// Take outside ownership of the raw pointer. void *take() { if (isInvalid()) return 0; void *tmp = Ptr; Ptr = 0; return tmp; } /// Take outside ownership of the raw pointer and cast it down. template<typename T> T *takeAs() { return static_cast<T*>(take()); } /// Alias for interface familiarity with unique_ptr. void *release() { return take(); } /// Pass ownership to a classical ActionResult. DumbResult result() { if (isInvalid()) return true; return take(); } /// Move hook operator moving::ASTResultMover<Destroyer>() { return moving::ASTResultMover<Destroyer>(*this); } }; #else template <ASTDestroyer Destroyer> class ASTOwningResult { public: typedef ActionBase::ActionResult<DestroyerToUID<Destroyer>::UID> DumbResult; private: DumbResult Result; public: explicit ASTOwningResult(ActionBase &actions, bool invalid = false) : Result(invalid) { } ASTOwningResult(ActionBase &actions, void *node) : Result(node) { } ASTOwningResult(ActionBase &actions, const DumbResult &res) : Result(res) { } // Normal copying semantics are defined implicitly. ASTOwningResult(const ASTOwningPtr<Destroyer> &o) : Result(o.get()) { } /// Assignment from a raw pointer. Takes ownership - beware! ASTOwningResult & operator =(void *raw) { Result = raw; return *this; } /// Assignment from an ActionResult. Takes ownership - beware! ASTOwningResult & operator =(const DumbResult &res) { Result = res; return *this; } /// Access to the raw pointer. void * get() const { return Result.get(); } bool isInvalid() const { return Result.isInvalid(); } /// Does this point to a usable AST node? To be usable, the node must be /// valid and non-null. bool isUsable() const { return !Result.isInvalid() && get(); } /// Take outside ownership of the raw pointer. void * take() { return Result.get(); } /// Take outside ownership of the raw pointer and cast it down. template<typename T> T *takeAs() { return static_cast<T*>(take()); } /// Alias for interface familiarity with unique_ptr. void * release() { return take(); } /// Pass ownership to a classical ActionResult. DumbResult result() { return Result; } }; #endif template <ASTDestroyer Destroyer> class ASTMultiPtr { #if !defined(DISABLE_SMART_POINTERS) ActionBase &Actions; #endif void **Nodes; unsigned Count; #if !defined(DISABLE_SMART_POINTERS) friend class moving::ASTMultiMover<Destroyer>; ASTMultiPtr(ASTMultiPtr&); // DO NOT IMPLEMENT // Reference member prevents copy assignment. void destroy() { assert((Count == 0 || Nodes) && "No nodes when count is not zero."); for (unsigned i = 0; i < Count; ++i) { if (Nodes[i]) (Actions.*Destroyer)(Nodes[i]); } } #endif public: #if !defined(DISABLE_SMART_POINTERS) explicit ASTMultiPtr(ActionBase &actions) : Actions(actions), Nodes(0), Count(0) {} ASTMultiPtr(ActionBase &actions, void **nodes, unsigned count) : Actions(actions), Nodes(nodes), Count(count) {} /// Move constructor ASTMultiPtr(moving::ASTMultiMover<Destroyer> mover) : Actions(mover->Actions), Nodes(mover->Nodes), Count(mover->Count) { mover.release(); } #else // Normal copying implicitly defined explicit ASTMultiPtr(ActionBase &) : Nodes(0), Count(0) {} ASTMultiPtr(ActionBase &, void **nodes, unsigned count) : Nodes(nodes), Count(count) {} // Fake mover in Parse/AstGuard.h needs this: ASTMultiPtr(void **nodes, unsigned count) : Nodes(nodes), Count(count) {} #endif #if !defined(DISABLE_SMART_POINTERS) /// Move assignment ASTMultiPtr & operator =(moving::ASTMultiMover<Destroyer> mover) { destroy(); Nodes = mover->Nodes; Count = mover->Count; mover.release(); return *this; } #endif /// Access to the raw pointers. void ** get() const { return Nodes; } /// Access to the count. unsigned size() const { return Count; } void ** release() { #if !defined(DISABLE_SMART_POINTERS) void **tmp = Nodes; Nodes = 0; Count = 0; return tmp; #else return Nodes; #endif } #if !defined(DISABLE_SMART_POINTERS) /// Move hook operator moving::ASTMultiMover<Destroyer>() { return moving::ASTMultiMover<Destroyer>(*this); } #endif }; class ASTTemplateArgsPtr { #if !defined(DISABLE_SMART_POINTERS) ActionBase &Actions; #endif void **Args; bool *ArgIsType; mutable unsigned Count; #if !defined(DISABLE_SMART_POINTERS) void destroy() { if (!Count) return; for (unsigned i = 0; i != Count; ++i) if (Args[i] && !ArgIsType[i]) Actions.DeleteExpr((ActionBase::ExprTy *)Args[i]); Count = 0; } #endif public: ASTTemplateArgsPtr(ActionBase &actions, void **args, bool *argIsType, unsigned count) : #if !defined(DISABLE_SMART_POINTERS) Actions(actions), #endif Args(args), ArgIsType(argIsType), Count(count) { } // FIXME: Lame, not-fully-type-safe emulation of 'move semantics'. ASTTemplateArgsPtr(ASTTemplateArgsPtr &Other) : #if !defined(DISABLE_SMART_POINTERS) Actions(Other.Actions), #endif Args(Other.Args), ArgIsType(Other.ArgIsType), Count(Other.Count) { #if !defined(DISABLE_SMART_POINTERS) Other.Count = 0; #endif } // FIXME: Lame, not-fully-type-safe emulation of 'move semantics'. ASTTemplateArgsPtr& operator=(ASTTemplateArgsPtr &Other) { #if !defined(DISABLE_SMART_POINTERS) Actions = Other.Actions; #endif Args = Other.Args; ArgIsType = Other.ArgIsType; Count = Other.Count; #if !defined(DISABLE_SMART_POINTERS) Other.Count = 0; #endif return *this; } #if !defined(DISABLE_SMART_POINTERS) ~ASTTemplateArgsPtr() { destroy(); } #endif void **getArgs() const { return Args; } bool *getArgIsType() const {return ArgIsType; } unsigned size() const { return Count; } void reset(void **args, bool *argIsType, unsigned count) { destroy(); Args = args; ArgIsType = argIsType; Count = count; } void *operator[](unsigned Arg) const { return Args[Arg]; } void **release() const { #if !defined(DISABLE_SMART_POINTERS) Count = 0; #endif return Args; } }; #if !defined(DISABLE_SMART_POINTERS) // Out-of-line implementations due to definition dependencies template <ASTDestroyer Destroyer> inline void moving::ASTMultiMover<Destroyer>::release() { Moved.Nodes = 0; Moved.Count = 0; } // Move overloads. template <ASTDestroyer Destroyer> inline ASTOwningResult<Destroyer> move(ASTOwningResult<Destroyer> &ptr) { return ASTOwningResult<Destroyer>(moving::ASTResultMover<Destroyer>(ptr)); } template <ASTDestroyer Destroyer> inline ASTMultiPtr<Destroyer> move(ASTMultiPtr<Destroyer> &ptr) { return ASTMultiPtr<Destroyer>(moving::ASTMultiMover<Destroyer>(ptr)); } #else template <ASTDestroyer Destroyer> inline ASTOwningPtr<Destroyer>::ASTOwningPtr(const ASTOwningResult<Destroyer> &o) : Node(o.get()) {} // These versions are hopefully no-ops. template <ASTDestroyer Destroyer> inline ASTOwningResult<Destroyer>& move(ASTOwningResult<Destroyer> &ptr) { return ptr; } template <ASTDestroyer Destroyer> inline ASTOwningPtr<Destroyer>& move(ASTOwningPtr<Destroyer> &ptr) { return ptr; } template <ASTDestroyer Destroyer> inline ASTMultiPtr<Destroyer>& move(ASTMultiPtr<Destroyer> &ptr) { return ptr; } #endif } #endif <file_sep>/test/CodeGen/globalinit.c // RUN: clang-cc -emit-llvm %s -o %t int A[10] = { 1,2,3,4,5 }; extern int x[]; void foo() { x[0] = 1; } int x[10]; void bar() { x[0] = 1; } extern int y[]; void *g = y; int latin_ptr2len (char *p); int (*mb_ptr2len) (char *p) = latin_ptr2len; char string[8] = "string"; // extend init char string2[4] = "string"; // truncate init char *test(int c) { static char buf[10]; static char *bufptr = buf; return c ? buf : bufptr; } _Bool booltest = 0; void booltest2() { static _Bool booltest3 = 4; } // Scalars in braces. static int a = { 1 }; // References to enums. enum { EnumA, EnumB }; int c[] = { EnumA, EnumB }; // Binary operators int d[] = { EnumA | EnumB }; // PR1968 static int array[]; static int array[4]; <file_sep>/test/CodeGen/union.c // RUN: clang-cc %s -emit-llvm -o - union u_tag { int a; float b; } u; void f() { u.b = 11; } float get_b(union u_tag *my_u) { return my_u->b; } int f2( float __x ) { union{ float __f; unsigned int __u; }__u; return (int)(__u.__u >> 31); } typedef union { int i; int *j; } value; int f3(value v) { return *v.j; } enum E9 { one, two }; union S65 { enum E9 a; } ; union S65 s65; void fS65() { enum E9 e = s65.a; } typedef union{ unsigned char x[65536]; } q; int qfunc() {q buf; unsigned char* x = buf.x;} union RR {_Bool a : 1;} RRU; int RRF(void) {return RRU.a;} <file_sep>/tools/ccc/test/ccc/universal-hello.c // RUN: xcc -ccc-no-clang -arch ppc -arch i386 -arch x86_64 %s -o %t && // RUN: %t | grep "Hello, World" && // RUN: xcc -ccc-no-clang -pipe -arch ppc -arch i386 -arch x86_64 %s -o %t && // RUN: %t | grep "Hello, World" && // Check that multiple archs are handled properly. // RUN: xcc -ccc-print-phases -### -arch ppc -arch ppc %s | grep 'linker,' | count 1 && // Check that -ccc-clang-archs is honored. // RUN: xcc -ccc-clang-archs i386 -### -arch ppc -arch i386 %s 2>&1 | grep 'clang-cc"' | count 1 int main() { printf("Hello, World!\n"); return 0; } <file_sep>/lib/Driver/ToolChains.cpp //===--- ToolChains.cpp - ToolChain Implementations ---------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ToolChains.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/HostInfo.h" #include "clang/Driver/Option.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include <cstdlib> // ::getenv using namespace clang::driver; using namespace clang::driver::toolchains; /// Darwin_X86 - Darwin tool chain for i386 and x86_64. Darwin_X86::Darwin_X86(const HostInfo &Host, const char *Arch, const char *Platform, const char *OS, const unsigned (&_DarwinVersion)[3], const unsigned (&_GCCVersion)[3]) : ToolChain(Host, Arch, Platform, OS) { DarwinVersion[0] = _DarwinVersion[0]; DarwinVersion[1] = _DarwinVersion[1]; DarwinVersion[2] = _DarwinVersion[2]; GCCVersion[0] = _GCCVersion[0]; GCCVersion[1] = _GCCVersion[1]; GCCVersion[2] = _GCCVersion[2]; llvm::raw_string_ostream(MacosxVersionMin) << "10." << DarwinVersion[0] - 4 << '.' << DarwinVersion[1]; ToolChainDir = "i686-apple-darwin"; ToolChainDir += llvm::utostr(DarwinVersion[0]); ToolChainDir += "/"; ToolChainDir += llvm::utostr(GCCVersion[0]); ToolChainDir += '.'; ToolChainDir += llvm::utostr(GCCVersion[1]); ToolChainDir += '.'; ToolChainDir += llvm::utostr(GCCVersion[2]); std::string Path; if (getArchName() == "x86_64") { Path = getHost().getDriver().Dir; Path += "/../lib/gcc/"; Path += getToolChainDir(); Path += "/x86_64"; getFilePaths().push_back(Path); Path = "/usr/lib/gcc/"; Path += getToolChainDir(); Path += "/x86_64"; getFilePaths().push_back(Path); } Path = getHost().getDriver().Dir; Path += "/../lib/gcc/"; Path += getToolChainDir(); getFilePaths().push_back(Path); Path = "/usr/lib/gcc/"; Path += getToolChainDir(); getFilePaths().push_back(Path); Path = getHost().getDriver().Dir; Path += "/../libexec/gcc/"; Path += getToolChainDir(); getProgramPaths().push_back(Path); Path = "/usr/libexec/gcc/"; Path += getToolChainDir(); getProgramPaths().push_back(Path); Path = getHost().getDriver().Dir; Path += "/../libexec"; getProgramPaths().push_back(Path); getProgramPaths().push_back(getHost().getDriver().Dir); } Darwin_X86::~Darwin_X86() { // Free tool implementations. for (llvm::DenseMap<unsigned, Tool*>::iterator it = Tools.begin(), ie = Tools.end(); it != ie; ++it) delete it->second; } Tool &Darwin_X86::SelectTool(const Compilation &C, const JobAction &JA) const { Action::ActionClass Key; if (getHost().getDriver().ShouldUseClangCompiler(C, JA, getArchName())) Key = Action::AnalyzeJobClass; else Key = JA.getKind(); Tool *&T = Tools[Key]; if (!T) { switch (Key) { case Action::InputClass: case Action::BindArchClass: assert(0 && "Invalid tool kind."); case Action::PreprocessJobClass: T = new tools::darwin::Preprocess(*this); break; case Action::AnalyzeJobClass: T = new tools::Clang(*this); break; case Action::PrecompileJobClass: case Action::CompileJobClass: T = new tools::darwin::Compile(*this); break; case Action::AssembleJobClass: T = new tools::darwin::Assemble(*this); break; case Action::LinkJobClass: T = new tools::darwin::Link(*this, MacosxVersionMin.c_str()); break; case Action::LipoJobClass: T = new tools::darwin::Lipo(*this); break; } } return *T; } DerivedArgList *Darwin_X86::TranslateArgs(InputArgList &Args) const { DerivedArgList *DAL = new DerivedArgList(Args, false); const OptTable &Opts = getHost().getDriver().getOpts(); // FIXME: We really want to get out of the tool chain level argument // translation business, as it makes the driver functionality much // more opaque. For now, we follow gcc closely solely for the // purpose of easily achieving feature parity & testability. Once we // have something that works, we should reevaluate each translation // and try to push it down into tool specific logic. Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ, false); Arg *iPhoneVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ, false); if (OSXVersion && iPhoneVersion) { getHost().getDriver().Diag(clang::diag::err_drv_argument_not_allowed_with) << OSXVersion->getAsString(Args) << iPhoneVersion->getAsString(Args); } else if (!OSXVersion && !iPhoneVersion) { // Chose the default version based on the arch. // // FIXME: This will need to be fixed when we merge in arm support. // Look for MACOSX_DEPLOYMENT_TARGET, otherwise use the version // from the host. const char *Version = ::getenv("MACOSX_DEPLOYMENT_TARGET"); if (!Version) Version = MacosxVersionMin.c_str(); const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ); DAL->append(DAL->MakeJoinedArg(0, O, Version)); } for (ArgList::iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { Arg *A = *it; if (A->getOption().matches(options::OPT_Xarch__)) { // FIXME: Canonicalize name. if (getArchName() != A->getValue(Args, 0)) continue; // FIXME: The arg is leaked here, and we should have a nicer // interface for this. unsigned Prev, Index = Prev = A->getIndex() + 1; Arg *XarchArg = Opts.ParseOneArg(Args, Index); // If the argument parsing failed or more than one argument was // consumed, the -Xarch_ argument's parameter tried to consume // extra arguments. Emit an error and ignore. // // We also want to disallow any options which would alter the // driver behavior; that isn't going to work in our model. We // use isDriverOption() as an approximation, although things // like -O4 are going to slip through. if (!XarchArg || Index > Prev + 1 || XarchArg->getOption().isDriverOption()) { getHost().getDriver().Diag(clang::diag::err_drv_invalid_Xarch_argument) << A->getAsString(Args); continue; } XarchArg->setBaseArg(A); A = XarchArg; } // Sob. These is strictly gcc compatible for the time being. Apple // gcc translates options twice, which means that self-expanding // options add duplicates. options::ID id = A->getOption().getId(); switch (id) { default: DAL->append(A); break; case options::OPT_mkernel: case options::OPT_fapple_kext: DAL->append(A); DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_static))); DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_static))); break; case options::OPT_dependency_file: DAL->append(DAL->MakeSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(Args))); break; case options::OPT_gfull: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_g_Flag))); DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols))); break; case options::OPT_gused: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_g_Flag))); DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols))); break; case options::OPT_fterminated_vtables: case options::OPT_findirect_virtual_calls: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_fapple_kext))); DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_static))); break; case options::OPT_shared: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_dynamiclib))); break; case options::OPT_fconstant_cfstrings: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings))); break; case options::OPT_fno_constant_cfstrings: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings))); break; case options::OPT_Wnonportable_cfstrings: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_mwarn_nonportable_cfstrings))); break; case options::OPT_Wno_nonportable_cfstrings: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings))); break; case options::OPT_fpascal_strings: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_mpascal_strings))); break; case options::OPT_fno_pascal_strings: DAL->append(DAL->MakeFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings))); break; } } // FIXME: Actually, gcc always adds this, but it is filtered for // duplicates somewhere. This also changes the order of things, so // look it up. if (getArchName() == "x86_64") if (!Args.hasArg(options::OPT_m64, false)) DAL->append(DAL->MakeFlagArg(0, Opts.getOption(options::OPT_m64))); if (!Args.hasArg(options::OPT_mtune_EQ, false)) DAL->append(DAL->MakeJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2")); return DAL; } bool Darwin_X86::IsMathErrnoDefault() const { return false; } bool Darwin_X86::IsUnwindTablesDefault() const { // FIXME: Gross; we should probably have some separate target // definition, possibly even reusing the one in clang. return getArchName() == "x86_64"; } const char *Darwin_X86::GetDefaultRelocationModel() const { return "pic"; } const char *Darwin_X86::GetForcedPicModel() const { if (getArchName() == "x86_64") return "pic"; return 0; } /// Generic_GCC - A tool chain using the 'gcc' command to perform /// all subcommands; this relies on gcc translating the majority of /// command line options. Generic_GCC::Generic_GCC(const HostInfo &Host, const char *Arch, const char *Platform, const char *OS) : ToolChain(Host, Arch, Platform, OS) { std::string Path(getHost().getDriver().Dir); Path += "/../libexec"; getProgramPaths().push_back(Path); getProgramPaths().push_back(getHost().getDriver().Dir); } Generic_GCC::~Generic_GCC() { // Free tool implementations. for (llvm::DenseMap<unsigned, Tool*>::iterator it = Tools.begin(), ie = Tools.end(); it != ie; ++it) delete it->second; } Tool &Generic_GCC::SelectTool(const Compilation &C, const JobAction &JA) const { Action::ActionClass Key; if (getHost().getDriver().ShouldUseClangCompiler(C, JA, getArchName())) Key = Action::AnalyzeJobClass; else Key = JA.getKind(); Tool *&T = Tools[Key]; if (!T) { switch (Key) { case Action::InputClass: case Action::BindArchClass: assert(0 && "Invalid tool kind."); case Action::PreprocessJobClass: T = new tools::gcc::Preprocess(*this); break; case Action::PrecompileJobClass: T = new tools::gcc::Precompile(*this); break; case Action::AnalyzeJobClass: T = new tools::Clang(*this); break; case Action::CompileJobClass: T = new tools::gcc::Compile(*this); break; case Action::AssembleJobClass: T = new tools::gcc::Assemble(*this); break; case Action::LinkJobClass: T = new tools::gcc::Link(*this); break; // This is a bit ungeneric, but the only platform using a driver // driver is Darwin. case Action::LipoJobClass: T = new tools::darwin::Lipo(*this); break; } } return *T; } bool Generic_GCC::IsMathErrnoDefault() const { return true; } bool Generic_GCC::IsUnwindTablesDefault() const { // FIXME: Gross; we should probably have some separate target // definition, possibly even reusing the one in clang. return getArchName() == "x86_64"; } const char *Generic_GCC::GetDefaultRelocationModel() const { return "static"; } const char *Generic_GCC::GetForcedPicModel() const { return 0; } DerivedArgList *Generic_GCC::TranslateArgs(InputArgList &Args) const { return new DerivedArgList(Args, true); } /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly. FreeBSD::FreeBSD(const HostInfo &Host, const char *Arch, const char *Platform, const char *OS, bool Lib32) : Generic_GCC(Host, Arch, Platform, OS) { if (Lib32) { getFilePaths().push_back(getHost().getDriver().Dir + "/../lib32"); getFilePaths().push_back("/usr/lib32"); } else { getFilePaths().push_back(getHost().getDriver().Dir + "/../lib"); getFilePaths().push_back("/usr/lib"); } } Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA) const { Action::ActionClass Key; if (getHost().getDriver().ShouldUseClangCompiler(C, JA, getArchName())) Key = Action::AnalyzeJobClass; else Key = JA.getKind(); Tool *&T = Tools[Key]; if (!T) { switch (Key) { case Action::AssembleJobClass: T = new tools::freebsd::Assemble(*this); break; case Action::LinkJobClass: T = new tools::freebsd::Link(*this); break; default: T = &Generic_GCC::SelectTool(C, JA); } } return *T; } <file_sep>/test/Sema/block-return.c // RUN: clang-cc -fsyntax-only %s -verify -fblocks typedef void (^CL)(void); CL foo() { short y; short (^add1)(void) = ^{ return y+1; }; // expected-warning {{incompatible block pointer types initializing 'int (^)(void)', expected 'short (^)(void)'}} CL X = ^{ if (2) return; return 1; // expected-error {{void block should not return a value}} }; int (^Y) (void) = ^{ if (3) return 1; else return; // expected-error {{non-void block should return a value}} }; char *(^Z)(void) = ^{ if (3) return ""; else return (char*)0; }; double (^A)(void) = ^ { // expected-warning {{incompatible block pointer types initializing 'float (^)(void)', expected 'double (^)(void)'}} if (1) return (float)1.0; else if (2) return (double)2.0; return 1; }; char *(^B)(void) = ^{ if (3) return ""; else return 2; // expected-warning {{incompatible integer to pointer conversion returning 'int', expected 'char *'}} }; return ^{ return 1; }; // expected-warning {{incompatible block pointer types returning 'int (^)(void)', expected 'CL'}} expected-error {{returning block that lives on the local stack}} } typedef int (^CL2)(void); CL2 foo2() { return ^{ return 1; }; // expected-error {{returning block that lives on the local stack}} } typedef unsigned int * uintptr_t; typedef char Boolean; typedef int CFBasicHash; #define INVOKE_CALLBACK2(P, A, B) (P)(A, B) typedef struct { Boolean (^isEqual)(const CFBasicHash *, uintptr_t stack_value_or_key1, uintptr_t stack_value_or_key2, Boolean is_key); } CFBasicHashCallbacks; int foo3() { CFBasicHashCallbacks cb; Boolean (*value_equal)(uintptr_t, uintptr_t) = 0; cb.isEqual = ^(const CFBasicHash *table, uintptr_t stack_value_or_key1, uintptr_t stack_value_or_key2, Boolean is_key) { return (Boolean)(uintptr_t)INVOKE_CALLBACK2(value_equal, (uintptr_t)stack_value_or_key1, (uintptr_t)stack_value_or_key2); }; } static int funk(char *s) { if (^{} == ((void*)0)) return 1; else return 0; } void foo4() { int (^xx)(const char *s) = ^(char *s) { return 1; }; // expected-warning {{incompatible block pointer types initializing 'int (^)(char *)', expected 'int (^)(char const *)'}} int (*yy)(const char *s) = funk; // expected-warning {{incompatible pointer types initializing 'int (char *)', expected 'int (*)(char const *)'}} int (^nested)(char *s) = ^(char *str) { void (^nest)(void) = ^(void) { printf("%s\n", str); }; next(); return 1; }; // expected-warning{{implicitly declaring C library function 'printf' with type 'int (char const *, ...)'}} \ // expected-note{{please include the header <stdio.h> or explicitly provide a declaration for 'printf'}} } <file_sep>/tools/scan-view/scan-view #!/usr/bin/env python """The clang static analyzer results viewer. """ import sys import posixpath import thread import time import urllib import webbrowser # How long to wait for server to start. kSleepTimeout = .05 kMaxSleeps = 100 # Default server parameters kDefaultHost = '127.0.0.1' kDefaultPort = 8181 kMaxPortsToTry = 100 ### def url_is_up(url): try: o = urllib.urlopen(url) except IOError: return False o.close() return True def start_browser(port, options): import urllib, webbrowser url = 'http://%s:%d'%(options.host, port) # Wait for server to start... if options.debug: sys.stderr.write('%s: Waiting for server.' % sys.argv[0]) sys.stderr.flush() for i in range(kMaxSleeps): if url_is_up(url): break if options.debug: sys.stderr.write('.') sys.stderr.flush() time.sleep(kSleepTimeout) else: print >>sys.stderr,'WARNING: Unable to detect that server started.' if options.debug: print >>sys.stderr,'%s: Starting webbrowser...' % sys.argv[0] webbrowser.open(url) def run(port, options, root): import ScanView try: print 'Starting scan-view at: http://%s:%d'%(options.host, port) print ' Use Ctrl-C to exit.' httpd = ScanView.create_server((options.host, port), options, root) httpd.serve_forever() except KeyboardInterrupt: pass def port_is_open(port): import SocketServer try: t = SocketServer.TCPServer((kDefaultHost,port),None) except: return False t.server_close() return True def main(): from optparse import OptionParser parser = OptionParser('usage: %prog [options] <results directory>') parser.set_description(__doc__) parser.add_option( '--host', dest="host", default=kDefaultHost, type="string", help="Host interface to listen on. (default=%s)" % kDefaultHost) parser.add_option( '--port', dest="port", default=None, type="int", help="Port to listen on. (default=%s)" % kDefaultPort) parser.add_option("--debug", dest="debug", default=0, action="count", help="Print additional debugging information.") parser.add_option("--auto-reload", dest="autoReload", default=False, action="store_true", help="Automatically update module for each request.") parser.add_option("--no-browser", dest="startBrowser", default=True, action="store_false", help="Don't open a webbrowser on startup.") parser.add_option("--allow-all-hosts", dest="onlyServeLocal", default=True, action="store_false", help='Allow connections from any host (access restricted to "127.0.0.1" by default)') (options, args) = parser.parse_args() if len(args) != 1: parser.error('No results directory specified.') root, = args # Make sure this directory is in a reasonable state to view. if not posixpath.exists(posixpath.join(root,'index.html')): parser.error('Invalid directory, analysis results not found!') # Find an open port. We aren't particularly worried about race # conditions here. Note that if the user specified a port we only # use that one. if options.port is not None: port = options.port else: for i in range(kMaxPortsToTry): if port_is_open(kDefaultPort + i): port = kDefaultPort + i break else: parser.error('Unable to find usable port in [%d,%d)'%(kDefaultPort, kDefaultPort+kMaxPortsToTry)) # Kick off thread to wait for server and start web browser, if # requested. if options.startBrowser: t = thread.start_new_thread(start_browser, (port,options)) run(port, options, root) if __name__ == '__main__': main() <file_sep>/test/SemaCXX/access.cpp // RUN: clang-cc -fsyntax-only -verify %s class C { struct S; // expected-note {{previously declared 'private' here}} public: struct S {}; // expected-error {{'S' redeclared with 'public' access}} }; struct S { class C; // expected-note {{previously declared 'public' here}} private: class C { }; // expected-error {{'C' redeclared with 'private' access}} }; class T { protected: template<typename T> struct A; // expected-note {{previously declared 'protected' here}} private: template<typename T> struct A {}; // expected-error {{'A' redeclared with 'private' access}} }; <file_sep>/test/CodeGenCXX/member-functions.cpp // RUN: clang-cc -emit-llvm %s -o %t && struct C { void f(); void g(int, ...); }; // RUN: grep "define void @_ZN1C1fEv" %t | count 1 && void C::f() { } void f() { C c; // RUN: grep "call void @_ZN1C1fEv" %t | count 1 && c.f(); // RUN: grep "call void (.struct.C\*, i32, ...)\* @_ZN1C1gEiz" %t | count 1 c.g(1, 2, 3); } <file_sep>/lib/AST/DeclCXX.cpp //===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the C++ related Decl classes. // //===----------------------------------------------------------------------===// #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Expr.h" #include "clang/Basic/IdentifierTable.h" #include "llvm/ADT/STLExtras.h" using namespace clang; //===----------------------------------------------------------------------===// // Decl Allocation/Deallocation Method Implementations //===----------------------------------------------------------------------===// CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id) : RecordDecl(K, TK, DC, L, Id), UserDeclaredConstructor(false), UserDeclaredCopyConstructor(false), UserDeclaredCopyAssignment(false), UserDeclaredDestructor(false), Aggregate(true), PlainOldData(true), Polymorphic(false), Abstract(false), HasTrivialConstructor(true), Bases(0), NumBases(0), Conversions(DC, DeclarationName()), TemplateOrInstantiation() { } CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, CXXRecordDecl* PrevDecl) { CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, L, Id); C.getTypeDeclType(R, PrevDecl); return R; } CXXRecordDecl::~CXXRecordDecl() { delete [] Bases; } void CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases) { // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class (clause 9) with [...] // no base classes [...]. Aggregate = false; if (this->Bases) delete [] this->Bases; // FIXME: allocate using the ASTContext this->Bases = new CXXBaseSpecifier[NumBases]; this->NumBases = NumBases; for (unsigned i = 0; i < NumBases; ++i) this->Bases[i] = *Bases[i]; } bool CXXRecordDecl::hasConstCopyConstructor(ASTContext &Context) const { QualType ClassType = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this)); DeclarationName ConstructorName = Context.DeclarationNames.getCXXConstructorName( Context.getCanonicalType(ClassType)); unsigned TypeQuals; DeclContext::lookup_const_iterator Con, ConEnd; for (llvm::tie(Con, ConEnd) = this->lookup(Context, ConstructorName); Con != ConEnd; ++Con) { if (cast<CXXConstructorDecl>(*Con)->isCopyConstructor(Context, TypeQuals) && (TypeQuals & QualType::Const) != 0) return true; } return false; } bool CXXRecordDecl::hasConstCopyAssignment(ASTContext &Context) const { QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType( const_cast<CXXRecordDecl*>(this))); DeclarationName OpName =Context.DeclarationNames.getCXXOperatorName(OO_Equal); DeclContext::lookup_const_iterator Op, OpEnd; for (llvm::tie(Op, OpEnd) = this->lookup(Context, OpName); Op != OpEnd; ++Op) { // C++ [class.copy]p9: // A user-declared copy assignment operator is a non-static non-template // member function of class X with exactly one parameter of type X, X&, // const X&, volatile X& or const volatile X&. const CXXMethodDecl* Method = cast<CXXMethodDecl>(*Op); if (Method->isStatic()) continue; // TODO: Skip templates? Or is this implicitly done due to parameter types? const FunctionProtoType *FnType = Method->getType()->getAsFunctionProtoType(); assert(FnType && "Overloaded operator has no prototype."); // Don't assert on this; an invalid decl might have been left in the AST. if (FnType->getNumArgs() != 1 || FnType->isVariadic()) continue; bool AcceptsConst = true; QualType ArgType = FnType->getArgType(0); if (const LValueReferenceType *Ref = ArgType->getAsLValueReferenceType()) { ArgType = Ref->getPointeeType(); // Is it a non-const lvalue reference? if (!ArgType.isConstQualified()) AcceptsConst = false; } if (Context.getCanonicalType(ArgType).getUnqualifiedType() != ClassType) continue; // We have a single argument of type cv X or cv X&, i.e. we've found the // copy assignment operator. Return whether it accepts const arguments. return AcceptsConst; } assert(isInvalidDecl() && "No copy assignment operator declared in valid code."); return false; } void CXXRecordDecl::addedConstructor(ASTContext &Context, CXXConstructorDecl *ConDecl) { if (!ConDecl->isImplicit()) { // Note that we have a user-declared constructor. UserDeclaredConstructor = true; // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class (clause 9) with no // user-declared constructors (12.1) [...]. Aggregate = false; // C++ [class]p4: // A POD-struct is an aggregate class [...] PlainOldData = false; // C++ [class.ctor]p5: // A constructor is trivial if it is an implicitly-declared default // constructor. HasTrivialConstructor = false; // Note when we have a user-declared copy constructor, which will // suppress the implicit declaration of a copy constructor. if (ConDecl->isCopyConstructor(Context)) UserDeclaredCopyConstructor = true; } } void CXXRecordDecl::addedAssignmentOperator(ASTContext &Context, CXXMethodDecl *OpDecl) { // We're interested specifically in copy assignment operators. // Unlike addedConstructor, this method is not called for implicit // declarations. const FunctionProtoType *FnType = OpDecl->getType()->getAsFunctionProtoType(); assert(FnType && "Overloaded operator has no proto function type."); assert(FnType->getNumArgs() == 1 && !FnType->isVariadic()); QualType ArgType = FnType->getArgType(0); if (const LValueReferenceType *Ref = ArgType->getAsLValueReferenceType()) ArgType = Ref->getPointeeType(); ArgType = ArgType.getUnqualifiedType(); QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType( const_cast<CXXRecordDecl*>(this))); if (ClassType != Context.getCanonicalType(ArgType)) return; // This is a copy assignment operator. // Suppress the implicit declaration of a copy constructor. UserDeclaredCopyAssignment = true; // C++ [class]p4: // A POD-struct is an aggregate class that [...] has no user-defined copy // assignment operator [...]. PlainOldData = false; } void CXXRecordDecl::addConversionFunction(ASTContext &Context, CXXConversionDecl *ConvDecl) { Conversions.addOverload(ConvDecl); } CXXMethodDecl * CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isStatic, bool isInline) { return new (C) CXXMethodDecl(CXXMethod, RD, L, N, T, isStatic, isInline); } QualType CXXMethodDecl::getThisType(ASTContext &C) const { // C++ 9.3.2p1: The type of this in a member function of a class X is X*. // If the member function is declared const, the type of this is const X*, // if the member function is declared volatile, the type of this is // volatile X*, and if the member function is declared const volatile, // the type of this is const volatile X*. assert(isInstance() && "No 'this' for static methods!"); QualType ClassTy = C.getTagDeclType(const_cast<CXXRecordDecl*>(getParent())); ClassTy = ClassTy.getWithAdditionalQualifiers(getTypeQualifiers()); return C.getPointerType(ClassTy).withConst(); } CXXBaseOrMemberInitializer:: CXXBaseOrMemberInitializer(QualType BaseType, Expr **Args, unsigned NumArgs) : Args(0), NumArgs(0) { BaseOrMember = reinterpret_cast<uintptr_t>(BaseType.getTypePtr()); assert((BaseOrMember & 0x01) == 0 && "Invalid base class type pointer"); BaseOrMember |= 0x01; if (NumArgs > 0) { this->NumArgs = NumArgs; this->Args = new Expr*[NumArgs]; for (unsigned Idx = 0; Idx < NumArgs; ++Idx) this->Args[Idx] = Args[Idx]; } } CXXBaseOrMemberInitializer:: CXXBaseOrMemberInitializer(FieldDecl *Member, Expr **Args, unsigned NumArgs) : Args(0), NumArgs(0) { BaseOrMember = reinterpret_cast<uintptr_t>(Member); assert((BaseOrMember & 0x01) == 0 && "Invalid member pointer"); if (NumArgs > 0) { this->NumArgs = NumArgs; this->Args = new Expr*[NumArgs]; for (unsigned Idx = 0; Idx < NumArgs; ++Idx) this->Args[Idx] = Args[Idx]; } } CXXBaseOrMemberInitializer::~CXXBaseOrMemberInitializer() { delete [] Args; } CXXConstructorDecl * CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isExplicit, bool isInline, bool isImplicitlyDeclared) { assert(N.getNameKind() == DeclarationName::CXXConstructorName && "Name must refer to a constructor"); return new (C) CXXConstructorDecl(RD, L, N, T, isExplicit, isInline, isImplicitlyDeclared); } bool CXXConstructorDecl::isDefaultConstructor() const { // C++ [class.ctor]p5: // A default constructor for a class X is a constructor of class // X that can be called without an argument. return (getNumParams() == 0) || (getNumParams() > 0 && getParamDecl(0)->getDefaultArg() != 0); } bool CXXConstructorDecl::isCopyConstructor(ASTContext &Context, unsigned &TypeQuals) const { // C++ [class.copy]p2: // A non-template constructor for class X is a copy constructor // if its first parameter is of type X&, const X&, volatile X& or // const volatile X&, and either there are no other parameters // or else all other parameters have default arguments (8.3.6). if ((getNumParams() < 1) || (getNumParams() > 1 && getParamDecl(1)->getDefaultArg() == 0)) return false; const ParmVarDecl *Param = getParamDecl(0); // Do we have a reference type? Rvalue references don't count. const LValueReferenceType *ParamRefType = Param->getType()->getAsLValueReferenceType(); if (!ParamRefType) return false; // Is it a reference to our class type? QualType PointeeType = Context.getCanonicalType(ParamRefType->getPointeeType()); QualType ClassTy = Context.getTagDeclType(const_cast<CXXRecordDecl*>(getParent())); if (PointeeType.getUnqualifiedType() != ClassTy) return false; // We have a copy constructor. TypeQuals = PointeeType.getCVRQualifiers(); return true; } bool CXXConstructorDecl::isConvertingConstructor() const { // C++ [class.conv.ctor]p1: // A constructor declared without the function-specifier explicit // that can be called with a single parameter specifies a // conversion from the type of its first parameter to the type of // its class. Such a constructor is called a converting // constructor. if (isExplicit()) return false; return (getNumParams() == 0 && getType()->getAsFunctionProtoType()->isVariadic()) || (getNumParams() == 1) || (getNumParams() > 1 && getParamDecl(1)->getDefaultArg() != 0); } CXXDestructorDecl * CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isInline, bool isImplicitlyDeclared) { assert(N.getNameKind() == DeclarationName::CXXDestructorName && "Name must refer to a destructor"); return new (C) CXXDestructorDecl(RD, L, N, T, isInline, isImplicitlyDeclared); } CXXConversionDecl * CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isInline, bool isExplicit) { assert(N.getNameKind() == DeclarationName::CXXConversionFunctionName && "Name must refer to a conversion function"); return new (C) CXXConversionDecl(RD, L, N, T, isInline, isExplicit); } OverloadedFunctionDecl * OverloadedFunctionDecl::Create(ASTContext &C, DeclContext *DC, DeclarationName N) { return new (C) OverloadedFunctionDecl(DC, N); } LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, LanguageIDs Lang, bool Braces) { return new (C) LinkageSpecDecl(DC, L, Lang, Braces); } UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, SourceLocation NamespaceLoc, SourceLocation IdentLoc, NamespaceDecl *Used, DeclContext *CommonAncestor) { return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, IdentLoc, Used, CommonAncestor); } NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation IdentLoc, NamedDecl *Namespace) { return new (C) NamespaceAliasDecl(DC, L, AliasLoc, Alias, IdentLoc, Namespace); } StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, Expr *AssertExpr, StringLiteral *Message) { return new (C) StaticAssertDecl(DC, L, AssertExpr, Message); } void StaticAssertDecl::Destroy(ASTContext& C) { AssertExpr->Destroy(C); Message->Destroy(C); this->~StaticAssertDecl(); C.Deallocate((void *)this); } StaticAssertDecl::~StaticAssertDecl() { } static const char *getAccessName(AccessSpecifier AS) { switch (AS) { default: case AS_none: assert("Invalid access specifier!"); return 0; case AS_public: return "public"; case AS_private: return "private"; case AS_protected: return "protected"; } } const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB, AccessSpecifier AS) { return DB << getAccessName(AS); } <file_sep>/test/CodeGen/ext-vector.c // RUN: clang-cc -emit-llvm %s -o %t typedef __attribute__(( ext_vector_type(4) )) float float4; typedef __attribute__(( ext_vector_type(2) )) float float2; typedef __attribute__(( ext_vector_type(4) )) int int4; float4 foo = (float4){ 1.0, 2.0, 3.0, 4.0 }; const float4 bar = (float4){ 1.0, 2.0, 3.0, __builtin_inff() }; float4 test1(float4 V) { return V.wzyx+V; } float2 vec2, vec2_2; float4 vec4, vec4_2; float f; void test2() { vec2 = vec4.xy; // shorten f = vec2.x; // extract elt vec4 = vec4.yyyy; // splat vec2.x = f; // insert one. vec2.yx = vec2; // reverse } void test3(float4 *out) { *out = ((float4) {1.0f, 2.0f, 3.0f, 4.0f }); } void test4(float4 *out) { float a = 1.0f; float b = 2.0f; float c = 3.0f; float d = 4.0f; *out = ((float4) {a,b,c,d}); } void test5(float4 *out) { float a; float4 b; a = 1.0f; b = a; b = b * 5.0f; b = 5.0f * b; b *= a; *out = b; } void test6(float4 *ap, float4 *bp, float c) { float4 a = *ap; float4 b = *bp; a = a + b; a = a - b; a = a * b; a = a / b; a = a + c; a = a - c; a = a * c; a = a / c; a += b; a -= b; a *= b; a /= b; a += c; a -= c; a *= c; a /= c; // Vector comparisons can sometimes crash the x86 backend: rdar://6326239, // reject them until the implementation is stable. #if 0 int4 cmp; cmp = a < b; cmp = a <= b; cmp = a < b; cmp = a >= b; cmp = a == b; cmp = a != b; #endif } void test7(int4 *ap, int4 *bp, int c) { int4 a = *ap; int4 b = *bp; a = a + b; a = a - b; a = a * b; a = a / b; a = a % b; a = a + c; a = a - c; a = a * c; a = a / c; a = a % c; a += b; a -= b; a *= b; a /= b; a %= b; a += c; a -= c; a *= c; a /= c; a %= c; // Vector comparisons can sometimes crash the x86 backend: rdar://6326239, // reject them until the implementation is stable. #if 0 int4 cmp; cmp = a < b; cmp = a <= b; cmp = a < b; cmp = a >= b; cmp = a == b; cmp = a != b; #endif } <file_sep>/test/Driver/phases.c // Basic compilation for various types of files. // RUN: clang -ccc-host-triple i386-unknown-unknown -ccc-print-phases -x c %s -x objective-c %s -x c++ %s -x objective-c++ -x assembler %s -x assembler-with-cpp %s -x none %s 2> %t && // RUN: grep '0: input, ".*phases.c", c' %t && // RUN: grep -F '1: preprocessor, {0}, cpp-output' %t && // RUN: grep -F '2: compiler, {1}, assembler' %t && // RUN: grep -F '3: assembler, {2}, object' %t && // RUN: grep '4: input, ".*phases.c", objective-c' %t && // RUN: grep -F '5: preprocessor, {4}, objective-c-cpp-output' %t && // RUN: grep -F '6: compiler, {5}, assembler' %t && // RUN: grep -F '7: assembler, {6}, object' %t && // RUN: grep '8: input, ".*phases.c", c++' %t && // RUN: grep -F '9: preprocessor, {8}, c++-cpp-output' %t && // RUN: grep -F '10: compiler, {9}, assembler' %t && // RUN: grep -F '11: assembler, {10}, object' %t && // RUN: grep '12: input, ".*phases.c", assembler' %t && // RUN: grep -F '13: assembler, {12}, object' %t && // RUN: grep '14: input, ".*phases.c", assembler-with-cpp' %t && // RUN: grep -F '15: preprocessor, {14}, assembler' %t && // RUN: grep -F '16: assembler, {15}, object' %t && // RUN: grep '17: input, ".*phases.c", c' %t && // RUN: grep -F '18: preprocessor, {17}, cpp-output' %t && // RUN: grep -F '19: compiler, {18}, assembler' %t && // RUN: grep -F '20: assembler, {19}, object' %t && // RUN: grep -F '21: linker, {3, 7, 11, 13, 16, 20}, image' %t && // Universal linked image. // RUN: clang -ccc-host-triple i386-apple-darwin9 -ccc-print-phases -x c %s -arch ppc -arch i386 2> %t && // RUN: grep '0: input, ".*phases.c", c' %t && // RUN: grep -F '1: preprocessor, {0}, cpp-output' %t && // RUN: grep -F '2: compiler, {1}, assembler' %t && // RUN: grep -F '3: assembler, {2}, object' %t && // RUN: grep -F '4: linker, {3}, image' %t && // RUN: grep -F '5: bind-arch, "ppc", {4}, image' %t && // RUN: grep -F '6: bind-arch, "i386", {4}, image' %t && // RUN: grep -F '7: lipo, {5, 6}, image' %t && // Universal object file. // RUN: clang -ccc-host-triple i386-apple-darwin9 -ccc-print-phases -c -x c %s -arch ppc -arch i386 2> %t && // RUN: grep '0: input, ".*phases.c", c' %t && // RUN: grep -F '1: preprocessor, {0}, cpp-output' %t && // RUN: grep -F '2: compiler, {1}, assembler' %t && // RUN: grep -F '3: assembler, {2}, object' %t && // RUN: grep -F '4: bind-arch, "ppc", {3}, object' %t && // RUN: grep -F '5: bind-arch, "i386", {3}, object' %t && // RUN: grep -F '6: lipo, {4, 5}, object' %t && // Arch defaulting // RUN: clang -ccc-host-triple i386-apple-darwin9 -ccc-print-phases -c -x assembler %s 2> %t && // RUN: grep -F '2: bind-arch, "i386", {1}, object' %t && // RUN: clang -ccc-host-triple i386-apple-darwin9 -ccc-print-phases -c -x assembler %s -m32 -m64 2> %t && // RUN: grep -F '2: bind-arch, "x86_64", {1}, object' %t && // RUN: clang -ccc-host-triple x86_64-apple-darwin9 -ccc-print-phases -c -x assembler %s 2> %t && // RUN: grep -F '2: bind-arch, "x86_64", {1}, object' %t && // RUN: clang -ccc-host-triple x86_64-apple-darwin9 -ccc-print-phases -c -x assembler %s -m64 -m32 2> %t && // RUN: grep -F '2: bind-arch, "i386", {1}, object' %t && // Analyzer // RUN: clang -ccc-host-triple i386-unknown-unknown -ccc-print-phases --analyze %s 2> %t && // RUN: grep '0: input, ".*phases.c", c' %t && // RUN: grep -F '1: preprocessor, {0}, cpp-output' %t && // RUN: grep -F '2: analyzer, {1}, plist' %t && // Precompiler // RUN: clang -ccc-host-triple i386-unknown-unknown -ccc-print-phases -x c-header %s 2> %t && // RUN: grep '0: input, ".*phases.c", c-header' %t && // RUN: grep -F '1: preprocessor, {0}, c-header-cpp-output' %t && // RUN: grep -F '2: precompiler, {1}, precompiled-header' %t && // Darwin overrides the handling for .s // RUN: touch %t.s && // RUN: clang -ccc-host-triple i386-unknown-unknown -ccc-print-phases -c %t.s 2> %t && // RUN: grep '0: input, ".*\.s", assembler' %t && // RUN: grep -F '1: assembler, {0}, object' %t && // RUN: clang -ccc-host-triple i386-apple-darwin9 -ccc-print-phases -c %t.s 2> %t && // RUN: grep '0: input, ".*\.s", assembler-with-cpp' %t && // RUN: grep -F '1: preprocessor, {0}, assembler' %t && // RUN: grep -F '2: assembler, {1}, object' %t && // RUN: true <file_sep>/lib/AST/NestedNameSpecifier.cpp //===--- NestedNameSpecifier.cpp - C++ nested name specifiers -----*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the NestedNameSpecifier class, which represents // a C++ nested-name-specifier. // //===----------------------------------------------------------------------===// #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" #include <cassert> using namespace clang; NestedNameSpecifier * NestedNameSpecifier::FindOrInsert(ASTContext &Context, const NestedNameSpecifier &Mockup) { llvm::FoldingSetNodeID ID; Mockup.Profile(ID); void *InsertPos = 0; NestedNameSpecifier *NNS = Context.NestedNameSpecifiers.FindNodeOrInsertPos(ID, InsertPos); if (!NNS) { NNS = new (Context, 4) NestedNameSpecifier(Mockup); Context.NestedNameSpecifiers.InsertNode(NNS, InsertPos); } return NNS; } NestedNameSpecifier * NestedNameSpecifier::Create(ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II) { assert(II && "Identifier cannot be NULL"); assert(Prefix && Prefix->isDependent() && "Prefix must be dependent"); NestedNameSpecifier Mockup; Mockup.Prefix.setPointer(Prefix); Mockup.Prefix.setInt(Identifier); Mockup.Specifier = II; return FindOrInsert(Context, Mockup); } NestedNameSpecifier * NestedNameSpecifier::Create(ASTContext &Context, NestedNameSpecifier *Prefix, NamespaceDecl *NS) { assert(NS && "Namespace cannot be NULL"); assert((!Prefix || (Prefix->getAsType() == 0 && Prefix->getAsIdentifier() == 0)) && "Broken nested name specifier"); NestedNameSpecifier Mockup; Mockup.Prefix.setPointer(Prefix); Mockup.Prefix.setInt(Namespace); Mockup.Specifier = NS; return FindOrInsert(Context, Mockup); } NestedNameSpecifier * NestedNameSpecifier::Create(ASTContext &Context, NestedNameSpecifier *Prefix, bool Template, Type *T) { assert(T && "Type cannot be NULL"); NestedNameSpecifier Mockup; Mockup.Prefix.setPointer(Prefix); Mockup.Prefix.setInt(Template? TypeSpecWithTemplate : TypeSpec); Mockup.Specifier = T; return FindOrInsert(Context, Mockup); } NestedNameSpecifier *NestedNameSpecifier::GlobalSpecifier(ASTContext &Context) { if (!Context.GlobalNestedNameSpecifier) Context.GlobalNestedNameSpecifier = new (Context, 4) NestedNameSpecifier(); return Context.GlobalNestedNameSpecifier; } /// \brief Whether this nested name specifier refers to a dependent /// type or not. bool NestedNameSpecifier::isDependent() const { switch (getKind()) { case Identifier: // Identifier specifiers always represent dependent types return true; case Namespace: case Global: return false; case TypeSpec: case TypeSpecWithTemplate: return getAsType()->isDependentType(); } // Necessary to suppress a GCC warning. return false; } /// \brief Print this nested name specifier to the given output /// stream. void NestedNameSpecifier::print(llvm::raw_ostream &OS) const { if (getPrefix()) getPrefix()->print(OS); switch (getKind()) { case Identifier: OS << getAsIdentifier()->getName(); break; case Namespace: OS << getAsNamespace()->getIdentifier()->getName(); break; case Global: break; case TypeSpecWithTemplate: OS << "template "; // Fall through to print the type. case TypeSpec: { std::string TypeStr; Type *T = getAsType(); // If this is a qualified name type, suppress the qualification: // it's part of our nested-name-specifier sequence anyway. FIXME: // We should be able to assert that this doesn't happen. if (const QualifiedNameType *QualT = dyn_cast<QualifiedNameType>(T)) T = QualT->getNamedType().getTypePtr(); if (const TagType *TagT = dyn_cast<TagType>(T)) TagT->getAsStringInternal(TypeStr, true); else T->getAsStringInternal(TypeStr); OS << TypeStr; break; } } OS << "::"; } void NestedNameSpecifier::Destroy(ASTContext &Context) { this->~NestedNameSpecifier(); Context.Deallocate((void *)this); } void NestedNameSpecifier::dump() { print(llvm::errs()); } <file_sep>/include/clang/AST/ASTConsumer.h //===--- ASTConsumer.h - Abstract interface for reading ASTs ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTConsumer class. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_ASTCONSUMER_H #define LLVM_CLANG_AST_ASTCONSUMER_H namespace clang { class ASTContext; class DeclGroupRef; class TagDecl; class HandleTagDeclDefinition; /// ASTConsumer - This is an abstract interface that should be implemented by /// clients that read ASTs. This abstraction layer allows the client to be /// independent of the AST producer (e.g. parser vs AST dump file reader, etc). class ASTConsumer { public: virtual ~ASTConsumer() {} /// Initialize - This is called to initialize the consumer, providing the /// ASTContext. virtual void Initialize(ASTContext &Context) {} /// HandleTopLevelDecl - Handle the specified top-level declaration. This is /// called by the parser to process every top-level Decl*. Note that D can /// be the head of a chain of Decls (e.g. for `int a, b` the chain will have /// two elements). Use Decl::getNextDeclarator() to walk the chain. virtual void HandleTopLevelDecl(DeclGroupRef D); /// HandleTranslationUnit - This method is called when the ASTs for entire /// translation unit have been parsed. virtual void HandleTranslationUnit(ASTContext &Ctx) {} /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl /// (e.g. struct, union, enum, class) is completed. This allows the client to /// hack on the type, which can occur at any point in the file (because these /// can be defined in declspecs). virtual void HandleTagDeclDefinition(TagDecl *D) {} /// PrintStats - If desired, print any statistics. virtual void PrintStats() { } }; } // end namespace clang. #endif <file_sep>/lib/Driver/ToolChains.h //===--- ToolChains.h - ToolChain Implementations ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef CLANG_LIB_DRIVER_TOOLCHAINS_H_ #define CLANG_LIB_DRIVER_TOOLCHAINS_H_ #include "clang/Driver/Action.h" #include "clang/Driver/ToolChain.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/Compiler.h" #include "Tools.h" namespace clang { namespace driver { namespace toolchains { /// Generic_GCC - A tool chain using the 'gcc' command to perform /// all subcommands; this relies on gcc translating the majority of /// command line options. class VISIBILITY_HIDDEN Generic_GCC : public ToolChain { protected: mutable llvm::DenseMap<unsigned, Tool*> Tools; public: Generic_GCC(const HostInfo &Host, const char *Arch, const char *Platform, const char *OS); ~Generic_GCC(); virtual DerivedArgList *TranslateArgs(InputArgList &Args) const; virtual Tool &SelectTool(const Compilation &C, const JobAction &JA) const; virtual bool IsMathErrnoDefault() const; virtual bool IsUnwindTablesDefault() const; virtual const char *GetDefaultRelocationModel() const; virtual const char *GetForcedPicModel() const; }; /// Darwin_X86 - Darwin tool chain for i386 an x86_64. class VISIBILITY_HIDDEN Darwin_X86 : public ToolChain { mutable llvm::DenseMap<unsigned, Tool*> Tools; /// Darwin version of tool chain. unsigned DarwinVersion[3]; /// GCC version to use. unsigned GCCVersion[3]; /// The directory suffix for this tool chain. std::string ToolChainDir; /// The default macosx-version-min of this tool chain; empty until /// initialized. mutable std::string MacosxVersionMin; const char *getMacosxVersionMin() const; public: Darwin_X86(const HostInfo &Host, const char *Arch, const char *Platform, const char *OS, const unsigned (&DarwinVersion)[3], const unsigned (&GCCVersion)[3]); ~Darwin_X86(); void getDarwinVersion(unsigned (&Res)[3]) const { Res[0] = DarwinVersion[0]; Res[1] = DarwinVersion[1]; Res[2] = DarwinVersion[2]; } void getMacosxVersion(unsigned (&Res)[3]) const { Res[0] = 10; Res[1] = DarwinVersion[0] - 4; Res[2] = DarwinVersion[1]; } const char *getMacosxVersionStr() const { return MacosxVersionMin.c_str(); } const std::string &getToolChainDir() const { return ToolChainDir; } virtual DerivedArgList *TranslateArgs(InputArgList &Args) const; virtual Tool &SelectTool(const Compilation &C, const JobAction &JA) const; virtual bool IsMathErrnoDefault() const; virtual bool IsUnwindTablesDefault() const; virtual const char *GetDefaultRelocationModel() const; virtual const char *GetForcedPicModel() const; }; /// Darwin_GCC - Generic Darwin tool chain using gcc. class VISIBILITY_HIDDEN Darwin_GCC : public Generic_GCC { public: Darwin_GCC(const HostInfo &Host, const char *Arch, const char *Platform, const char *OS) : Generic_GCC(Host, Arch, Platform, OS) {} virtual const char *GetDefaultRelocationModel() const { return "pic"; } }; class VISIBILITY_HIDDEN FreeBSD : public Generic_GCC { public: FreeBSD(const HostInfo &Host, const char *Arch, const char *Platform, const char *OS, bool Lib32); virtual Tool &SelectTool(const Compilation &C, const JobAction &JA) const; }; } // end namespace toolchains } // end namespace driver } // end namespace clang #endif <file_sep>/lib/Sema/SemaTemplateInstantiateDecl.cpp //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/ // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. //===----------------------------------------------------------------------===/ // // This file implements C++ template instantiation for declarations. // //===----------------------------------------------------------------------===/ #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/Expr.h" #include "llvm/Support/Compiler.h" using namespace clang; namespace { class VISIBILITY_HIDDEN TemplateDeclInstantiator : public DeclVisitor<TemplateDeclInstantiator, Decl *> { Sema &SemaRef; DeclContext *Owner; const TemplateArgument *TemplateArgs; unsigned NumTemplateArgs; public: typedef Sema::OwningExprResult OwningExprResult; TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs), NumTemplateArgs(NumTemplateArgs) { } // FIXME: Once we get closer to completion, replace these // manually-written declarations with automatically-generated ones // from clang/AST/DeclNodes.def. Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); Decl *VisitNamespaceDecl(NamespaceDecl *D); Decl *VisitTypedefDecl(TypedefDecl *D); Decl *VisitVarDecl(VarDecl *D); Decl *VisitFieldDecl(FieldDecl *D); Decl *VisitStaticAssertDecl(StaticAssertDecl *D); Decl *VisitEnumDecl(EnumDecl *D); Decl *VisitEnumConstantDecl(EnumConstantDecl *D); Decl *VisitCXXRecordDecl(CXXRecordDecl *D); Decl *VisitCXXMethodDecl(CXXMethodDecl *D); Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); Decl *VisitCXXConversionDecl(CXXConversionDecl *D); ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D); // Base case. FIXME: Remove once we can instantiate everything. Decl *VisitDecl(Decl *) { assert(false && "Template instantiation of unknown declaration kind!"); return 0; } // Helper functions for instantiating methods. QualType InstantiateFunctionType(FunctionDecl *D, llvm::SmallVectorImpl<ParmVarDecl *> &Params); bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); }; } Decl * TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { assert(false && "Translation units cannot be instantiated"); return D; } Decl * TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { assert(false && "Namespaces cannot be instantiated"); return D; } Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { bool Invalid = false; QualType T = D->getUnderlyingType(); if (T->isDependentType()) { T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs, D->getLocation(), D->getDeclName()); if (T.isNull()) { Invalid = true; T = SemaRef.Context.IntTy; } } // Create the new typedef TypedefDecl *Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T); if (Invalid) Typedef->setInvalidDecl(); Owner->addDecl(SemaRef.Context, Typedef); return Typedef; } Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { // Instantiate the type of the declaration QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs, NumTemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName()); if (T.isNull()) return 0; // Build the instantiataed declaration VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T, D->getStorageClass(), D->getTypeSpecStartLoc()); Var->setThreadSpecified(D->isThreadSpecified()); Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); Var->setDeclaredInCondition(D->isDeclaredInCondition()); // FIXME: In theory, we could have a previous declaration for // variables that are not static data members. bool Redeclaration = false; if (SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration)) Var->setInvalidDecl(); Owner->addDecl(SemaRef.Context, Var); if (D->getInit()) { OwningExprResult Init = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs, NumTemplateArgs); if (Init.isInvalid()) Var->setInvalidDecl(); else SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), D->hasCXXDirectInitializer()); } return Var; } Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { bool Invalid = false; QualType T = D->getType(); if (T->isDependentType()) { T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs, D->getLocation(), D->getDeclName()); if (!T.isNull() && T->isFunctionType()) { // C++ [temp.arg.type]p3: // If a declaration acquires a function type through a type // dependent on a template-parameter and this causes a // declaration that does not use the syntactic form of a // function declarator to have function type, the program is // ill-formed. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) << T; T = QualType(); Invalid = true; } } Expr *BitWidth = D->getBitWidth(); if (Invalid) BitWidth = 0; else if (BitWidth) { OwningExprResult InstantiatedBitWidth = SemaRef.InstantiateExpr(BitWidth, TemplateArgs, NumTemplateArgs); if (InstantiatedBitWidth.isInvalid()) { Invalid = true; BitWidth = 0; } else BitWidth = (Expr *)InstantiatedBitWidth.release(); } FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T, cast<RecordDecl>(Owner), D->getLocation(), D->isMutable(), BitWidth, D->getAccess(), 0); if (Field) { if (Invalid) Field->setInvalidDecl(); Owner->addDecl(SemaRef.Context, Field); } return Field; } Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { Expr *AssertExpr = D->getAssertExpr(); OwningExprResult InstantiatedAssertExpr = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs, NumTemplateArgs); if (InstantiatedAssertExpr.isInvalid()) return 0; OwningExprResult Message = SemaRef.Clone(D->getMessage()); Decl *StaticAssert = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), move(InstantiatedAssertExpr), move(Message)).getAs<Decl>(); return StaticAssert; } Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), /*PrevDecl=*/0); Enum->setAccess(D->getAccess()); Owner->addDecl(SemaRef.Context, Enum); Enum->startDefinition(); llvm::SmallVector<Sema::DeclPtrTy, 16> Enumerators; EnumConstantDecl *LastEnumConst = 0; for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(SemaRef.Context), ECEnd = D->enumerator_end(SemaRef.Context); EC != ECEnd; ++EC) { // The specified value for the enumerator. OwningExprResult Value = SemaRef.Owned((Expr *)0); if (Expr *UninstValue = EC->getInitExpr()) Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs, NumTemplateArgs); // Drop the initial value and continue. bool isInvalid = false; if (Value.isInvalid()) { Value = SemaRef.Owned((Expr *)0); isInvalid = true; } EnumConstantDecl *EnumConst = SemaRef.CheckEnumConstant(Enum, LastEnumConst, EC->getLocation(), EC->getIdentifier(), move(Value)); if (isInvalid) { if (EnumConst) EnumConst->setInvalidDecl(); Enum->setInvalidDecl(); } if (EnumConst) { Enum->addDecl(SemaRef.Context, EnumConst); Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); LastEnumConst = EnumConst; } } SemaRef.ActOnEnumBody(Enum->getLocation(), Sema::DeclPtrTy::make(Enum), &Enumerators[0], Enumerators.size()); return Enum; } Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { assert(false && "EnumConstantDecls can only occur within EnumDecls."); return 0; } Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { CXXRecordDecl *PrevDecl = 0; if (D->isInjectedClassName()) PrevDecl = cast<CXXRecordDecl>(Owner); CXXRecordDecl *Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, D->getLocation(), D->getIdentifier(), PrevDecl); Record->setImplicit(D->isImplicit()); Record->setAccess(D->getAccess()); if (!D->isInjectedClassName()) Record->setInstantiationOfMemberClass(D); else Record->setDescribedClassTemplate(D->getDescribedClassTemplate()); Owner->addDecl(SemaRef.Context, Record); return Record; } Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { // Only handle actual methods; we'll deal with constructors, // destructors, etc. separately. if (D->getKind() != Decl::CXXMethod) return 0; llvm::SmallVector<ParmVarDecl *, 16> Params; QualType T = InstantiateFunctionType(D, Params); if (T.isNull()) return 0; // Build the instantiated method declaration. CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); CXXMethodDecl *Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), D->getDeclName(), T, D->isStatic(), D->isInline()); // Attach the parameters for (unsigned P = 0; P < Params.size(); ++P) Params[P]->setOwningFunction(Method); Method->setParams(SemaRef.Context, &Params[0], Params.size()); if (InitMethodInstantiation(Method, D)) Method->setInvalidDecl(); NamedDecl *PrevDecl = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(), Sema::LookupOrdinaryName, true); // In C++, the previous declaration we find might be a tag type // (class or enum). In this case, the new declaration will hide the // tag type. Note that this does does not apply if we're declaring a // typedef (C++ [dcl.typedef]p4). if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) PrevDecl = 0; bool Redeclaration = false; bool OverloadableAttrRequired = false; if (SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration, /*FIXME:*/OverloadableAttrRequired)) Method->setInvalidDecl(); if (!Method->isInvalidDecl() || !PrevDecl) Owner->addDecl(SemaRef.Context, Method); return Method; } Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { llvm::SmallVector<ParmVarDecl *, 16> Params; QualType T = InstantiateFunctionType(D, Params); if (T.isNull()) return 0; // Build the instantiated method declaration. CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); DeclarationName Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(ClassTy); CXXConstructorDecl *Constructor = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(), Name, T, D->isExplicit(), D->isInline(), false); // Attach the parameters for (unsigned P = 0; P < Params.size(); ++P) Params[P]->setOwningFunction(Constructor); Constructor->setParams(SemaRef.Context, &Params[0], Params.size()); if (InitMethodInstantiation(Constructor, D)) Constructor->setInvalidDecl(); NamedDecl *PrevDecl = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true); // In C++, the previous declaration we find might be a tag type // (class or enum). In this case, the new declaration will hide the // tag type. Note that this does does not apply if we're declaring a // typedef (C++ [dcl.typedef]p4). if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) PrevDecl = 0; bool Redeclaration = false; bool OverloadableAttrRequired = false; if (SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration, /*FIXME:*/OverloadableAttrRequired)) Constructor->setInvalidDecl(); if (!Constructor->isInvalidDecl()) Owner->addDecl(SemaRef.Context, Constructor); return Constructor; } Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { llvm::SmallVector<ParmVarDecl *, 16> Params; QualType T = InstantiateFunctionType(D, Params); if (T.isNull()) return 0; assert(Params.size() == 0 && "Destructor with parameters?"); // Build the instantiated destructor declaration. CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(SemaRef.Context, Record, D->getLocation(), SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy), T, D->isInline(), false); if (InitMethodInstantiation(Destructor, D)) Destructor->setInvalidDecl(); bool Redeclaration = false; bool OverloadableAttrRequired = false; NamedDecl *PrevDecl = 0; if (SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration, /*FIXME:*/OverloadableAttrRequired)) Destructor->setInvalidDecl(); Owner->addDecl(SemaRef.Context, Destructor); return Destructor; } Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { llvm::SmallVector<ParmVarDecl *, 16> Params; QualType T = InstantiateFunctionType(D, Params); if (T.isNull()) return 0; assert(Params.size() == 0 && "Destructor with parameters?"); // Build the instantiated conversion declaration. CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); QualType ConvTy = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType()); CXXConversionDecl *Conversion = CXXConversionDecl::Create(SemaRef.Context, Record, D->getLocation(), SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy), T, D->isInline(), D->isExplicit()); if (InitMethodInstantiation(Conversion, D)) Conversion->setInvalidDecl(); bool Redeclaration = false; bool OverloadableAttrRequired = false; NamedDecl *PrevDecl = 0; if (SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration, /*FIXME:*/OverloadableAttrRequired)) Conversion->setInvalidDecl(); Owner->addDecl(SemaRef.Context, Conversion); return Conversion; } ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs, NumTemplateArgs, D->getLocation(), D->getDeclName()); if (OrigT.isNull()) return 0; QualType T = SemaRef.adjustParameterType(OrigT); if (D->getDefaultArg()) { // FIXME: Leave a marker for "uninstantiated" default // arguments. They only get instantiated on demand at the call // site. unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning, "sorry, dropping default argument during template instantiation"); SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID) << D->getDefaultArg()->getSourceRange(); } // Allocate the parameter ParmVarDecl *Param = 0; if (T == OrigT) Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T, D->getStorageClass(), 0); else Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T, OrigT, D->getStorageClass(), 0); // Note: we don't try to instantiate function parameters until after // we've instantiated the function's type. Therefore, we don't have // to check for 'void' parameter types here. return Param; } Decl * TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) { // Since parameter types can decay either before or after // instantiation, we simply treat OriginalParmVarDecls as // ParmVarDecls the same way, and create one or the other depending // on what happens after template instantiation. return VisitParmVarDecl(D); } Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs, NumTemplateArgs); return Instantiator.Visit(D); } /// \brief Instantiates the type of the given function, including /// instantiating all of the function parameters. /// /// \param D The function that we will be instantiated /// /// \param Params the instantiated parameter declarations /// \returns the instantiated function's type if successfull, a NULL /// type if there was an error. QualType TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D, llvm::SmallVectorImpl<ParmVarDecl *> &Params) { bool InvalidDecl = false; // Instantiate the function parameters TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs, NumTemplateArgs); llvm::SmallVector<QualType, 16> ParamTys; for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end(); P != PEnd; ++P) { if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { if (PInst->getType()->isVoidType()) { SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); PInst->setInvalidDecl(); } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), PInst->getType(), diag::err_abstract_type_in_decl, Sema::AbstractParamType)) PInst->setInvalidDecl(); Params.push_back(PInst); ParamTys.push_back(PInst->getType()); if (PInst->isInvalidDecl()) InvalidDecl = true; } else InvalidDecl = true; } // FIXME: Deallocate dead declarations. if (InvalidDecl) return QualType(); const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType(); assert(Proto && "Missing prototype?"); QualType ResultType = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs, NumTemplateArgs, D->getLocation(), D->getDeclName()); if (ResultType.isNull()) return QualType(); return SemaRef.BuildFunctionType(ResultType, &ParamTys[0], ParamTys.size(), Proto->isVariadic(), Proto->getTypeQuals(), D->getLocation(), D->getDeclName()); } /// \brief Initializes common fields of an instantiated method /// declaration (New) from the corresponding fields of its template /// (Tmpl). /// /// \returns true if there was an error bool TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl) { CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); New->setAccess(Tmpl->getAccess()); if (Tmpl->isVirtual()) { New->setVirtual(); Record->setAggregate(false); Record->setPOD(false); Record->setPolymorphic(true); } if (Tmpl->isDeleted()) New->setDeleted(); if (Tmpl->isPure()) { New->setPure(); Record->setAbstract(true); } // FIXME: attributes // FIXME: New needs a pointer to Tmpl return false; } <file_sep>/lib/AST/DeclGroup.cpp //===--- DeclGroup.cpp - Classes for representing groups of Decls -*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the DeclGroup and DeclGroupRef classes. // //===----------------------------------------------------------------------===// #include "clang/AST/DeclGroup.h" #include "clang/AST/Decl.h" #include "clang/AST/ASTContext.h" #include "llvm/Support/Allocator.h" #include "llvm/Bitcode/Serialize.h" #include "llvm/Bitcode/Deserialize.h" using namespace clang; DeclGroup* DeclGroup::Create(ASTContext &C, Decl **Decls, unsigned NumDecls) { assert(NumDecls > 1 && "Invalid DeclGroup"); unsigned Size = sizeof(DeclGroup) + sizeof(Decl*) * NumDecls; void* Mem = C.Allocate(Size, llvm::AlignOf<DeclGroup>::Alignment); new (Mem) DeclGroup(NumDecls, Decls); return static_cast<DeclGroup*>(Mem); } /// Emit - Serialize a DeclGroup to Bitcode. void DeclGroup::Emit(llvm::Serializer& S) const { S.EmitInt(NumDecls); S.BatchEmitOwnedPtrs(NumDecls, &(*this)[0]); } /// Read - Deserialize a DeclGroup from Bitcode. DeclGroup* DeclGroup::Read(llvm::Deserializer& D, ASTContext& C) { unsigned NumDecls = (unsigned) D.ReadInt(); unsigned Size = sizeof(DeclGroup) + sizeof(Decl*) * NumDecls; unsigned alignment = llvm::AlignOf<DeclGroup>::Alignment; DeclGroup* DG = (DeclGroup*) C.Allocate(Size, alignment); new (DG) DeclGroup(); DG->NumDecls = NumDecls; D.BatchReadOwnedPtrs(NumDecls, &(*DG)[0], C); return DG; } DeclGroup::DeclGroup(unsigned numdecls, Decl** decls) : NumDecls(numdecls) { assert(numdecls > 0); assert(decls); memcpy(this+1, decls, numdecls * sizeof(*decls)); } void DeclGroup::Destroy(ASTContext& C) { this->~DeclGroup(); C.Deallocate((void*) this); } void DeclGroupRef::Emit(llvm::Serializer& S) const { if (isSingleDecl()) { S.EmitBool(false); S.EmitPtr(D); } else { S.EmitBool(true); S.EmitPtr(&getDeclGroup()); } } DeclGroupRef DeclGroupRef::ReadVal(llvm::Deserializer& D) { if (D.ReadBool()) return DeclGroupRef(D.ReadPtr<Decl>()); return DeclGroupRef(D.ReadPtr<DeclGroup>()); } <file_sep>/CMakeLists.txt macro(add_clang_library name) set(srcs ${ARGN}) if(MSVC_IDE OR XCODE) file( GLOB_RECURSE headers *.h) set(srcs ${srcs} ${headers}) string( REGEX MATCHALL "/[^/]+" split_path ${CMAKE_CURRENT_SOURCE_DIR}) list( GET split_path -1 dir) file( GLOB_RECURSE headers ../../include/clang${dir}/*.h) set(srcs ${srcs} ${headers}) endif(MSVC_IDE OR XCODE) add_library( ${name} ${srcs} ) if( LLVM_COMMON_DEPENDS ) add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} ) endif( LLVM_COMMON_DEPENDS ) add_dependencies(${name} ClangDiagnosticCommon) if(MSVC) get_target_property(cflag ${name} COMPILE_FLAGS) if(NOT cflag) set(cflag "") endif(NOT cflag) set(cflag "${cflag} /Za") set_target_properties(${name} PROPERTIES COMPILE_FLAGS ${cflag}) endif(MSVC) install(TARGETS ${name} LIBRARY DESTINATION lib ARCHIVE DESTINATION lib) endmacro(add_clang_library) macro(add_clang_executable name) set(srcs ${ARGN}) if(MSVC_IDE) file( GLOB_RECURSE headers *.h) set(srcs ${srcs} ${headers}) endif(MSVC_IDE) add_llvm_executable( ${name} ${srcs} ) install(TARGETS ${name} RUNTIME DESTINATION bin) endmacro(add_clang_executable) include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include ) install(DIRECTORY include DESTINATION . PATTERN ".svn" EXCLUDE ) add_definitions( -D_GNU_SOURCE ) add_subdirectory(include) add_subdirectory(lib) add_subdirectory(tools) # TODO: docs. <file_sep>/test/CodeGen/rdr-6098585-default-fallthrough-to-caserange.c // RUN: clang-cc -triple i386-unknown-unknown --emit-llvm-bc -o - %s | opt -std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32 10" %t // Ensure that this doesn't compile to infinite loop in g() due to // miscompilation of fallthrough from default to a (tested) case // range. static int f0(unsigned x) { switch(x) { default: x += 1; case 10 ... 0xFFFFFFFF: return 0; } } int g() { f0(1); return 10; } <file_sep>/test/CodeGen/flexible-array-init.c // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm -o - %s | grep 7 | count 1 && // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm -o - %s | grep 11 | count 1 && // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm -o - %s | grep 13 | count 1 && // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm -o - %s | grep 15 | count 1 struct { int x; int y[]; } a = { 1, 7, 11 }; struct { int x; int y[]; } b = { 1, { 13, 15 } }; <file_sep>/lib/Sema/SemaAttr.cpp //===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for non-trivial attributes and // pragmas. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/AST/Expr.h" using namespace clang; //===----------------------------------------------------------------------===// // Pragma Packed //===----------------------------------------------------------------------===// namespace { /// PragmaPackStack - Simple class to wrap the stack used by #pragma /// pack. class PragmaPackStack { typedef std::vector< std::pair<unsigned, IdentifierInfo*> > stack_ty; /// Alignment - The current user specified alignment. unsigned Alignment; /// Stack - Entries in the #pragma pack stack, consisting of saved /// alignments and optional names. stack_ty Stack; public: PragmaPackStack() : Alignment(0) {} void setAlignment(unsigned A) { Alignment = A; } unsigned getAlignment() { return Alignment; } /// push - Push the current alignment onto the stack, optionally /// using the given \arg Name for the record, if non-zero. void push(IdentifierInfo *Name) { Stack.push_back(std::make_pair(Alignment, Name)); } /// pop - Pop a record from the stack and restore the current /// alignment to the previous value. If \arg Name is non-zero then /// the first such named record is popped, otherwise the top record /// is popped. Returns true if the pop succeeded. bool pop(IdentifierInfo *Name); }; } // end anonymous namespace. bool PragmaPackStack::pop(IdentifierInfo *Name) { if (Stack.empty()) return false; // If name is empty just pop top. if (!Name) { Alignment = Stack.back().first; Stack.pop_back(); return true; } // Otherwise, find the named record. for (unsigned i = Stack.size(); i != 0; ) { --i; if (Stack[i].second == Name) { // Found it, pop up to and including this record. Alignment = Stack[i].first; Stack.erase(Stack.begin() + i, Stack.end()); return true; } } return false; } /// FreePackedContext - Deallocate and null out PackContext. void Sema::FreePackedContext() { delete static_cast<PragmaPackStack*>(PackContext); PackContext = 0; } /// getPragmaPackAlignment() - Return the current alignment as specified by /// the current #pragma pack directive, or 0 if none is currently active. unsigned Sema::getPragmaPackAlignment() const { if (PackContext) return static_cast<PragmaPackStack*>(PackContext)->getAlignment(); return 0; } void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, ExprTy *alignment, SourceLocation PragmaLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { Expr *Alignment = static_cast<Expr *>(alignment); // If specified then alignment must be a "small" power of two. unsigned AlignmentVal = 0; if (Alignment) { llvm::APSInt Val; // pack(0) is like pack(), which just works out since that is what // we use 0 for in PackAttr. if (!Alignment->isIntegerConstantExpr(Val, Context) || !(Val == 0 || Val.isPowerOf2()) || Val.getZExtValue() > 16) { Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment); Alignment->Destroy(Context); return; // Ignore } AlignmentVal = (unsigned) Val.getZExtValue(); } if (PackContext == 0) PackContext = new PragmaPackStack(); PragmaPackStack *Context = static_cast<PragmaPackStack*>(PackContext); switch (Kind) { case Action::PPK_Default: // pack([n]) Context->setAlignment(AlignmentVal); break; case Action::PPK_Show: // pack(show) // Show the current alignment, making sure to show the right value // for the default. AlignmentVal = Context->getAlignment(); // FIXME: This should come from the target. if (AlignmentVal == 0) AlignmentVal = 8; Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal; break; case Action::PPK_Push: // pack(push [, id] [, [n]) Context->push(Name); // Set the new alignment if specified. if (Alignment) Context->setAlignment(AlignmentVal); break; case Action::PPK_Pop: // pack(pop [, id] [, n]) // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack: // "#pragma pack(pop, identifier, n) is undefined" if (Alignment && Name) Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment); // Do the pop. if (!Context->pop(Name)) { // If a name was specified then failure indicates the name // wasn't found. Otherwise failure indicates the stack was // empty. Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed) << (Name ? "no record matching name" : "stack empty"); // FIXME: Warn about popping named records as MSVC does. } else { // Pop succeeded, set the new alignment if specified. if (Alignment) Context->setAlignment(AlignmentVal); } break; default: assert(0 && "Invalid #pragma pack kind."); } } void Sema::ActOnPragmaUnused(ExprTy **Exprs, unsigned NumExprs, SourceLocation PragmaLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { // Verify that all of the expressions are valid before // modifying the attributes of any referenced decl. Expr *ErrorExpr = 0; for (unsigned i = 0; i < NumExprs; ++i) { Expr *Ex = (Expr*) Exprs[i]; if (!isa<DeclRefExpr>(Ex)) { ErrorExpr = Ex; break; } Decl *d = cast<DeclRefExpr>(Ex)->getDecl();; if (!isa<VarDecl>(d) || !cast<VarDecl>(d)->hasLocalStorage()) { ErrorExpr = Ex; break; } } // Delete the expressions if we encountered any error. if (ErrorExpr) { Diag(ErrorExpr->getLocStart(), diag::warn_pragma_unused_expected_localvar); for (unsigned i = 0; i < NumExprs; ++i) ((Expr*) Exprs[i])->Destroy(Context); return; } // Otherwise, add the 'unused' attribute to each referenced declaration. for (unsigned i = 0; i < NumExprs; ++i) { DeclRefExpr *DR = (DeclRefExpr*) Exprs[i]; DR->getDecl()->addAttr(::new (Context) UnusedAttr()); DR->Destroy(Context); } } <file_sep>/test/SemaCXX/static-initializers.cpp // RUN: clang-cc -fsyntax-only -verify %s int f() { return 10; } void g() { static int a = f(); } static int b = f(); <file_sep>/test/FixIt/fixit-errors-1.c // RUN: clang-cc -fsyntax-only -pedantic -fixit %s -o - | clang-cc -pedantic -Werror -x c - /* This is a test of the various code modification hints that are provided as part of warning or extension diagnostics. All of the warnings will be fixed by -fixit, and the resulting file should compile cleanly with -Werror -pedantic. */ // FIXME: If you put a space at the end of the line, it doesn't work yet! char *s = "hi\ there"; // The following line isn't terminated, don't fix it. int i; // expected-error{{no newline at end of file}} <file_sep>/include/clang/Analysis/PathSensitive/Store.h //== Store.h - Interface for maps from Locations to Values ------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defined the types Store and StoreManager. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_STORE_H #define LLVM_CLANG_ANALYSIS_STORE_H #include "clang/Analysis/PathSensitive/SVals.h" #include "clang/Analysis/PathSensitive/MemRegion.h" #include "clang/Analysis/PathSensitive/ValueManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallVector.h" #include <iosfwd> namespace clang { typedef const void* Store; class GRState; class GRStateManager; class Stmt; class Expr; class ObjCIvarDecl; class SubRegionMap; class StoreManager { protected: ValueManager &ValMgr; /// MRMgr - Manages region objects associated with this StoreManager. MemRegionManager &MRMgr; StoreManager(ValueManager &valMgr) : ValMgr(valMgr), MRMgr(ValMgr.getRegionManager()) {} public: virtual ~StoreManager() {} /// Return the value bound to specified location in a given state. /// \param[in] state The analysis state. /// \param[in] loc The symbolic memory location. /// \param[in] T An optional type that provides a hint indicating the /// expected type of the returned value. This is used if the value is /// lazily computed. /// \return The value bound to the location \c loc. virtual SVal Retrieve(const GRState* state, Loc loc, QualType T = QualType()) = 0; /// Return a state with the specified value bound to the given location. /// \param[in] state The analysis state. /// \param[in] loc The symbolic memory location. /// \param[in] val The value to bind to location \c loc. /// \return A pointer to a GRState object that contains the same bindings as /// \c state with the addition of having the value specified by \c val bound /// to the location given for \c loc. virtual const GRState* Bind(const GRState* state, Loc loc, SVal val) = 0; virtual Store Remove(Store St, Loc L) = 0; /// BindCompoundLiteral - Return the store that has the bindings currently /// in 'store' plus the bindings for the CompoundLiteral. 'R' is the region /// for the compound literal and 'BegInit' and 'EndInit' represent an /// array of initializer values. virtual const GRState* BindCompoundLiteral(const GRState* St, const CompoundLiteralExpr* CL, SVal V) = 0; /// getInitialStore - Returns the initial "empty" store representing the /// value bindings upon entry to an analyzed function. virtual Store getInitialStore() = 0; /// getRegionManager - Returns the internal RegionManager object that is /// used to query and manipulate MemRegion objects. MemRegionManager& getRegionManager() { return MRMgr; } /// getSubRegionMap - Returns an opaque map object that clients can query /// to get the subregions of a given MemRegion object. It is the // caller's responsibility to 'delete' the returned map. virtual SubRegionMap* getSubRegionMap(const GRState *state) = 0; virtual SVal getLValueVar(const GRState* St, const VarDecl* VD) = 0; virtual SVal getLValueString(const GRState* St, const StringLiteral* S) = 0; virtual SVal getLValueCompoundLiteral(const GRState* St, const CompoundLiteralExpr* CL) = 0; virtual SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base) = 0; virtual SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D) = 0; virtual SVal getLValueElement(const GRState* St, SVal Base, SVal Offset) = 0; virtual SVal getSizeInElements(const GRState* St, const MemRegion* R) { return UnknownVal(); } /// ArrayToPointer - Used by GRExprEngine::VistCast to handle implicit /// conversions between arrays and pointers. virtual SVal ArrayToPointer(Loc Array) = 0; class CastResult { const GRState* State; const MemRegion* R; public: const GRState* getState() const { return State; } const MemRegion* getRegion() const { return R; } CastResult(const GRState* s, const MemRegion* r = 0) : State(s), R(r) {} }; /// CastRegion - Used by GRExprEngine::VisitCast to handle casts from /// a MemRegion* to a specific location type. 'R' is the region being /// casted and 'CastToTy' the result type of the cast. virtual CastResult CastRegion(const GRState* state, const MemRegion* R, QualType CastToTy) = 0; /// EvalBinOp - Perform pointer arithmetic. virtual SVal EvalBinOp(BinaryOperator::Opcode Op, Loc L, NonLoc R) { return UnknownVal(); } /// getSelfRegion - Returns the region for the 'self' (Objective-C) or /// 'this' object (C++). When used when analyzing a normal function this /// method returns NULL. virtual const MemRegion* getSelfRegion(Store store) = 0; virtual Store RemoveDeadBindings(const GRState* state, Stmt* Loc, SymbolReaper& SymReaper, llvm::SmallVectorImpl<const MemRegion*>& RegionRoots) = 0; virtual const GRState* BindDecl(const GRState* St, const VarDecl* VD, SVal InitVal) = 0; virtual const GRState* BindDeclWithNoInit(const GRState* St, const VarDecl* VD) = 0; virtual const GRState* setExtent(const GRState* St, const MemRegion* R, SVal Extent) { return St; } virtual void print(Store store, std::ostream& Out, const char* nl, const char *sep) = 0; class BindingsHandler { public: virtual ~BindingsHandler(); virtual bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R, SVal val) = 0; }; /// iterBindings - Iterate over the bindings in the Store. virtual void iterBindings(Store store, BindingsHandler& f) = 0; }; /// SubRegionMap - An abstract interface that represents a queryable map /// between MemRegion objects and their subregions. class SubRegionMap { public: virtual ~SubRegionMap() {} class Visitor { public: virtual ~Visitor() {}; virtual bool Visit(const MemRegion* Parent, const MemRegion* SubRegion) = 0; }; virtual bool iterSubRegions(const MemRegion* R, Visitor& V) const = 0; }; StoreManager* CreateBasicStoreManager(GRStateManager& StMgr); StoreManager* CreateRegionStoreManager(GRStateManager& StMgr); } // end clang namespace #endif <file_sep>/tools/clang-cc/Makefile ##===- tools/clang-cc/Makefile -----------------------------*- Makefile -*-===## # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # ##===----------------------------------------------------------------------===## LEVEL = ../../../.. TOOLNAME = clang-cc CPPFLAGS += -I$(PROJ_SRC_DIR)/../../include -I$(PROJ_OBJ_DIR)/../../include CXXFLAGS = -fno-rtti # Clang has no plugins, optimize startup time. TOOL_NO_EXPORTS = 1 # Include this here so we can get the configuration of the targets # that have been configured for construction. We have to do this # early so we can set up LINK_COMPONENTS before including Makefile.rules include $(LEVEL)/Makefile.config LINK_COMPONENTS := $(TARGETS_TO_BUILD) bitreader bitwriter codegen ipo selectiondag USEDLIBS = clangCodeGen.a clangAnalysis.a clangRewrite.a clangSema.a \ clangFrontend.a clangAST.a clangParse.a clangLex.a \ clangBasic.a # clang-cc lives in a special location; we can get away with this # because nothing else gets installed from here. PROJ_bindir := $(DESTDIR)$(PROJ_prefix)/libexec include $(LLVM_SRC_ROOT)/Makefile.rules <file_sep>/test/SemaTemplate/instantiation-default-1.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T, typename U = const T> struct Def1; template<> struct Def1<int> { void foo(); }; template<> struct Def1<const int> { // expected-note{{previous definition is here}} void bar(); }; template<> struct Def1<int&> { void wibble(); }; void test_Def1(Def1<int, const int> *d1, Def1<const int, const int> *d2, Def1<int&, int&> *d3) { d1->foo(); d2->bar(); d3->wibble(); } template<typename T, // FIXME: bad error message below, needs better location info typename T2 = const T*> // expected-error{{'T2' declared as a pointer to a reference}} struct Def2; template<> struct Def2<int> { void foo(); }; void test_Def2(Def2<int, int const*> *d2) { d2->foo(); } typedef int& int_ref_t; Def2<int_ref_t> *d2; // expected-note{{in instantiation of default argument for 'Def2<int &>' required here}} template<> struct Def1<const int, const int> { }; // expected-error{{redefinition of 'Def1'}} template<typename T, typename T2 = T&> struct Def3; template<> struct Def3<int> { void foo(); }; template<> struct Def3<int&> { void bar(); }; void test_Def3(Def3<int, int&> *d3a, Def3<int&, int&> *d3b) { d3a->foo(); d3b->bar(); } template<typename T, typename T2 = T[]> struct Def4; template<> struct Def4<int> { void foo(); }; void test_Def4(Def4<int, int[]> *d4a) { d4a->foo(); } template<typename T, typename T2 = T const[12]> struct Def5; template<> struct Def5<int> { void foo(); }; template<> struct Def5<int, int const[13]> { void bar(); }; void test_Def5(Def5<int, const int[12]> *d5a, Def5<int, const int[13]> *d5b) { d5a->foo(); d5b->bar(); } template<typename R, typename Arg1, typename Arg2 = Arg1, typename FuncType = R (*)(Arg1, Arg2)> struct Def6; template<> struct Def6<int, float> { void foo(); }; template<> struct Def6<bool, int[5], float(double, double)> { void bar(); }; bool test_Def6(Def6<int, float, float> *d6a, Def6<int, float, float, int (*)(float, float)> *d6b, Def6<bool, int[5], float(double, double), bool(*)(int*, float(*)(double, double))> *d6c) { d6a->foo(); d6b->foo(); d6c->bar(); return d6a == d6b; } <file_sep>/test/Driver/parsing.c // RUN: clang -ccc-print-options input -Yunknown -m32 -arch ppc -djoined -A separate -Ajoined -Wp,one,two -Xarch_joined AndSeparate -sectalign 1 2 3 2> %t && // RUN: grep 'Option 0 - Name: "<input>", Values: {"input"}' %t && // RUN: grep 'Option 1 - Name: "<unknown>", Values: {"-Yunknown"}' %t && // RUN: grep 'Option 2 - Name: "-m32", Values: {}' %t && // RUN: grep 'Option 3 - Name: "-arch", Values: {"ppc"}' %t && // RUN: grep 'Option 4 - Name: "-d", Values: {"joined"}' %t && // RUN: grep 'Option 5 - Name: "-A", Values: {"separate"}' %t && // RUN: grep 'Option 6 - Name: "-A", Values: {"joined"}' %t && // RUN: grep 'Option 7 - Name: "-Wp,", Values: {"one", "two"}' %t && // RUN: grep 'Option 8 - Name: "-Xarch_", Values: {"joined", "AndSeparate"}' %t && // RUN: grep 'Option 9 - Name: "-sectalign", Values: {"1", "2", "3"}' %t && // RUN: not clang -V 2> %t && // RUN: grep "error: argument to '-V' is missing (expected 1 value)" %t && // RUN: not clang -sectalign 1 2 2> %t && // RUN: grep "error: argument to '-sectalign' is missing (expected 3 values)" %t && // Verify that search continues after find the first option. // RUN: clang -ccc-print-options -Wally 2> %t && // RUN: grep 'Option 0 - Name: "-W", Values: {"ally"}' %t && // RUN: true <file_sep>/test/CodeGen/rdr-6098585-default-after-caserange.c // RUN: clang-cc -triple i386-unknown-unknown --emit-llvm-bc -o - %s | opt -std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32" %t | count 1 && // RUN: grep "ret i32 10" %t | count 1 // Ensure that default after a case range is not ignored. static int f1(unsigned x) { switch(x) { case 10 ... 0xFFFFFFFF: return 0; default: return 10; } } int g() { return f1(2); } <file_sep>/www/OpenProjects.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Clang - Get Involved</title> <link type="text/css" rel="stylesheet" href="menu.css" /> <link type="text/css" rel="stylesheet" href="content.css" /> </head> <body> <!--#include virtual="menu.html.incl"--> <div id="content"> <h1>Open Clang Projects</h1> <p>Here are a few tasks that are available for newcomers to work on, depending on what your interests are. This list is provided to generate ideas, it is not intended to be comprehensive. Please ask on cfe-dev for more specifics or to verify that one of these isn't already completed. :)</p> <ul> <li><b>Compile your favorite C/ObjC project with Clang</b>: Clang's type-checking and code generation is very close to complete (but not bug free!) for C and Objective-C. We appreciate all reports of code that is rejected or miscompiled by the front-end. If you notice invalid code that is not rejected, or poor diagnostics when code is rejected, that is also very important to us. For make-based projects, the <a href="get_started.html#ccc"><code>ccc</code></a> driver works as a drop-in replacement for GCC.</li> <li><b>Overflow detection</b>: an interesting project would be to add a -ftrapv compilation mode that causes -emit-llvm to generate overflow tests for all signed integer arithmetic operators, and call abort if they overflow. Overflow is undefined in C and hard for people to reason about. LLVM IR also has intrinsics for generating arithmetic with overflow checks directly.</li> <li><b>Undefined behavior checking</b>: similar to adding -ftrapv, codegen could insert runtime checks for all sorts of different undefined behaviors, from reading uninitialized variables, buffer overflows, and many other things. This checking would be expensive, but the optimizers could eliminate many of the checks in some cases, and it would be very interesting to test code in this mode for certain crowds of people. Because the inserted code is coming from clang, the "abort" message could be very detailed about exactly what went wrong.</li> <li><b>Improve target support</b>: The current target interfaces are heavily stubbed out and need to be implemented fully. See the FIXME's in TargetInfo. Additionally, the actual target implementations (instances of TargetInfoImpl) also need to be completed.</li> <li><b>Implement an tool to generate code documentation</b>: Clang's library-based design allows it to be used by a variety of tools that reason about source code. One great application of Clang would be to build an auto-documentation system like doxygen that generates code documentation from source code. The advantage of using Clang for such a tool is that the tool would use the same preprocessor/parser/ASTs as the compiler itself, giving it a very rich understanding of the code.</li> <li><b>Use clang libraries to implement better versions of existing tools</b>: Clang is built as a set of libraries, which means that it is possible to implement capabilities similar to other source language tools, improving them in various ways. Two examples are <a href="http://distcc.samba.org/">distcc</a> and the <a href="http://delta.tigris.org/">delta testcase reduction tool</a>. The former can be improved to scale better and be more efficient. The later could also be faster and more efficient at reducing C-family programs if built on the clang preprocessor.</li> <li><b>Use clang libraries to extend Ragel with a JIT</b>: <a href="http://research.cs.queensu.ca/~thurston/ragel/">Ragel</a> is a state machine compiler that lets you embed C code into state machines and generate C code. It would be relatively easy to turn this into a JIT compiler using LLVM.</li> <li><b>Self-testing using clang</b>: There are several neat ways to improve the quality of clang by self-testing. Some examples: <ul> <li>Improve the reliability of AST printing and serialization by ensuring that the AST produced by clang on an input doesn't change when it is reparsed or unserialized. <li>Improve parser reliability and error generation by automatically or randomly changing the input checking that clang doesn't crash and that it doesn't generate excessive errors for small input changes. Manipulating the input at both the text and token levels is likely to produce interesting test cases. </ul> </li> <li><b>Continue work on C++ support</b>: Implementing all of C++ is a very big job, but there are lots of little pieces that can be picked off and implemented. Here are some small- to mid-sized C++ implementation projects: <ul> <li>Using declarations: These are completely unsupported at the moment.</li> <li>Type-checking for the conditional operator (? :): this currently follows C semantics, not C++ semantics.</li> <li>Type-checking for explicit conversions: currently follows C semantics, not C++ semantics.</li> <li>Type-checking for copy assignment: Clang parses overloaded copy-assignment operators, but they aren't used as part of assignment syntax ("a = b").</li> <li>Qualified member references: C++ supports qualified member references such as <code>x-&gt;Base::foo</code>, but Clang has no parsing or semantic analysis for them.</li> <li>Virtual functions: Clang parses <code>virtual</code> and attaches it to the AST. However, it does not determine whether a given function overrides a virtual function in a base class.</li> <li>Implicit definitions of special member functions: Clang implicitly declares the various special member functions (default constructor, copy constructor, copy assignment operator, destructor) when necessary, but is not yet able to provide definitions for these functions.</li> <li>Parsing and AST representations of friend classes and functions</li> <li>AST representation for implicit C++ conversions: implicit conversions that involve non-trivial operations (e.g., invoking a user-defined conversion function, performing a base-to-derived or derived-to-base conversion) need explicit representation in Clang's AST.</li> <li>Improved diagnostics for overload resolution failures: after an overload resolution failure, we currently print out the overload resolution candidates. We should also print out the reason that each candidate failed, e.g., "too few arguments", "too many arguments", "cannot initialize parameter with an lvalue of type 'foo'", etc.</li> </ul> Also, see the <a href="cxx_status.html">C++ status report page</a> to find out what is missing and what is already at least partially supported.</li> </ul> <p>If you hit a bug with clang, it is very useful for us if you reduce the code that demonstrates the problem down to something small. There are many ways to do this; ask on cfe-dev for advice.</p> </div> </body> </html> <file_sep>/test/CodeGen/builtinshufflevector.c // RUN: clang-cc -emit-llvm < %s | grep 'shufflevector' | count 1 typedef int v4si __attribute__ ((vector_size (16))); v4si a(v4si x, v4si y) {return __builtin_shufflevector(x, y, 3, 2, 5, 7);} <file_sep>/test/SemaCXX/conversion-function.cpp // RUN: clang-cc -fsyntax-only -verify %s class X { public: operator bool(); operator int() const; bool f() { return operator bool(); } float g() { return operator float(); // expected-error{{no matching function for call to 'operator float'}} } }; operator int(); // expected-error{{conversion function must be a non-static member function}} operator int; // expected-error{{'operator int' cannot be the name of a variable or data member}} typedef int func_type(int); typedef int array_type[10]; class Y { public: void operator bool(int, ...) const; // expected-error{{conversion function cannot have a return type}} \ // expected-error{{conversion function cannot have any parameters}} \ // expected-error{{conversion function cannot be variadic}} operator func_type(); // expected-error{{conversion function cannot convert to a function type}} operator array_type(); // expected-error{{conversion function cannot convert to an array type}} }; typedef int INT; typedef INT* INT_PTR; class Z { operator int(); // expected-note {{previous declaration is here}} operator int**(); // expected-note {{previous declaration is here}} operator INT(); // expected-error{{conversion function cannot be redeclared}} operator INT_PTR*(); // expected-error{{conversion function cannot be redeclared}} }; class A { }; class B : public A { public: operator A&() const; // expected-warning{{conversion function converting 'class B' to its base class 'class A' will never be used}} operator const void() const; // expected-warning{{conversion function converting 'class B' to 'void const' will never be used}} operator const B(); // expected-warning{{conversion function converting 'class B' to itself will never be used}} }; <file_sep>/include/clang/Analysis/Visitors/CFGRecStmtVisitor.h //==- CFGRecStmtVisitor - Recursive visitor of CFG statements ---*- C++ --*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the template class CFGRecStmtVisitor, which extends // CFGStmtVisitor by implementing a default recursive visit of all statements. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_CFG_REC_STMT_VISITOR_H #define LLVM_CLANG_ANALYSIS_CFG_REC_STMT_VISITOR_H #include "clang/Analysis/Visitors/CFGStmtVisitor.h" namespace clang { template <typename ImplClass> class CFGRecStmtVisitor : public CFGStmtVisitor<ImplClass,void> { public: void VisitStmt(Stmt* S) { static_cast< ImplClass* >(this)->VisitChildren(S); } // Defining operator() allows the visitor to be used as a C++ style functor. void operator()(Stmt* S) { static_cast<ImplClass*>(this)->BlockStmt_Visit(S);} }; } // end namespace clang #endif <file_sep>/test/Coverage/html-diagnostics.c // RUN: rm -rf %t && // RUN: clang-cc --html-diags=%t -checker-simple %s void f0(int x) { int *p = &x; if (x > 10) { if (x == 22) p = 0; } *p = 10; } <file_sep>/test/SemaTemplate/instantiate-expr-2.cpp // RUN: clang-cc -fsyntax-only %s typedef char one_byte; typedef char (&two_bytes)[2]; typedef char (&four_bytes)[4]; typedef char (&eight_bytes)[8]; template<int N> struct A { }; namespace N1 { struct X { }; } namespace N2 { struct Y { }; two_bytes operator+(Y, Y); } namespace N3 { struct Z { }; eight_bytes operator+(Z, Z); } namespace N4 { one_byte operator+(N1::X, N2::Y); template<typename T, typename U> struct BinOpOverload { typedef A<sizeof(T() + U())> type; }; } namespace N1 { four_bytes operator+(X, X); } namespace N3 { eight_bytes operator+(Z, Z); // redeclaration } void test_bin_op_overload(A<1> *a1, A<2> *a2, A<4> *a4, A<8> *a8) { typedef N4::BinOpOverload<N1::X, N2::Y>::type XY; XY *xy = a1; typedef N4::BinOpOverload<N1::X, N1::X>::type XX; XX *xx = a4; typedef N4::BinOpOverload<N2::Y, N2::Y>::type YY; YY *yy = a2; typedef N4::BinOpOverload<N3::Z, N3::Z>::type ZZ; ZZ *zz = a8; } namespace N3 { eight_bytes operator-(::N3::Z); } namespace N4 { template<typename T> struct UnaryOpOverload { typedef A<sizeof(-T())> type; }; } void test_unary_op_overload(A<8> *a8) { typedef N4::UnaryOpOverload<N3::Z>::type UZ; UZ *uz = a8; } /* namespace N5 { template<int I> struct Lookup { enum { val = I, more = val + 1 }; }; template<bool B> struct Cond { enum Junk { is = B ? Lookup<B>::more : Lookup<Lookup<B+1>::more>::val }; }; enum { resultT = Cond<true>::is, resultF = Cond<false>::is }; } */ namespace N6 { // non-typedependent template<int I> struct Lookup {}; template<bool B, typename T, typename E> struct Cond { typedef Lookup<B ? sizeof(T) : sizeof(E)> True; typedef Lookup<!B ? sizeof(T) : sizeof(E)> False; }; typedef Cond<true, int, char>::True True; typedef Cond<true, int, char>::False False; // check that we have the right types Lookup<1> const &L1(False()); Lookup<sizeof(int)> const &L2(True()); } namespace N7 { // type dependent template<int I> struct Lookup {}; template<bool B, typename T, typename E> struct Cond { T foo() { return B ? T() : E(); } typedef Lookup<sizeof(B ? T() : E())> Type; }; //Cond<true, int*, double> C; // Errors //int V(C.foo()); // Errors //typedef Cond<true, int*, double>::Type Type; // Errors + CRASHES! typedef Cond<true, int, double>::Type Type; } <file_sep>/lib/CodeGen/CGCXX.cpp //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This contains code dealing with C++ code generation. // //===----------------------------------------------------------------------===// // We might split this into multiple files if it gets too unwieldy #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "Mangle.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "llvm/ADT/StringExtras.h" using namespace clang; using namespace CodeGen; void CodeGenFunction::GenerateStaticCXXBlockVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV) { // FIXME: This should use __cxa_guard_{acquire,release}? assert(!getContext().getLangOptions().ThreadsafeStatics && "thread safe statics are currently not supported!"); llvm::SmallString<256> GuardVName; llvm::raw_svector_ostream GuardVOut(GuardVName); mangleGuardVariable(&D, getContext(), GuardVOut); // Create the guard variable. llvm::GlobalValue *GuardV = new llvm::GlobalVariable(llvm::Type::Int64Ty, false, GV->getLinkage(), llvm::Constant::getNullValue(llvm::Type::Int64Ty), GuardVName.c_str(), &CGM.getModule()); // Load the first byte of the guard variable. const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::Int8Ty, 0); llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy), "tmp"); // Compare it against 0. llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::Int8Ty); llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool"); llvm::BasicBlock *InitBlock = createBasicBlock("init"); llvm::BasicBlock *EndBlock = createBasicBlock("init.end"); // If the guard variable is 0, jump to the initializer code. Builder.CreateCondBr(ICmp, InitBlock, EndBlock); EmitBlock(InitBlock); const Expr *Init = D.getInit(); if (!hasAggregateLLVMType(Init->getType())) { llvm::Value *V = EmitScalarExpr(Init); Builder.CreateStore(V, GV, D.getType().isVolatileQualified()); } else if (Init->getType()->isAnyComplexType()) { EmitComplexExprIntoAddr(Init, GV, D.getType().isVolatileQualified()); } else { EmitAggExpr(Init, GV, D.getType().isVolatileQualified()); } Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::Int8Ty, 1), Builder.CreateBitCast(GuardV, PtrTy)); EmitBlock(EndBlock); } RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) { const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()); const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); assert(MD->isInstance() && "Trying to emit a member call expr on a static method!"); const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); const llvm::Type *Ty = CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), FPT->isVariadic()); llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, Ty); llvm::Value *BaseValue = 0; // There's a deref operator node added in Sema::BuildCallToMemberFunction // that's giving the wrong type for -> call exprs so we just ignore them // for now. if (ME->isArrow()) return EmitUnsupportedRValue(CE, "C++ member call expr"); else { LValue BaseLV = EmitLValue(ME->getBase()); BaseValue = BaseLV.getAddress(); } CallArgList Args; // Push the 'this' pointer. Args.push_back(std::make_pair(RValue::get(BaseValue), MD->getThisType(getContext()))); EmitCallArgs(Args, FPT, CE->arg_begin(), CE->arg_end()); QualType ResultType = MD->getType()->getAsFunctionType()->getResultType(); return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, MD); } llvm::Value *CodeGenFunction::LoadCXXThis() { assert(isa<CXXMethodDecl>(CurFuncDecl) && "Must be in a C++ member function decl to load 'this'"); assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() && "Must be in a C++ member function decl to load 'this'"); // FIXME: What if we're inside a block? return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this"); } const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D, CXXCtorType Type) { llvm::SmallString<256> Name; llvm::raw_svector_ostream Out(Name); mangleCXXCtor(D, Type, Context, Out); Name += '\0'; return UniqueMangledName(Name.begin(), Name.end()); } void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type) { const llvm::FunctionType *Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false); const char *Name = getMangledCXXCtorName(D, Type); llvm::Function *Fn = cast<llvm::Function>(GetOrCreateLLVMFunction(Name, Ty, D)); CodeGenFunction(*this).GenerateCode(D, Fn); SetFunctionDefinitionAttributes(D, Fn); SetLLVMFunctionAttributesForDefinition(D, Fn); } static bool canGenerateCXXConstructor(const CXXConstructorDecl *D, ASTContext &Context) { const CXXRecordDecl *RD = D->getParent(); // The class has base classes - we don't support that right now. if (RD->getNumBases() > 0) return false; for (CXXRecordDecl::field_iterator I = RD->field_begin(Context), E = RD->field_end(Context); I != E; ++I) { // We don't support ctors for fields that aren't POD. if (!I->getType()->isPODType()) return false; } return true; } void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) { if (!canGenerateCXXConstructor(D, getContext())) { ErrorUnsupported(D, "C++ constructor", true); return; } EmitCXXConstructor(D, Ctor_Complete); EmitCXXConstructor(D, Ctor_Base); } <file_sep>/lib/CodeGen/CGExprConstant.cpp //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This contains code to emit Constant Expr nodes as LLVM code. // //===----------------------------------------------------------------------===// #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "CGObjCRuntime.h" #include "clang/AST/APValue.h" #include "clang/AST/ASTContext.h" #include "clang/AST/StmtVisitor.h" #include "llvm/Constants.h" #include "llvm/Function.h" #include "llvm/GlobalVariable.h" #include "llvm/Support/Compiler.h" #include "llvm/Target/TargetData.h" using namespace clang; using namespace CodeGen; namespace { class VISIBILITY_HIDDEN ConstExprEmitter : public StmtVisitor<ConstExprEmitter, llvm::Constant*> { CodeGenModule &CGM; CodeGenFunction *CGF; public: ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf) : CGM(cgm), CGF(cgf) { } //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// llvm::Constant *VisitStmt(Stmt *S) { return 0; } llvm::Constant *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { return Visit(E->getInitializer()); } llvm::Constant *VisitCastExpr(CastExpr* E) { // GCC cast to union extension if (E->getType()->isUnionType()) { const llvm::Type *Ty = ConvertType(E->getType()); Expr *SubExpr = E->getSubExpr(); return EmitUnion(CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF), Ty); } if (CGM.getContext().getCanonicalType(E->getSubExpr()->getType()) == CGM.getContext().getCanonicalType(E->getType())) { return Visit(E->getSubExpr()); } return 0; } llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { return Visit(DAE->getExpr()); } llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) { std::vector<llvm::Constant*> Elts; const llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(ILE->getType())); unsigned NumInitElements = ILE->getNumInits(); // FIXME: Check for wide strings // FIXME: Check for NumInitElements exactly equal to 1?? if (NumInitElements > 0 && (isa<StringLiteral>(ILE->getInit(0)) || isa<ObjCEncodeExpr>(ILE->getInit(0))) && ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType()) return Visit(ILE->getInit(0)); const llvm::Type *ElemTy = AType->getElementType(); unsigned NumElements = AType->getNumElements(); // Initialising an array requires us to automatically // initialise any elements that have not been initialised explicitly unsigned NumInitableElts = std::min(NumInitElements, NumElements); // Copy initializer elements. unsigned i = 0; bool RewriteType = false; for (; i < NumInitableElts; ++i) { Expr *Init = ILE->getInit(i); llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF); if (!C) return 0; RewriteType |= (C->getType() != ElemTy); Elts.push_back(C); } // Initialize remaining array elements. // FIXME: This doesn't handle member pointers correctly! for (; i < NumElements; ++i) Elts.push_back(llvm::Constant::getNullValue(ElemTy)); if (RewriteType) { // FIXME: Try to avoid packing the array std::vector<const llvm::Type*> Types; for (unsigned i = 0; i < Elts.size(); ++i) Types.push_back(Elts[i]->getType()); const llvm::StructType *SType = llvm::StructType::get(Types, true); return llvm::ConstantStruct::get(SType, Elts); } return llvm::ConstantArray::get(AType, Elts); } void InsertBitfieldIntoStruct(std::vector<llvm::Constant*>& Elts, FieldDecl* Field, Expr* E) { // Calculate the value to insert llvm::Constant *C = CGM.EmitConstantExpr(E, Field->getType(), CGF); if (!C) return; llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C); if (!CI) { CGM.ErrorUnsupported(E, "bitfield initialization"); return; } llvm::APInt V = CI->getValue(); // Calculate information about the relevant field const llvm::Type* Ty = CI->getType(); const llvm::TargetData &TD = CGM.getTypes().getTargetData(); unsigned size = TD.getTypePaddedSizeInBits(Ty); unsigned fieldOffset = CGM.getTypes().getLLVMFieldNo(Field) * size; CodeGenTypes::BitFieldInfo bitFieldInfo = CGM.getTypes().getBitFieldInfo(Field); fieldOffset += bitFieldInfo.Begin; // Find where to start the insertion // FIXME: This is O(n^2) in the number of bit-fields! // FIXME: This won't work if the struct isn't completely packed! unsigned offset = 0, i = 0; while (offset < (fieldOffset & -8)) offset += TD.getTypePaddedSizeInBits(Elts[i++]->getType()); // Advance over 0 sized elements (must terminate in bounds since // the bitfield must have a size). while (TD.getTypePaddedSizeInBits(Elts[i]->getType()) == 0) ++i; // Promote the size of V if necessary // FIXME: This should never occur, but currently it can because // initializer constants are cast to bool, and because clang is // not enforcing bitfield width limits. if (bitFieldInfo.Size > V.getBitWidth()) V.zext(bitFieldInfo.Size); // Insert the bits into the struct // FIXME: This algorthm is only correct on X86! // FIXME: THis algorthm assumes bit-fields only have byte-size elements! unsigned bitsToInsert = bitFieldInfo.Size; unsigned curBits = std::min(8 - (fieldOffset & 7), bitsToInsert); unsigned byte = V.getLoBits(curBits).getZExtValue() << (fieldOffset & 7); do { llvm::Constant* byteC = llvm::ConstantInt::get(llvm::Type::Int8Ty, byte); Elts[i] = llvm::ConstantExpr::getOr(Elts[i], byteC); ++i; V = V.lshr(curBits); bitsToInsert -= curBits; if (!bitsToInsert) break; curBits = bitsToInsert > 8 ? 8 : bitsToInsert; byte = V.getLoBits(curBits).getZExtValue(); } while (true); } llvm::Constant *EmitStructInitialization(InitListExpr *ILE) { const llvm::StructType *SType = cast<llvm::StructType>(ConvertType(ILE->getType())); RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl(); std::vector<llvm::Constant*> Elts; // Initialize the whole structure to zero. // FIXME: This doesn't handle member pointers correctly! for (unsigned i = 0; i < SType->getNumElements(); ++i) { const llvm::Type *FieldTy = SType->getElementType(i); Elts.push_back(llvm::Constant::getNullValue(FieldTy)); } // Copy initializer elements. Skip padding fields. unsigned EltNo = 0; // Element no in ILE int FieldNo = 0; // Field no in RecordDecl bool RewriteType = false; for (RecordDecl::field_iterator Field = RD->field_begin(CGM.getContext()), FieldEnd = RD->field_end(CGM.getContext()); EltNo < ILE->getNumInits() && Field != FieldEnd; ++Field) { FieldNo++; if (!Field->getIdentifier()) continue; if (Field->isBitField()) { InsertBitfieldIntoStruct(Elts, *Field, ILE->getInit(EltNo)); } else { unsigned FieldNo = CGM.getTypes().getLLVMFieldNo(*Field); llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(EltNo), Field->getType(), CGF); if (!C) return 0; RewriteType |= (C->getType() != Elts[FieldNo]->getType()); Elts[FieldNo] = C; } EltNo++; } if (RewriteType) { // FIXME: Make this work for non-packed structs assert(SType->isPacked() && "Cannot recreate unpacked structs"); std::vector<const llvm::Type*> Types; for (unsigned i = 0; i < Elts.size(); ++i) Types.push_back(Elts[i]->getType()); SType = llvm::StructType::get(Types, true); } return llvm::ConstantStruct::get(SType, Elts); } llvm::Constant *EmitUnion(llvm::Constant *C, const llvm::Type *Ty) { if (!C) return 0; // Build a struct with the union sub-element as the first member, // and padded to the appropriate size std::vector<llvm::Constant*> Elts; std::vector<const llvm::Type*> Types; Elts.push_back(C); Types.push_back(C->getType()); unsigned CurSize = CGM.getTargetData().getTypePaddedSize(C->getType()); unsigned TotalSize = CGM.getTargetData().getTypePaddedSize(Ty); while (CurSize < TotalSize) { Elts.push_back(llvm::Constant::getNullValue(llvm::Type::Int8Ty)); Types.push_back(llvm::Type::Int8Ty); CurSize++; } // This always generates a packed struct // FIXME: Try to generate an unpacked struct when we can llvm::StructType* STy = llvm::StructType::get(Types, true); return llvm::ConstantStruct::get(STy, Elts); } llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) { const llvm::Type *Ty = ConvertType(ILE->getType()); FieldDecl* curField = ILE->getInitializedFieldInUnion(); if (!curField) { // There's no field to initialize, so value-initialize the union. #ifndef NDEBUG // Make sure that it's really an empty and not a failure of // semantic analysis. RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl(); for (RecordDecl::field_iterator Field = RD->field_begin(CGM.getContext()), FieldEnd = RD->field_end(CGM.getContext()); Field != FieldEnd; ++Field) assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); #endif return llvm::Constant::getNullValue(Ty); } if (curField->isBitField()) { // Create a dummy struct for bit-field insertion unsigned NumElts = CGM.getTargetData().getTypePaddedSize(Ty) / 8; llvm::Constant* NV = llvm::Constant::getNullValue(llvm::Type::Int8Ty); std::vector<llvm::Constant*> Elts(NumElts, NV); InsertBitfieldIntoStruct(Elts, curField, ILE->getInit(0)); const llvm::ArrayType *RetTy = llvm::ArrayType::get(NV->getType(), NumElts); return llvm::ConstantArray::get(RetTy, Elts); } llvm::Constant *InitElem; if (ILE->getNumInits() > 0) { Expr *Init = ILE->getInit(0); InitElem = CGM.EmitConstantExpr(Init, Init->getType(), CGF); } else { InitElem = CGM.EmitNullConstant(curField->getType()); } return EmitUnion(InitElem, Ty); } llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) { const llvm::VectorType *VType = cast<llvm::VectorType>(ConvertType(ILE->getType())); const llvm::Type *ElemTy = VType->getElementType(); std::vector<llvm::Constant*> Elts; unsigned NumElements = VType->getNumElements(); unsigned NumInitElements = ILE->getNumInits(); unsigned NumInitableElts = std::min(NumInitElements, NumElements); // Copy initializer elements. unsigned i = 0; for (; i < NumInitableElts; ++i) { Expr *Init = ILE->getInit(i); llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF); if (!C) return 0; Elts.push_back(C); } for (; i < NumElements; ++i) Elts.push_back(llvm::Constant::getNullValue(ElemTy)); return llvm::ConstantVector::get(VType, Elts); } llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) { return CGM.EmitNullConstant(E->getType()); } llvm::Constant *VisitInitListExpr(InitListExpr *ILE) { if (ILE->getType()->isScalarType()) { // We have a scalar in braces. Just use the first element. if (ILE->getNumInits() > 0) { Expr *Init = ILE->getInit(0); return CGM.EmitConstantExpr(Init, Init->getType(), CGF); } return CGM.EmitNullConstant(ILE->getType()); } if (ILE->getType()->isArrayType()) return EmitArrayInitialization(ILE); if (ILE->getType()->isStructureType()) return EmitStructInitialization(ILE); if (ILE->getType()->isUnionType()) return EmitUnionInitialization(ILE); if (ILE->getType()->isVectorType()) return EmitVectorInitialization(ILE); assert(0 && "Unable to handle InitListExpr"); // Get rid of control reaches end of void function warning. // Not reached. return 0; } llvm::Constant *VisitStringLiteral(StringLiteral *E) { assert(!E->getType()->isPointerType() && "Strings are always arrays"); // This must be a string initializing an array in a static initializer. // Don't emit it as the address of the string, emit the string data itself // as an inline array. return llvm::ConstantArray::get(CGM.GetStringForStringLiteral(E), false); } llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) { // This must be an @encode initializing an array in a static initializer. // Don't emit it as the address of the string, emit the string data itself // as an inline array. std::string Str; CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str); const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType()); // Resize the string to the right size, adding zeros at the end, or // truncating as needed. Str.resize(CAT->getSize().getZExtValue(), '\0'); return llvm::ConstantArray::get(Str, false); } llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) { return Visit(E->getSubExpr()); } // Utility methods const llvm::Type *ConvertType(QualType T) { return CGM.getTypes().ConvertType(T); } public: llvm::Constant *EmitLValue(Expr *E) { switch (E->getStmtClass()) { default: break; case Expr::CompoundLiteralExprClass: { // Note that due to the nature of compound literals, this is guaranteed // to be the only use of the variable, so we just generate it here. CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); llvm::Constant* C = Visit(CLE->getInitializer()); // FIXME: "Leaked" on failure. if (C) C = new llvm::GlobalVariable(C->getType(), E->getType().isConstQualified(), llvm::GlobalValue::InternalLinkage, C, ".compoundliteral", &CGM.getModule()); return C; } case Expr::DeclRefExprClass: case Expr::QualifiedDeclRefExprClass: { NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl(); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl)) return CGM.GetAddrOfFunction(FD); if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) { // We can never refer to a variable with local storage. if (!VD->hasLocalStorage()) { if (VD->isFileVarDecl() || VD->hasExternalStorage()) return CGM.GetAddrOfGlobalVar(VD); else if (VD->isBlockVarDecl()) { assert(CGF && "Can't access static local vars without CGF"); return CGF->GetAddrOfStaticLocalVar(VD); } } } break; } case Expr::StringLiteralClass: return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E)); case Expr::ObjCEncodeExprClass: return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E)); case Expr::ObjCStringLiteralClass: { ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E); llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(SL); return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType())); } case Expr::PredefinedExprClass: { // __func__/__FUNCTION__ -> "". __PRETTY_FUNCTION__ -> "top level". std::string Str; if (cast<PredefinedExpr>(E)->getIdentType() == PredefinedExpr::PrettyFunction) Str = "top level"; return CGM.GetAddrOfConstantCString(Str, ".tmp"); } case Expr::AddrLabelExprClass: { assert(CGF && "Invalid address of label expression outside function."); unsigned id = CGF->GetIDForAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel()); llvm::Constant *C = llvm::ConstantInt::get(llvm::Type::Int32Ty, id); return llvm::ConstantExpr::getIntToPtr(C, ConvertType(E->getType())); } case Expr::CallExprClass: { CallExpr* CE = cast<CallExpr>(E); if (CE->isBuiltinCall(CGM.getContext()) != Builtin::BI__builtin___CFStringMakeConstantString) break; const Expr *Arg = CE->getArg(0)->IgnoreParenCasts(); const StringLiteral *Literal = cast<StringLiteral>(Arg); // FIXME: need to deal with UCN conversion issues. return CGM.GetAddrOfConstantCFString(Literal); } case Expr::BlockExprClass: { std::string FunctionName; if (CGF) FunctionName = CGF->CurFn->getName(); else FunctionName = "global"; return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str()); } } return 0; } }; } // end anonymous namespace. llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF) { Expr::EvalResult Result; bool Success = false; if (DestType->isReferenceType()) { // If the destination type is a reference type, we need to evaluate it // as an lvalue. if (E->EvaluateAsLValue(Result, Context)) { if (const Expr *LVBase = Result.Val.getLValueBase()) { if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVBase)) { const ValueDecl *VD = cast<ValueDecl>(DRE->getDecl()); // We can only initialize a reference with an lvalue if the lvalue // is not a reference itself. Success = !VD->getType()->isReferenceType(); } } } } else Success = E->Evaluate(Result, Context); if (Success) { assert(!Result.HasSideEffects && "Constant expr should not have any side effects!"); switch (Result.Val.getKind()) { case APValue::Uninitialized: assert(0 && "Constant expressions should be initialized."); return 0; case APValue::LValue: { const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType); llvm::Constant *Offset = llvm::ConstantInt::get(llvm::Type::Int64Ty, Result.Val.getLValueOffset()); llvm::Constant *C; if (const Expr *LVBase = Result.Val.getLValueBase()) { C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase)); // Apply offset if necessary. if (!Offset->isNullValue()) { const llvm::Type *Type = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type); Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1); C = llvm::ConstantExpr::getBitCast(Casted, C->getType()); } // Convert to the appropriate type; this could be an lvalue for // an integer. if (isa<llvm::PointerType>(DestTy)) return llvm::ConstantExpr::getBitCast(C, DestTy); return llvm::ConstantExpr::getPtrToInt(C, DestTy); } else { C = Offset; // Convert to the appropriate type; this could be an lvalue for // an integer. if (isa<llvm::PointerType>(DestTy)) return llvm::ConstantExpr::getIntToPtr(C, DestTy); // If the types don't match this should only be a truncate. if (C->getType() != DestTy) return llvm::ConstantExpr::getTrunc(C, DestTy); return C; } } case APValue::Int: { llvm::Constant *C = llvm::ConstantInt::get(Result.Val.getInt()); if (C->getType() == llvm::Type::Int1Ty) { const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); C = llvm::ConstantExpr::getZExt(C, BoolTy); } return C; } case APValue::ComplexInt: { llvm::Constant *Complex[2]; Complex[0] = llvm::ConstantInt::get(Result.Val.getComplexIntReal()); Complex[1] = llvm::ConstantInt::get(Result.Val.getComplexIntImag()); return llvm::ConstantStruct::get(Complex, 2); } case APValue::Float: return llvm::ConstantFP::get(Result.Val.getFloat()); case APValue::ComplexFloat: { llvm::Constant *Complex[2]; Complex[0] = llvm::ConstantFP::get(Result.Val.getComplexFloatReal()); Complex[1] = llvm::ConstantFP::get(Result.Val.getComplexFloatImag()); return llvm::ConstantStruct::get(Complex, 2); } case APValue::Vector: { llvm::SmallVector<llvm::Constant *, 4> Inits; unsigned NumElts = Result.Val.getVectorLength(); for (unsigned i = 0; i != NumElts; ++i) { APValue &Elt = Result.Val.getVectorElt(i); if (Elt.isInt()) Inits.push_back(llvm::ConstantInt::get(Elt.getInt())); else Inits.push_back(llvm::ConstantFP::get(Elt.getFloat())); } return llvm::ConstantVector::get(&Inits[0], Inits.size()); } } } llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E)); if (C && C->getType() == llvm::Type::Int1Ty) { const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); C = llvm::ConstantExpr::getZExt(C, BoolTy); } return C; } llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { // Always return an LLVM null constant for now; this will change when we // get support for IRGen of member pointers. return llvm::Constant::getNullValue(getTypes().ConvertType(T)); } <file_sep>/test/FixIt/fixit-c90.c /* RUN: clang-cc -fsyntax-only -std=c90 -pedantic -fixit %s -o - | clang-cc -pedantic -x c -std=c90 -Werror - */ /* This is a test of the various code modification hints that are provided as part of warning or extension diagnostics. All of the warnings will be fixed by -fixit, and the resulting file should compile cleanly with -Werror -pedantic. */ enum e0 { e1, }; <file_sep>/test/Driver/preprocessor.c // RUN: clang -E -x c-header %s > %t && // RUN: grep 'B B' %t #define A B A A <file_sep>/test/SemaCXX/constructor-recovery.cpp // RUN: clang-cc -fsyntax-only -verify %s struct C { virtual C() = 0; // expected-error{{constructor cannot be declared 'virtual'}} }; void f() { C c; } <file_sep>/lib/AST/Decl.cpp //===--- Decl.cpp - Declaration AST Node Implementation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Decl subclasses. // //===----------------------------------------------------------------------===// #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Stmt.h" #include "clang/AST/Expr.h" #include "clang/Basic/IdentifierTable.h" #include <vector> using namespace clang; void Attr::Destroy(ASTContext &C) { if (Next) { Next->Destroy(C); Next = 0; } this->~Attr(); C.Deallocate((void*)this); } //===----------------------------------------------------------------------===// // Decl Allocation/Deallocation Method Implementations //===----------------------------------------------------------------------===// TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { return new (C) TranslationUnitDecl(); } NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id) { return new (C) NamespaceDecl(DC, L, Id); } void NamespaceDecl::Destroy(ASTContext& C) { // NamespaceDecl uses "NextDeclarator" to chain namespace declarations // together. They are all top-level Decls. this->~NamespaceDecl(); C.Deallocate((void *)this); } ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T) { return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T); } const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { switch (SC) { case VarDecl::None: break; case VarDecl::Auto: return "auto"; break; case VarDecl::Extern: return "extern"; break; case VarDecl::PrivateExtern: return "__private_extern__"; break; case VarDecl::Register: return "register"; break; case VarDecl::Static: return "static"; break; } assert(0 && "Invalid storage class"); return 0; } ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, StorageClass S, Expr *DefArg) { return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, S, DefArg); } QualType ParmVarDecl::getOriginalType() const { if (const OriginalParmVarDecl *PVD = dyn_cast<OriginalParmVarDecl>(this)) return PVD->OriginalType; return getType(); } bool VarDecl::isExternC(ASTContext &Context) const { if (!Context.getLangOptions().CPlusPlus) return (getDeclContext()->isTranslationUnit() && getStorageClass() != Static) || (getDeclContext()->isFunctionOrMethod() && hasExternalStorage()); for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) return getStorageClass() != Static; break; } if (DC->isFunctionOrMethod()) return false; } return false; } OriginalParmVarDecl *OriginalParmVarDecl::Create( ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, QualType OT, StorageClass S, Expr *DefArg) { return new (C) OriginalParmVarDecl(DC, L, Id, T, OT, S, DefArg); } FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, StorageClass S, bool isInline, bool hasPrototype, SourceLocation TypeSpecStartLoc) { FunctionDecl *New = new (C) FunctionDecl(Function, DC, L, N, T, S, isInline, TypeSpecStartLoc); New->HasPrototype = hasPrototype; return New; } BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { return new (C) BlockDecl(DC, L); } FieldDecl *FieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *BW, bool Mutable) { return new (C) FieldDecl(Decl::Field, DC, L, Id, T, BW, Mutable); } bool FieldDecl::isAnonymousStructOrUnion() const { if (!isImplicit() || getDeclName()) return false; if (const RecordType *Record = getType()->getAsRecordType()) return Record->getDecl()->isAnonymousStructOrUnion(); return false; } EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V) { return new (C) EnumConstantDecl(CD, L, Id, T, E, V); } void EnumConstantDecl::Destroy(ASTContext& C) { if (Init) Init->Destroy(C); Decl::Destroy(C); } TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T) { return new (C) TypedefDecl(DC, L, Id, T); } EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, EnumDecl *PrevDecl) { EnumDecl *Enum = new (C) EnumDecl(DC, L, Id); C.getTypeDeclType(Enum, PrevDecl); return Enum; } void EnumDecl::Destroy(ASTContext& C) { Decl::Destroy(C); } void EnumDecl::completeDefinition(ASTContext &C, QualType NewType) { assert(!isDefinition() && "Cannot redefine enums!"); IntegerType = NewType; TagDecl::completeDefinition(); } FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, StringLiteral *Str) { return new (C) FileScopeAsmDecl(DC, L, Str); } //===----------------------------------------------------------------------===// // NamedDecl Implementation //===----------------------------------------------------------------------===// std::string NamedDecl::getQualifiedNameAsString() const { std::vector<std::string> Names; std::string QualName; const DeclContext *Ctx = getDeclContext(); if (Ctx->isFunctionOrMethod()) return getNameAsString(); while (Ctx) { if (Ctx->isFunctionOrMethod()) // FIXME: That probably will happen, when D was member of local // scope class/struct/union. How do we handle this case? break; if (const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx)) Names.push_back(ND->getNameAsString()); else break; Ctx = Ctx->getParent(); } std::vector<std::string>::reverse_iterator I = Names.rbegin(), End = Names.rend(); for (; I!=End; ++I) QualName += *I + "::"; QualName += getNameAsString(); return QualName; } bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); // UsingDirectiveDecl's are not really NamedDecl's, and all have same name. // We want to keep it, unless it nominates same namespace. if (getKind() == Decl::UsingDirective) { return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() == cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace(); } if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) // For function declarations, we keep track of redeclarations. return FD->getPreviousDeclaration() == OldD; // For method declarations, we keep track of redeclarations. if (isa<ObjCMethodDecl>(this)) return false; // For non-function declarations, if the declarations are of the // same kind then this must be a redeclaration, or semantic analysis // would not have given us the new declaration. return this->getKind() == OldD->getKind(); } bool NamedDecl::hasLinkage() const { if (const VarDecl *VD = dyn_cast<VarDecl>(this)) return VD->hasExternalStorage() || VD->isFileVarDecl(); if (isa<FunctionDecl>(this) && !isa<CXXMethodDecl>(this)) return true; return false; } //===----------------------------------------------------------------------===// // VarDecl Implementation //===----------------------------------------------------------------------===// VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, StorageClass S, SourceLocation TypeSpecStartLoc) { return new (C) VarDecl(Var, DC, L, Id, T, S, TypeSpecStartLoc); } void VarDecl::Destroy(ASTContext& C) { Expr *Init = getInit(); if (Init) Init->Destroy(C); this->~VarDecl(); C.Deallocate((void *)this); } VarDecl::~VarDecl() { } bool VarDecl::isTentativeDefinition(ASTContext &Context) const { if (!isFileVarDecl() || Context.getLangOptions().CPlusPlus) return false; return (!getInit() && (getStorageClass() == None || getStorageClass() == Static)); } const Expr *VarDecl::getDefinition(const VarDecl *&Def) const { Def = this; while (Def && !Def->getInit()) Def = Def->getPreviousDeclaration(); return Def? Def->getInit() : 0; } //===----------------------------------------------------------------------===// // FunctionDecl Implementation //===----------------------------------------------------------------------===// void FunctionDecl::Destroy(ASTContext& C) { if (Body) Body->Destroy(C); for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I) (*I)->Destroy(C); C.Deallocate(ParamInfo); Decl::Destroy(C); } CompoundStmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { for (const FunctionDecl *FD = this; FD != 0; FD = FD->PreviousDeclaration) { if (FD->Body) { Definition = FD; return cast<CompoundStmt>(FD->Body); } } return 0; } bool FunctionDecl::isMain() const { return getDeclContext()->getLookupContext()->isTranslationUnit() && getIdentifier() && getIdentifier()->isStr("main"); } bool FunctionDecl::isExternC(ASTContext &Context) const { // In C, any non-static, non-overloadable function has external // linkage. if (!Context.getLangOptions().CPlusPlus) return getStorageClass() != Static && !getAttr<OverloadableAttr>(); for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) return getStorageClass() != Static && !getAttr<OverloadableAttr>(); break; } } return false; } bool FunctionDecl::isGlobal() const { if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) return Method->isStatic(); if (getStorageClass() == Static) return false; for (const DeclContext *DC = getDeclContext(); DC->isNamespace(); DC = DC->getParent()) { if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { if (!Namespace->getDeclName()) return false; break; } } return true; } /// \brief Returns a value indicating whether this function /// corresponds to a builtin function. /// /// The function corresponds to a built-in function if it is /// declared at translation scope or within an extern "C" block and /// its name matches with the name of a builtin. The returned value /// will be 0 for functions that do not correspond to a builtin, a /// value of type \c Builtin::ID if in the target-independent range /// \c [1,Builtin::First), or a target-specific builtin value. unsigned FunctionDecl::getBuiltinID(ASTContext &Context) const { if (!getIdentifier() || !getIdentifier()->getBuiltinID()) return 0; unsigned BuiltinID = getIdentifier()->getBuiltinID(); if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) return BuiltinID; // This function has the name of a known C library // function. Determine whether it actually refers to the C library // function or whether it just has the same name. // If this is a static function, it's not a builtin. if (getStorageClass() == Static) return 0; // If this function is at translation-unit scope and we're not in // C++, it refers to the C library function. if (!Context.getLangOptions().CPlusPlus && getDeclContext()->isTranslationUnit()) return BuiltinID; // If the function is in an extern "C" linkage specification and is // not marked "overloadable", it's the real function. if (isa<LinkageSpecDecl>(getDeclContext()) && cast<LinkageSpecDecl>(getDeclContext())->getLanguage() == LinkageSpecDecl::lang_c && !getAttr<OverloadableAttr>()) return BuiltinID; // Not a builtin return 0; } // Helper function for FunctionDecl::getNumParams and FunctionDecl::setParams() static unsigned getNumTypeParams(QualType T) { const FunctionType *FT = T->getAsFunctionType(); if (isa<FunctionNoProtoType>(FT)) return 0; return cast<FunctionProtoType>(FT)->getNumArgs(); } unsigned FunctionDecl::getNumParams() const { // Can happen if a FunctionDecl is declared using typeof(some_other_func) bar; if (!ParamInfo) return 0; return getNumTypeParams(getType()); } void FunctionDecl::setParams(ASTContext& C, ParmVarDecl **NewParamInfo, unsigned NumParams) { assert(ParamInfo == 0 && "Already has param info!"); assert(NumParams == getNumTypeParams(getType()) && "Parameter count mismatch!"); // Zero params -> null pointer. if (NumParams) { void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams); ParamInfo = new (Mem) ParmVarDecl*[NumParams]; memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); } } /// getMinRequiredArguments - Returns the minimum number of arguments /// needed to call this function. This may be fewer than the number of /// function parameters, if some of the parameters have default /// arguments (in C++). unsigned FunctionDecl::getMinRequiredArguments() const { unsigned NumRequiredArgs = getNumParams(); while (NumRequiredArgs > 0 && getParamDecl(NumRequiredArgs-1)->getDefaultArg()) --NumRequiredArgs; return NumRequiredArgs; } /// getOverloadedOperator - Which C++ overloaded operator this /// function represents, if any. OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) return getDeclName().getCXXOverloadedOperator(); else return OO_None; } //===----------------------------------------------------------------------===// // TagDecl Implementation //===----------------------------------------------------------------------===// void TagDecl::startDefinition() { TagType *TagT = const_cast<TagType *>(TypeForDecl->getAsTagType()); TagT->decl.setPointer(this); TagT->getAsTagType()->decl.setInt(1); } void TagDecl::completeDefinition() { assert((!TypeForDecl || TypeForDecl->getAsTagType()->decl.getPointer() == this) && "Attempt to redefine a tag definition?"); IsDefinition = true; TagType *TagT = const_cast<TagType *>(TypeForDecl->getAsTagType()); TagT->decl.setPointer(this); TagT->decl.setInt(0); } TagDecl* TagDecl::getDefinition(ASTContext& C) const { QualType T = C.getTypeDeclType(const_cast<TagDecl*>(this)); TagDecl* D = cast<TagDecl>(T->getAsTagType()->getDecl()); return D->isDefinition() ? D : 0; } //===----------------------------------------------------------------------===// // RecordDecl Implementation //===----------------------------------------------------------------------===// RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id) : TagDecl(DK, TK, DC, L, Id) { HasFlexibleArrayMember = false; AnonymousStructOrUnion = false; assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); } RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, RecordDecl* PrevDecl) { RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id); C.getTypeDeclType(R, PrevDecl); return R; } RecordDecl::~RecordDecl() { } void RecordDecl::Destroy(ASTContext& C) { TagDecl::Destroy(C); } bool RecordDecl::isInjectedClassName() const { return isImplicit() && getDeclName() && getDeclContext()->isRecord() && cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); } /// completeDefinition - Notes that the definition of this type is now /// complete. void RecordDecl::completeDefinition(ASTContext& C) { assert(!isDefinition() && "Cannot redefine record!"); TagDecl::completeDefinition(); } //===----------------------------------------------------------------------===// // BlockDecl Implementation //===----------------------------------------------------------------------===// BlockDecl::~BlockDecl() { } void BlockDecl::Destroy(ASTContext& C) { if (Body) Body->Destroy(C); for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I) (*I)->Destroy(C); C.Deallocate(ParamInfo); Decl::Destroy(C); } void BlockDecl::setParams(ASTContext& C, ParmVarDecl **NewParamInfo, unsigned NParms) { assert(ParamInfo == 0 && "Already has param info!"); // Zero params -> null pointer. if (NParms) { NumParams = NParms; void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams); ParamInfo = new (Mem) ParmVarDecl*[NumParams]; memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); } } unsigned BlockDecl::getNumParams() const { return NumParams; } <file_sep>/test/Misc/diag-mapping2.c // This should warn by default. // RUN: clang-cc %s 2>&1 | grep "warning:" && // This should not emit anything. // RUN: clang-cc %s -w 2>&1 | not grep diagnostic && // RUN: clang-cc %s -Wno-#warnings 2>&1 | not grep diagnostic && // -Werror can map all warnings to error. // RUN: clang-cc %s -Werror 2>&1 | grep "error:" && // -Werror can map this one warning to error. // RUN: clang-cc %s -Werror=#warnings 2>&1 | grep "error:" && // -Wno-error= overrides -Werror. rdar://3158301 // RUN: clang-cc %s -Werror -Wno-error=#warnings 2>&1 | grep "warning:" #warning foo <file_sep>/include/clang/Analysis/Visitors/CFGVarDeclVisitor.h //==- CFGVarDeclVisitor - Generic visitor of VarDecls in a CFG --*- C++ --*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the template class CFGVarDeclVisitor, which provides // a generic way to visit all the VarDecl's in a CFG. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_CFG_VARDECL_VISITOR_H #define LLVM_CLANG_ANALYSIS_CFG_VARDECL_VISITOR_H #include "clang/Analysis/Visitors/CFGStmtVisitor.h" #include "clang/AST/Decl.h" #include "clang/AST/Stmt.h" #include "clang/AST/CFG.h" namespace clang { template <typename ImplClass> class CFGVarDeclVisitor : public CFGStmtVisitor<ImplClass> { const CFG& cfg; public: CFGVarDeclVisitor(const CFG& c) : cfg(c) {} void VisitStmt(Stmt* S) { static_cast<ImplClass*>(this)->VisitChildren(S); } void VisitDeclRefExpr(DeclRefExpr* DR) { static_cast<ImplClass*>(this)->VisitDeclChain(DR->getDecl()); } void VisitDeclStmt(DeclStmt* DS) { static_cast<ImplClass*>(this)->VisitDeclChain(DS->getDecl()); } void VisitDeclChain(ScopedDecl* D) { for (; D != NULL ; D = D->getNextDeclarator()) static_cast<ImplClass*>(this)->VisitScopedDecl(D); } void VisitScopedDecl(ScopedDecl* D) { if (VarDecl* V = dyn_cast<VarDecl>(D)) static_cast<ImplClass*>(this)->VisitVarDecl(V); } void VisitVarDecl(VarDecl* D) {} void VisitAllDecls() { for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) for (CFGBlock::const_iterator SI=BI->begin(),SE = BI->end();SI != SE;++SI) static_cast<ImplClass*>(this)->BlockStmt_Visit(const_cast<Stmt*>(*SI)); } }; } // end namespace clang #endif <file_sep>/lib/Driver/ToolChain.cpp //===--- ToolChain.cpp - Collections of tools for one platform ----------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/ToolChain.h" #include "clang/Driver/Action.h" #include "clang/Driver/Driver.h" #include "clang/Driver/HostInfo.h" using namespace clang::driver; ToolChain::ToolChain(const HostInfo &_Host, const char *_Arch, const char *_Platform, const char *_OS) : Host(_Host), Arch(_Arch), Platform(_Platform), OS(_OS) { } ToolChain::~ToolChain() { } llvm::sys::Path ToolChain::GetFilePath(const Compilation &C, const char *Name) const { return Host.getDriver().GetFilePath(Name, *this); } llvm::sys::Path ToolChain::GetProgramPath(const Compilation &C, const char *Name, bool WantFile) const { return Host.getDriver().GetProgramPath(Name, *this, WantFile); } <file_sep>/lib/Frontend/ManagerRegistry.cpp //===- ManagerRegistry.cpp - Pluggble Analyzer module creators --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the pluggable analyzer module creators. // //===----------------------------------------------------------------------===// #include "clang/Frontend/ManagerRegistry.h" using namespace clang; StoreManagerCreator ManagerRegistry::StoreMgrCreator = 0; ConstraintManagerCreator ManagerRegistry::ConstraintMgrCreator = 0; <file_sep>/test/Coverage/ast-printing.c // RUN: clang-cc --fsyntax-only %s && // RUN: clang-cc --ast-print %s && // RUN: clang-cc --ast-dump %s #include "c-language-features.inc" <file_sep>/test/Parser/char-literal-printing.c // RUN: clang-cc -ast-print %s #include <stddef.h> char test1(void) { return '\\'; } wchar_t test2(void) { return L'\\'; } char test3(void) { return '\''; } wchar_t test4(void) { return L'\''; } char test5(void) { return '\a'; } wchar_t test6(void) { return L'\a'; } char test7(void) { return '\b'; } wchar_t test8(void) { return L'\b'; } char test9(void) { return '\e'; } wchar_t test10(void) { return L'\e'; } char test11(void) { return '\f'; } wchar_t test12(void) { return L'\f'; } char test13(void) { return '\n'; } wchar_t test14(void) { return L'\n'; } char test15(void) { return '\r'; } wchar_t test16(void) { return L'\r'; } char test17(void) { return '\t'; } wchar_t test18(void) { return L'\t'; } char test19(void) { return '\v'; } wchar_t test20(void) { return L'\v'; } char test21(void) { return 'c'; } wchar_t test22(void) { return L'c'; } char test23(void) { return '\x3'; } wchar_t test24(void) { return L'\x3'; } wchar_t test25(void) { return L'\x333'; } <file_sep>/test/CodeGen/vla.c // RUN: clang-cc %s -emit-llvm -o %t int b(char* x); // Extremely basic VLA test void a(int x) { char arry[x]; arry[0] = 10; b(arry); } int c(int n) { return sizeof(int[n]); } int f0(int x) { int vla[x]; return vla[x-1]; } void f(int count) { int a[count]; do { } while (0); if (a[0] != 3) { } } <file_sep>/tools/ccc/test/ccc/hello.cpp // RUN: xcc -ccc-cxx %s -o %t && // RUN: %t | grep "Hello, World" // XFAIL #include <iostream> int main() { std::cout << "Hello, World!\n"; return 0; } <file_sep>/test/CodeGen/builtins-ffs_parity_popcount.c // RUN: clang-cc -emit-llvm -o - %s > %t // RUN: ! grep "__builtin" %t #include <stdio.h> void test(int M, long long N) { printf("%d %lld: %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n", M, N, __builtin_ffs(M), __builtin_ffsl(M), __builtin_ffsll(M), __builtin_parity(M), __builtin_parityl(M), __builtin_parityll(M), __builtin_popcount(M), __builtin_popcountl(M), __builtin_popcountll(M), __builtin_ffs(N), __builtin_ffsl(N), __builtin_ffsll(N), __builtin_parity(N), __builtin_parityl(N), __builtin_parityll(N), __builtin_popcount(N), __builtin_popcountl(N), __builtin_popcountll(N)); } <file_sep>/test/Parser/cxx-variadic-func.cpp // RUN: clang-cc -fsyntax-only %s void f(...) { int g(int(...)); } <file_sep>/test/Lexer/constants.c /* RUN: clang-cc -fsyntax-only -verify %s */ int x = 000000080; /* expected-error {{invalid digit}} */ int y = 0000\ 00080; /* expected-error {{invalid digit}} */ <file_sep>/test/SemaTemplate/qualified-names-diag.cpp // RUN: clang-cc -fsyntax-only -verify %s namespace std { template<typename T> class vector { }; } typedef int INT; typedef float Real; void test() { using namespace std; std::vector<INT> v1; vector<Real> v2; v1 = v2; // expected-error{{incompatible type assigning 'vector<Real>', expected 'std::vector<INT>'}} } <file_sep>/test/Preprocessor/_Pragma-syshdr2.c // RUN: clang-cc -E %s 2>&1 | grep 'file not found' #define DO_PRAGMA _Pragma DO_PRAGMA ("GCC dependency \"blahblabh\"") <file_sep>/lib/Analysis/GRExprEngineInternalChecks.cpp //=-- GRExprEngineInternalChecks.cpp - Builtin GRExprEngine Checks---*- C++ -*-= // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the BugType classes used by GRExprEngine to report // bugs derived from builtin checks in the path-sensitive engine. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" using namespace clang; //===----------------------------------------------------------------------===// // Utility functions. //===----------------------------------------------------------------------===// template <typename ITERATOR> inline ExplodedNode<GRState>* GetNode(ITERATOR I) { return *I; } template <> inline ExplodedNode<GRState>* GetNode(GRExprEngine::undef_arg_iterator I) { return I->first; } //===----------------------------------------------------------------------===// // Bug Descriptions. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN BuiltinBug : public BugType { GRExprEngine &Eng; protected: const std::string desc; public: BuiltinBug(GRExprEngine *eng, const char* n, const char* d) : BugType(n, "Logic Errors"), Eng(*eng), desc(d) {} BuiltinBug(GRExprEngine *eng, const char* n) : BugType(n, "Logic Errors"), Eng(*eng), desc(n) {} virtual void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) = 0; void FlushReports(BugReporter& BR) { FlushReportsImpl(BR, Eng); } template <typename ITER> void Emit(BugReporter& BR, ITER I, ITER E) { for (; I != E; ++I) BR.EmitReport(new BugReport(*this, desc.c_str(), GetNode(I))); } }; class VISIBILITY_HIDDEN NullDeref : public BuiltinBug { public: NullDeref(GRExprEngine* eng) : BuiltinBug(eng,"Null dereference", "Dereference of null pointer") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.null_derefs_begin(), Eng.null_derefs_end()); } }; class VISIBILITY_HIDDEN NilReceiverStructRet : public BugType { GRExprEngine &Eng; public: NilReceiverStructRet(GRExprEngine* eng) : BugType("'nil' receiver with struct return type", "Logic Errors"), Eng(*eng) {} void FlushReports(BugReporter& BR) { for (GRExprEngine::nil_receiver_struct_ret_iterator I=Eng.nil_receiver_struct_ret_begin(), E=Eng.nil_receiver_struct_ret_end(); I!=E; ++I) { std::string sbuf; llvm::raw_string_ostream os(sbuf); PostStmt P = cast<PostStmt>((*I)->getLocation()); ObjCMessageExpr *ME = cast<ObjCMessageExpr>(P.getStmt()); os << "The receiver in the message expression is 'nil' and results in the" " returned value (of type '" << ME->getType().getAsString() << "') to be garbage or otherwise undefined."; RangedBugReport *R = new RangedBugReport(*this, os.str().c_str(), *I); R->addRange(ME->getReceiver()->getSourceRange()); BR.EmitReport(R); } } }; class VISIBILITY_HIDDEN NilReceiverLargerThanVoidPtrRet : public BugType { GRExprEngine &Eng; public: NilReceiverLargerThanVoidPtrRet(GRExprEngine* eng) : BugType("'nil' receiver with return type larger than sizeof(void *)", "Logic Errors"), Eng(*eng) {} void FlushReports(BugReporter& BR) { for (GRExprEngine::nil_receiver_larger_than_voidptr_ret_iterator I=Eng.nil_receiver_larger_than_voidptr_ret_begin(), E=Eng.nil_receiver_larger_than_voidptr_ret_end(); I!=E; ++I) { std::string sbuf; llvm::raw_string_ostream os(sbuf); PostStmt P = cast<PostStmt>((*I)->getLocation()); ObjCMessageExpr *ME = cast<ObjCMessageExpr>(P.getStmt()); os << "The receiver in the message expression is 'nil' and results in the" " returned value (of type '" << ME->getType().getAsString() << "' and of size " << Eng.getContext().getTypeSize(ME->getType()) / 8 << " bytes) to be garbage or otherwise undefined."; RangedBugReport *R = new RangedBugReport(*this, os.str().c_str(), *I); R->addRange(ME->getReceiver()->getSourceRange()); BR.EmitReport(R); } } }; class VISIBILITY_HIDDEN UndefinedDeref : public BuiltinBug { public: UndefinedDeref(GRExprEngine* eng) : BuiltinBug(eng,"Dereference of undefined pointer value") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.undef_derefs_begin(), Eng.undef_derefs_end()); } }; class VISIBILITY_HIDDEN DivZero : public BuiltinBug { public: DivZero(GRExprEngine* eng) : BuiltinBug(eng,"Division-by-zero", "Division by zero or undefined value.") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.explicit_bad_divides_begin(), Eng.explicit_bad_divides_end()); } }; class VISIBILITY_HIDDEN UndefResult : public BuiltinBug { public: UndefResult(GRExprEngine* eng) : BuiltinBug(eng,"Undefined result", "Result of operation is undefined.") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.undef_results_begin(), Eng.undef_results_end()); } }; class VISIBILITY_HIDDEN BadCall : public BuiltinBug { public: BadCall(GRExprEngine *eng) : BuiltinBug(eng, "Invalid function call", "Called function pointer is a null or undefined pointer value") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.bad_calls_begin(), Eng.bad_calls_end()); } }; class VISIBILITY_HIDDEN BadArg : public BuiltinBug { public: BadArg(GRExprEngine* eng) : BuiltinBug(eng,"Uninitialized argument", "Pass-by-value argument in function call is undefined.") {} BadArg(GRExprEngine* eng, const char* d) : BuiltinBug(eng,"Uninitialized argument", d) {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::UndefArgsTy::iterator I = Eng.undef_arg_begin(), E = Eng.undef_arg_end(); I!=E; ++I) { // Generate a report for this bug. RangedBugReport *report = new RangedBugReport(*this, desc.c_str(), I->first); report->addRange(I->second->getSourceRange()); BR.EmitReport(report); } } }; class VISIBILITY_HIDDEN BadMsgExprArg : public BadArg { public: BadMsgExprArg(GRExprEngine* eng) : BadArg(eng,"Pass-by-value argument in message expression is undefined"){} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::UndefArgsTy::iterator I=Eng.msg_expr_undef_arg_begin(), E = Eng.msg_expr_undef_arg_end(); I!=E; ++I) { // Generate a report for this bug. RangedBugReport *report = new RangedBugReport(*this, desc.c_str(), I->first); report->addRange(I->second->getSourceRange()); BR.EmitReport(report); } } }; class VISIBILITY_HIDDEN BadReceiver : public BuiltinBug { public: BadReceiver(GRExprEngine* eng) : BuiltinBug(eng,"Uninitialized receiver", "Receiver in message expression is an uninitialized value") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::ErrorNodes::iterator I=Eng.undef_receivers_begin(), End = Eng.undef_receivers_end(); I!=End; ++I) { // Generate a report for this bug. RangedBugReport *report = new RangedBugReport(*this, desc.c_str(), *I); ExplodedNode<GRState>* N = *I; Stmt *S = cast<PostStmt>(N->getLocation()).getStmt(); Expr* E = cast<ObjCMessageExpr>(S)->getReceiver(); assert (E && "Receiver cannot be NULL"); report->addRange(E->getSourceRange()); BR.EmitReport(report); } } }; class VISIBILITY_HIDDEN RetStack : public BuiltinBug { public: RetStack(GRExprEngine* eng) : BuiltinBug(eng, "Return of address to stack-allocated memory") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::ret_stackaddr_iterator I=Eng.ret_stackaddr_begin(), End = Eng.ret_stackaddr_end(); I!=End; ++I) { ExplodedNode<GRState>* N = *I; Stmt *S = cast<PostStmt>(N->getLocation()).getStmt(); Expr* E = cast<ReturnStmt>(S)->getRetValue(); assert (E && "Return expression cannot be NULL"); // Get the value associated with E. loc::MemRegionVal V = cast<loc::MemRegionVal>(Eng.getStateManager().GetSVal(N->getState(), E)); // Generate a report for this bug. std::string buf; llvm::raw_string_ostream os(buf); SourceRange R; // Check if the region is a compound literal. if (const CompoundLiteralRegion* CR = dyn_cast<CompoundLiteralRegion>(V.getRegion())) { const CompoundLiteralExpr* CL = CR->getLiteralExpr(); os << "Address of stack memory associated with a compound literal " "declared on line " << BR.getSourceManager() .getInstantiationLineNumber(CL->getLocStart()) << " returned."; R = CL->getSourceRange(); } else if (const AllocaRegion* AR = dyn_cast<AllocaRegion>(V.getRegion())) { const Expr* ARE = AR->getExpr(); SourceLocation L = ARE->getLocStart(); R = ARE->getSourceRange(); os << "Address of stack memory allocated by call to alloca() on line " << BR.getSourceManager().getInstantiationLineNumber(L) << " returned."; } else { os << "Address of stack memory associated with local variable '" << V.getRegion()->getString() << "' returned."; } RangedBugReport *report = new RangedBugReport(*this, os.str().c_str(), N); report->addRange(E->getSourceRange()); if (R.isValid()) report->addRange(R); BR.EmitReport(report); } } }; class VISIBILITY_HIDDEN RetUndef : public BuiltinBug { public: RetUndef(GRExprEngine* eng) : BuiltinBug(eng, "Uninitialized return value", "Uninitialized or undefined return value returned to caller.") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.ret_undef_begin(), Eng.ret_undef_end()); } }; class VISIBILITY_HIDDEN UndefBranch : public BuiltinBug { struct VISIBILITY_HIDDEN FindUndefExpr { GRStateManager& VM; const GRState* St; FindUndefExpr(GRStateManager& V, const GRState* S) : VM(V), St(S) {} Expr* FindExpr(Expr* Ex) { if (!MatchesCriteria(Ex)) return 0; for (Stmt::child_iterator I=Ex->child_begin(), E=Ex->child_end();I!=E;++I) if (Expr* ExI = dyn_cast_or_null<Expr>(*I)) { Expr* E2 = FindExpr(ExI); if (E2) return E2; } return Ex; } bool MatchesCriteria(Expr* Ex) { return VM.GetSVal(St, Ex).isUndef(); } }; public: UndefBranch(GRExprEngine *eng) : BuiltinBug(eng,"Use of uninitialized value", "Branch condition evaluates to an uninitialized value.") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::undef_branch_iterator I=Eng.undef_branches_begin(), E=Eng.undef_branches_end(); I!=E; ++I) { // What's going on here: we want to highlight the subexpression of the // condition that is the most likely source of the "uninitialized // branch condition." We do a recursive walk of the condition's // subexpressions and roughly look for the most nested subexpression // that binds to Undefined. We then highlight that expression's range. BlockEdge B = cast<BlockEdge>((*I)->getLocation()); Expr* Ex = cast<Expr>(B.getSrc()->getTerminatorCondition()); assert (Ex && "Block must have a terminator."); // Get the predecessor node and check if is a PostStmt with the Stmt // being the terminator condition. We want to inspect the state // of that node instead because it will contain main information about // the subexpressions. assert (!(*I)->pred_empty()); // Note: any predecessor will do. They should have identical state, // since all the BlockEdge did was act as an error sink since the value // had to already be undefined. ExplodedNode<GRState> *N = *(*I)->pred_begin(); ProgramPoint P = N->getLocation(); const GRState* St = (*I)->getState(); if (PostStmt* PS = dyn_cast<PostStmt>(&P)) if (PS->getStmt() == Ex) St = N->getState(); FindUndefExpr FindIt(Eng.getStateManager(), St); Ex = FindIt.FindExpr(Ex); RangedBugReport *R = new RangedBugReport(*this, desc.c_str(), *I); R->addRange(Ex->getSourceRange()); BR.EmitReport(R); } } }; class VISIBILITY_HIDDEN OutOfBoundMemoryAccess : public BuiltinBug { public: OutOfBoundMemoryAccess(GRExprEngine* eng) : BuiltinBug(eng,"Out-of-bounds memory access", "Load or store into an out-of-bound memory position.") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { Emit(BR, Eng.explicit_oob_memacc_begin(), Eng.explicit_oob_memacc_end()); } }; class VISIBILITY_HIDDEN BadSizeVLA : public BuiltinBug { public: BadSizeVLA(GRExprEngine* eng) : BuiltinBug(eng, "Bad variable-length array (VLA) size") {} void FlushReportsImpl(BugReporter& BR, GRExprEngine& Eng) { for (GRExprEngine::ErrorNodes::iterator I = Eng.ExplicitBadSizedVLA.begin(), E = Eng.ExplicitBadSizedVLA.end(); I!=E; ++I) { // Determine whether this was a 'zero-sized' VLA or a VLA with an // undefined size. GRExprEngine::NodeTy* N = *I; PostStmt PS = cast<PostStmt>(N->getLocation()); DeclStmt *DS = cast<DeclStmt>(PS.getStmt()); VarDecl* VD = cast<VarDecl>(*DS->decl_begin()); QualType T = Eng.getContext().getCanonicalType(VD->getType()); VariableArrayType* VT = cast<VariableArrayType>(T); Expr* SizeExpr = VT->getSizeExpr(); std::string buf; llvm::raw_string_ostream os(buf); os << "The expression used to specify the number of elements in the " "variable-length array (VLA) '" << VD->getNameAsString() << "' evaluates to "; if (Eng.getStateManager().GetSVal(N->getState(), SizeExpr).isUndef()) os << "an undefined or garbage value."; else os << "0. VLAs with no elements have undefined behavior."; RangedBugReport *report = new RangedBugReport(*this, os.str().c_str(), N); report->addRange(SizeExpr->getSourceRange()); BR.EmitReport(report); } } }; //===----------------------------------------------------------------------===// // __attribute__(nonnull) checking class VISIBILITY_HIDDEN CheckAttrNonNull : public GRSimpleAPICheck { BugType *BT; BugReporter &BR; public: CheckAttrNonNull(BugReporter &br) : BT(0), BR(br) {} virtual bool Audit(ExplodedNode<GRState>* N, GRStateManager& VMgr) { CallExpr* CE = cast<CallExpr>(cast<PostStmt>(N->getLocation()).getStmt()); const GRState* state = N->getState(); SVal X = VMgr.GetSVal(state, CE->getCallee()); if (!isa<loc::FuncVal>(X)) return false; FunctionDecl* FD = dyn_cast<FunctionDecl>(cast<loc::FuncVal>(X).getDecl()); const NonNullAttr* Att = FD->getAttr<NonNullAttr>(); if (!Att) return false; // Iterate through the arguments of CE and check them for null. unsigned idx = 0; bool hasError = false; for (CallExpr::arg_iterator I=CE->arg_begin(), E=CE->arg_end(); I!=E; ++I, ++idx) { if (!VMgr.isEqual(state, *I, 0) || !Att->isNonNull(idx)) continue; // Lazily allocate the BugType object if it hasn't already been created. // Ownership is transferred to the BugReporter object once the BugReport // is passed to 'EmitWarning'. if (!BT) BT = new BugType("Argument with 'nonnull' attribute passed null", "API"); RangedBugReport *R = new RangedBugReport(*BT, "Null pointer passed as an argument to a " "'nonnull' parameter", N); R->addRange((*I)->getSourceRange()); BR.EmitReport(R); hasError = true; } return hasError; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Check registration. //===----------------------------------------------------------------------===// void GRExprEngine::RegisterInternalChecks() { // Register internal "built-in" BugTypes with the BugReporter. These BugTypes // are different than what probably many checks will do since they don't // create BugReports on-the-fly but instead wait until GRExprEngine finishes // analyzing a function. Generation of BugReport objects is done via a call // to 'FlushReports' from BugReporter. BR.Register(new NullDeref(this)); BR.Register(new UndefinedDeref(this)); BR.Register(new UndefBranch(this)); BR.Register(new DivZero(this)); BR.Register(new UndefResult(this)); BR.Register(new BadCall(this)); BR.Register(new RetStack(this)); BR.Register(new RetUndef(this)); BR.Register(new BadArg(this)); BR.Register(new BadMsgExprArg(this)); BR.Register(new BadReceiver(this)); BR.Register(new OutOfBoundMemoryAccess(this)); BR.Register(new BadSizeVLA(this)); BR.Register(new NilReceiverStructRet(this)); BR.Register(new NilReceiverLargerThanVoidPtrRet(this)); // The following checks do not need to have their associated BugTypes // explicitly registered with the BugReporter. If they issue any BugReports, // their associated BugType will get registered with the BugReporter // automatically. Note that the check itself is owned by the GRExprEngine // object. AddCheck(new CheckAttrNonNull(BR), Stmt::CallExprClass); } <file_sep>/test/Parser/extension.c // RUN: clang-cc %s -fsyntax-only // Top level extension marker. __extension__ typedef struct { long long int quot; long long int rem; }lldiv_t; // Compound expr __extension__ marker. void bar() { __extension__ int i; int j; } <file_sep>/test/Parser/builtin_types_compatible.c // RUN: clang-cc -fsyntax-only -verify %s extern int funcInt(int); extern float funcFloat(float); extern double funcDouble(double); // figure out why "char *" doesn't work (with gcc, nothing to do with clang) //extern void funcCharPtr(char *); #define func(expr) \ do { \ typeof(expr) tmp; \ if (__builtin_types_compatible_p(typeof(expr), int)) funcInt(tmp); \ else if (__builtin_types_compatible_p(typeof(expr), float)) funcFloat(tmp); \ else if (__builtin_types_compatible_p(typeof(expr), double)) funcDouble(tmp); \ } while (0) #define func_choose(expr) \ __builtin_choose_expr(__builtin_types_compatible_p(typeof(expr), int), funcInt(expr), \ __builtin_choose_expr(__builtin_types_compatible_p(typeof(expr), float), funcFloat(expr), \ __builtin_choose_expr(__builtin_types_compatible_p(typeof(expr), double), funcDouble(expr), (void)0))) static void test() { int a; float b; double d; func(a); func(b); func(d); a = func_choose(a); b = func_choose(b); d = func_choose(d); int c; struct xx { int a; } x, y; c = __builtin_choose_expr(a+3-7, b, x); // expected-error{{'__builtin_choose_expr' requires a constant expression}} c = __builtin_choose_expr(0, b, x); // expected-error{{incompatible type assigning 'struct xx', expected 'int'}} c = __builtin_choose_expr(5+3-7, b, x); y = __builtin_choose_expr(4+3-7, b, x); } <file_sep>/test/CodeGen/no-common.c // RUN: clang -emit-llvm -S -o %t %s && // RUN: grep '@x = common global' %t && // RUN: clang -fno-common -emit-llvm -S -o %t %s && // RUN: grep '@x = global' %t int x; <file_sep>/test/Analysis/uninit-vals.c // RUN: clang-cc -analyze -warn-uninit-values -verify %s int f1() { int x; return x; // expected-warning {{use of uninitialized variable}} } int f2(int x) { int y; int z = x + y; // expected-warning {{use of uninitialized variable}} return z; } int f3(int x) { int y; return x ? 1 : y; // expected-warning {{use of uninitialized variable}} } int f4(int x) { int y; if (x) y = 1; return y; // expected-warning {{use of uninitialized variable}} } int f5() { int a; a = 30; // no-warning } void f6(int i) { int x; for (i = 0 ; i < 10; i++) printf("%d",x++); // expected-warning {{use of uninitialized variable}} \ // expected-warning{{implicitly declaring C library function 'printf' with type 'int (char const *, ...)'}} \ // expected-note{{please include the header <stdio.h> or explicitly provide a declaration for 'printf'}} } void f7(int i) { int x = i; int y; for (i = 0; i < 10; i++ ) { printf("%d",x++); // no-warning x += y; // expected-warning {{use of uninitialized variable}} } } int f8(int j) { int x = 1, y = x + 1; if (y) // no-warning return x; return y; } <file_sep>/test/Sema/struct-decl.c // RUN: clang-cc -fsyntax-only -verify %s // PR3459 struct bar { char n[1]; }; struct foo { char name[(int)&((struct bar *)0)->n]; char name2[(int)&((struct bar *)0)->n - 1]; //expected-error{{array size is negative}} }; // PR3430 struct s { struct st { int v; } *ts; }; struct st; int foo() { struct st *f; return f->v + f[0].v; } // PR3642, PR3671 struct pppoe_tag { short tag_type; char tag_data[]; }; struct datatag { struct pppoe_tag hdr; //expected-warning{{field of variable sized type 'hdr' not at the end of a struct or class is a GNU extension}} char data; }; <file_sep>/test/CodeGen/2008-07-22-bitfield-init-after-zero-len-array.c // RUN: clang-cc --emit-llvm -o %t %s && // RUN: grep "i8 52" %t | count 1 struct et7 { float lv7[0]; char mv7:6; } yv7 = { {}, 52, }; <file_sep>/lib/Frontend/PCHReader.cpp //===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PCHReader class, which reads a precompiled header. // //===----------------------------------------------------------------------===// #include "clang/Frontend/PCHReader.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "clang/AST/Expr.h" #include "clang/AST/StmtVisitor.h" #include "clang/AST/Type.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/SourceManagerInternals.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MemoryBuffer.h" #include <algorithm> #include <cstdio> using namespace clang; //===----------------------------------------------------------------------===// // Declaration deserialization //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN PCHDeclReader { PCHReader &Reader; const PCHReader::RecordData &Record; unsigned &Idx; public: PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record, unsigned &Idx) : Reader(Reader), Record(Record), Idx(Idx) { } void VisitDecl(Decl *D); void VisitTranslationUnitDecl(TranslationUnitDecl *TU); void VisitNamedDecl(NamedDecl *ND); void VisitTypeDecl(TypeDecl *TD); void VisitTypedefDecl(TypedefDecl *TD); void VisitTagDecl(TagDecl *TD); void VisitEnumDecl(EnumDecl *ED); void VisitRecordDecl(RecordDecl *RD); void VisitValueDecl(ValueDecl *VD); void VisitEnumConstantDecl(EnumConstantDecl *ECD); void VisitFunctionDecl(FunctionDecl *FD); void VisitFieldDecl(FieldDecl *FD); void VisitVarDecl(VarDecl *VD); void VisitParmVarDecl(ParmVarDecl *PD); void VisitOriginalParmVarDecl(OriginalParmVarDecl *PD); void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD); void VisitBlockDecl(BlockDecl *BD); std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC); }; } void PCHDeclReader::VisitDecl(Decl *D) { D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++]))); D->setLexicalDeclContext( cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++]))); D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++])); D->setInvalidDecl(Record[Idx++]); if (Record[Idx++]) D->addAttr(Reader.ReadAttributes()); D->setImplicit(Record[Idx++]); D->setAccess((AccessSpecifier)Record[Idx++]); } void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) { VisitDecl(TU); } void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) { VisitDecl(ND); ND->setDeclName(Reader.ReadDeclarationName(Record, Idx)); } void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) { VisitNamedDecl(TD); TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr()); } void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) { // Note that we cannot use VisitTypeDecl here, because we need to // set the underlying type of the typedef *before* we try to read // the type associated with the TypedefDecl. VisitNamedDecl(TD); TD->setUnderlyingType(Reader.GetType(Record[Idx + 1])); TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr()); Idx += 2; } void PCHDeclReader::VisitTagDecl(TagDecl *TD) { VisitTypeDecl(TD); TD->setTagKind((TagDecl::TagKind)Record[Idx++]); TD->setDefinition(Record[Idx++]); TD->setTypedefForAnonDecl( cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++]))); } void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) { VisitTagDecl(ED); ED->setIntegerType(Reader.GetType(Record[Idx++])); } void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) { VisitTagDecl(RD); RD->setHasFlexibleArrayMember(Record[Idx++]); RD->setAnonymousStructOrUnion(Record[Idx++]); } void PCHDeclReader::VisitValueDecl(ValueDecl *VD) { VisitNamedDecl(VD); VD->setType(Reader.GetType(Record[Idx++])); } void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) { VisitValueDecl(ECD); if (Record[Idx++]) ECD->setInitExpr(Reader.ReadExpr()); ECD->setInitVal(Reader.ReadAPSInt(Record, Idx)); } void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) { VisitValueDecl(FD); // FIXME: function body FD->setPreviousDeclaration( cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++]))); FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]); FD->setInline(Record[Idx++]); FD->setVirtual(Record[Idx++]); FD->setPure(Record[Idx++]); FD->setInheritedPrototype(Record[Idx++]); FD->setHasPrototype(Record[Idx++]); FD->setDeleted(Record[Idx++]); FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); unsigned NumParams = Record[Idx++]; llvm::SmallVector<ParmVarDecl *, 16> Params; Params.reserve(NumParams); for (unsigned I = 0; I != NumParams; ++I) Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++]))); FD->setParams(Reader.getContext(), &Params[0], NumParams); } void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) { VisitValueDecl(FD); FD->setMutable(Record[Idx++]); if (Record[Idx++]) FD->setBitWidth(Reader.ReadExpr()); } void PCHDeclReader::VisitVarDecl(VarDecl *VD) { VisitValueDecl(VD); VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]); VD->setThreadSpecified(Record[Idx++]); VD->setCXXDirectInitializer(Record[Idx++]); VD->setDeclaredInCondition(Record[Idx++]); VD->setPreviousDeclaration( cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++]))); VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); if (Record[Idx++]) VD->setInit(Reader.ReadExpr()); } void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) { VisitVarDecl(PD); PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]); // FIXME: default argument (C++ only) } void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) { VisitParmVarDecl(PD); PD->setOriginalType(Reader.GetType(Record[Idx++])); } void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) { VisitDecl(AD); AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr())); } void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) { VisitDecl(BD); unsigned NumParams = Record[Idx++]; llvm::SmallVector<ParmVarDecl *, 16> Params; Params.reserve(NumParams); for (unsigned I = 0; I != NumParams; ++I) Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++]))); BD->setParams(Reader.getContext(), &Params[0], NumParams); } std::pair<uint64_t, uint64_t> PCHDeclReader::VisitDeclContext(DeclContext *DC) { uint64_t LexicalOffset = Record[Idx++]; uint64_t VisibleOffset = 0; if (DC->getPrimaryContext() == DC) VisibleOffset = Record[Idx++]; return std::make_pair(LexicalOffset, VisibleOffset); } //===----------------------------------------------------------------------===// // Statement/expression deserialization //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN PCHStmtReader : public StmtVisitor<PCHStmtReader, unsigned> { PCHReader &Reader; const PCHReader::RecordData &Record; unsigned &Idx; llvm::SmallVectorImpl<Expr *> &ExprStack; public: PCHStmtReader(PCHReader &Reader, const PCHReader::RecordData &Record, unsigned &Idx, llvm::SmallVectorImpl<Expr *> &ExprStack) : Reader(Reader), Record(Record), Idx(Idx), ExprStack(ExprStack) { } /// \brief The number of record fields required for the Expr class /// itself. static const unsigned NumExprFields = 3; // Each of the Visit* functions reads in part of the expression // from the given record and the current expression stack, then // return the total number of operands that it read from the // expression stack. unsigned VisitExpr(Expr *E); unsigned VisitPredefinedExpr(PredefinedExpr *E); unsigned VisitDeclRefExpr(DeclRefExpr *E); unsigned VisitIntegerLiteral(IntegerLiteral *E); unsigned VisitFloatingLiteral(FloatingLiteral *E); unsigned VisitImaginaryLiteral(ImaginaryLiteral *E); unsigned VisitStringLiteral(StringLiteral *E); unsigned VisitCharacterLiteral(CharacterLiteral *E); unsigned VisitParenExpr(ParenExpr *E); unsigned VisitUnaryOperator(UnaryOperator *E); unsigned VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); unsigned VisitArraySubscriptExpr(ArraySubscriptExpr *E); unsigned VisitCallExpr(CallExpr *E); unsigned VisitMemberExpr(MemberExpr *E); unsigned VisitCastExpr(CastExpr *E); unsigned VisitBinaryOperator(BinaryOperator *E); unsigned VisitCompoundAssignOperator(CompoundAssignOperator *E); unsigned VisitConditionalOperator(ConditionalOperator *E); unsigned VisitImplicitCastExpr(ImplicitCastExpr *E); unsigned VisitExplicitCastExpr(ExplicitCastExpr *E); unsigned VisitCStyleCastExpr(CStyleCastExpr *E); unsigned VisitCompoundLiteralExpr(CompoundLiteralExpr *E); unsigned VisitExtVectorElementExpr(ExtVectorElementExpr *E); unsigned VisitInitListExpr(InitListExpr *E); unsigned VisitDesignatedInitExpr(DesignatedInitExpr *E); unsigned VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); unsigned VisitVAArgExpr(VAArgExpr *E); unsigned VisitTypesCompatibleExpr(TypesCompatibleExpr *E); unsigned VisitChooseExpr(ChooseExpr *E); unsigned VisitGNUNullExpr(GNUNullExpr *E); unsigned VisitShuffleVectorExpr(ShuffleVectorExpr *E); unsigned VisitBlockDeclRefExpr(BlockDeclRefExpr *E); }; } unsigned PCHStmtReader::VisitExpr(Expr *E) { E->setType(Reader.GetType(Record[Idx++])); E->setTypeDependent(Record[Idx++]); E->setValueDependent(Record[Idx++]); assert(Idx == NumExprFields && "Incorrect expression field count"); return 0; } unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) { VisitExpr(E); E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]); return 0; } unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) { VisitExpr(E); E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++]))); E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++])); return 0; } unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) { VisitExpr(E); E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setValue(Reader.ReadAPInt(Record, Idx)); return 0; } unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) { VisitExpr(E); E->setValue(Reader.ReadAPFloat(Record, Idx)); E->setExact(Record[Idx++]); E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++])); return 0; } unsigned PCHStmtReader::VisitImaginaryLiteral(ImaginaryLiteral *E) { VisitExpr(E); E->setSubExpr(ExprStack.back()); return 1; } unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) { VisitExpr(E); unsigned Len = Record[Idx++]; assert(Record[Idx] == E->getNumConcatenated() && "Wrong number of concatenated tokens!"); ++Idx; E->setWide(Record[Idx++]); // Read string data llvm::SmallVector<char, 16> Str(&Record[Idx], &Record[Idx] + Len); E->setStrData(Reader.getContext(), &Str[0], Len); Idx += Len; // Read source locations for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I) E->setStrTokenLoc(I, SourceLocation::getFromRawEncoding(Record[Idx++])); return 0; } unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) { VisitExpr(E); E->setValue(Record[Idx++]); E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setWide(Record[Idx++]); return 0; } unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) { VisitExpr(E); E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setSubExpr(ExprStack.back()); return 1; } unsigned PCHStmtReader::VisitUnaryOperator(UnaryOperator *E) { VisitExpr(E); E->setSubExpr(ExprStack.back()); E->setOpcode((UnaryOperator::Opcode)Record[Idx++]); E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return 1; } unsigned PCHStmtReader::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { VisitExpr(E); E->setSizeof(Record[Idx++]); if (Record[Idx] == 0) { E->setArgument(ExprStack.back()); ++Idx; } else { E->setArgument(Reader.GetType(Record[Idx++])); } E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return E->isArgumentType()? 0 : 1; } unsigned PCHStmtReader::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { VisitExpr(E); E->setLHS(ExprStack[ExprStack.size() - 2]); E->setRHS(ExprStack[ExprStack.size() - 2]); E->setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return 2; } unsigned PCHStmtReader::VisitCallExpr(CallExpr *E) { VisitExpr(E); E->setNumArgs(Reader.getContext(), Record[Idx++]); E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setCallee(ExprStack[ExprStack.size() - E->getNumArgs() - 1]); for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) E->setArg(I, ExprStack[ExprStack.size() - N + I]); return E->getNumArgs() + 1; } unsigned PCHStmtReader::VisitMemberExpr(MemberExpr *E) { VisitExpr(E); E->setBase(ExprStack.back()); E->setMemberDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++]))); E->setMemberLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setArrow(Record[Idx++]); return 1; } unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) { VisitExpr(E); E->setSubExpr(ExprStack.back()); return 1; } unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) { VisitExpr(E); E->setLHS(ExprStack.end()[-2]); E->setRHS(ExprStack.end()[-1]); E->setOpcode((BinaryOperator::Opcode)Record[Idx++]); E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return 2; } unsigned PCHStmtReader::VisitCompoundAssignOperator(CompoundAssignOperator *E) { VisitBinaryOperator(E); E->setComputationLHSType(Reader.GetType(Record[Idx++])); E->setComputationResultType(Reader.GetType(Record[Idx++])); return 2; } unsigned PCHStmtReader::VisitConditionalOperator(ConditionalOperator *E) { VisitExpr(E); E->setCond(ExprStack[ExprStack.size() - 3]); E->setLHS(ExprStack[ExprStack.size() - 2]); E->setRHS(ExprStack[ExprStack.size() - 1]); return 3; } unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) { VisitCastExpr(E); E->setLvalueCast(Record[Idx++]); return 1; } unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) { VisitCastExpr(E); E->setTypeAsWritten(Reader.GetType(Record[Idx++])); return 1; } unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) { VisitExplicitCastExpr(E); E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return 1; } unsigned PCHStmtReader::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { VisitExpr(E); E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setInitializer(ExprStack.back()); E->setFileScope(Record[Idx++]); return 1; } unsigned PCHStmtReader::VisitExtVectorElementExpr(ExtVectorElementExpr *E) { VisitExpr(E); E->setBase(ExprStack.back()); E->setAccessor(Reader.GetIdentifierInfo(Record, Idx)); E->setAccessorLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return 1; } unsigned PCHStmtReader::VisitInitListExpr(InitListExpr *E) { VisitExpr(E); unsigned NumInits = Record[Idx++]; E->reserveInits(NumInits); for (unsigned I = 0; I != NumInits; ++I) E->updateInit(I, ExprStack[ExprStack.size() - NumInits - 1 + I]); E->setSyntacticForm(cast_or_null<InitListExpr>(ExprStack.back())); E->setLBraceLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRBraceLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setInitializedFieldInUnion( cast_or_null<FieldDecl>(Reader.GetDecl(Record[Idx++]))); E->sawArrayRangeDesignator(Record[Idx++]); return NumInits + 1; } unsigned PCHStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) { typedef DesignatedInitExpr::Designator Designator; VisitExpr(E); unsigned NumSubExprs = Record[Idx++]; assert(NumSubExprs == E->getNumSubExprs() && "Wrong number of subexprs"); for (unsigned I = 0; I != NumSubExprs; ++I) E->setSubExpr(I, ExprStack[ExprStack.size() - NumSubExprs + I]); E->setEqualOrColonLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setGNUSyntax(Record[Idx++]); llvm::SmallVector<Designator, 4> Designators; while (Idx < Record.size()) { switch ((pch::DesignatorTypes)Record[Idx++]) { case pch::DESIG_FIELD_DECL: { FieldDecl *Field = cast<FieldDecl>(Reader.GetDecl(Record[Idx++])); SourceLocation DotLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); SourceLocation FieldLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); Designators.push_back(Designator(Field->getIdentifier(), DotLoc, FieldLoc)); Designators.back().setField(Field); break; } case pch::DESIG_FIELD_NAME: { const IdentifierInfo *Name = Reader.GetIdentifierInfo(Record, Idx); SourceLocation DotLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); SourceLocation FieldLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); Designators.push_back(Designator(Name, DotLoc, FieldLoc)); break; } case pch::DESIG_ARRAY: { unsigned Index = Record[Idx++]; SourceLocation LBracketLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); SourceLocation RBracketLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); Designators.push_back(Designator(Index, LBracketLoc, RBracketLoc)); break; } case pch::DESIG_ARRAY_RANGE: { unsigned Index = Record[Idx++]; SourceLocation LBracketLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); SourceLocation EllipsisLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); SourceLocation RBracketLoc = SourceLocation::getFromRawEncoding(Record[Idx++]); Designators.push_back(Designator(Index, LBracketLoc, EllipsisLoc, RBracketLoc)); break; } } } E->setDesignators(&Designators[0], Designators.size()); return NumSubExprs; } unsigned PCHStmtReader::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { VisitExpr(E); return 0; } unsigned PCHStmtReader::VisitVAArgExpr(VAArgExpr *E) { VisitExpr(E); E->setSubExpr(ExprStack.back()); E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return 1; } unsigned PCHStmtReader::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) { VisitExpr(E); E->setArgType1(Reader.GetType(Record[Idx++])); E->setArgType2(Reader.GetType(Record[Idx++])); E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return 0; } unsigned PCHStmtReader::VisitChooseExpr(ChooseExpr *E) { VisitExpr(E); E->setCond(ExprStack[ExprStack.size() - 3]); E->setLHS(ExprStack[ExprStack.size() - 2]); E->setRHS(ExprStack[ExprStack.size() - 1]); E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return 3; } unsigned PCHStmtReader::VisitGNUNullExpr(GNUNullExpr *E) { VisitExpr(E); E->setTokenLocation(SourceLocation::getFromRawEncoding(Record[Idx++])); return 0; } unsigned PCHStmtReader::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { VisitExpr(E); unsigned NumExprs = Record[Idx++]; E->setExprs(&ExprStack[ExprStack.size() - NumExprs], NumExprs); E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++])); return NumExprs; } unsigned PCHStmtReader::VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { VisitExpr(E); E->setDecl(cast<ValueDecl>(Reader.GetDecl(Record[Idx++]))); E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++])); E->setByRef(Record[Idx++]); return 0; } // FIXME: use the diagnostics machinery static bool Error(const char *Str) { std::fprintf(stderr, "%s\n", Str); return true; } /// \brief Check the contents of the predefines buffer against the /// contents of the predefines buffer used to build the PCH file. /// /// The contents of the two predefines buffers should be the same. If /// not, then some command-line option changed the preprocessor state /// and we must reject the PCH file. /// /// \param PCHPredef The start of the predefines buffer in the PCH /// file. /// /// \param PCHPredefLen The length of the predefines buffer in the PCH /// file. /// /// \param PCHBufferID The FileID for the PCH predefines buffer. /// /// \returns true if there was a mismatch (in which case the PCH file /// should be ignored), or false otherwise. bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID) { const char *Predef = PP.getPredefines().c_str(); unsigned PredefLen = PP.getPredefines().size(); // If the two predefines buffers compare equal, we're done!. if (PredefLen == PCHPredefLen && strncmp(Predef, PCHPredef, PCHPredefLen) == 0) return false; // The predefines buffers are different. Produce a reasonable // diagnostic showing where they are different. // The source locations (potentially in the two different predefines // buffers) SourceLocation Loc1, Loc2; SourceManager &SourceMgr = PP.getSourceManager(); // Create a source buffer for our predefines string, so // that we can build a diagnostic that points into that // source buffer. FileID BufferID; if (Predef && Predef[0]) { llvm::MemoryBuffer *Buffer = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen, "<built-in>"); BufferID = SourceMgr.createFileIDForMemBuffer(Buffer); } unsigned MinLen = std::min(PredefLen, PCHPredefLen); std::pair<const char *, const char *> Locations = std::mismatch(Predef, Predef + MinLen, PCHPredef); if (Locations.first != Predef + MinLen) { // We found the location in the two buffers where there is a // difference. Form source locations to point there (in both // buffers). unsigned Offset = Locations.first - Predef; Loc1 = SourceMgr.getLocForStartOfFile(BufferID) .getFileLocWithOffset(Offset); Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID) .getFileLocWithOffset(Offset); } else if (PredefLen > PCHPredefLen) { Loc1 = SourceMgr.getLocForStartOfFile(BufferID) .getFileLocWithOffset(MinLen); } else { Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID) .getFileLocWithOffset(MinLen); } Diag(Loc1, diag::warn_pch_preprocessor); if (Loc2.isValid()) Diag(Loc2, diag::note_predef_in_pch); Diag(diag::note_ignoring_pch) << FileName; return true; } /// \brief Read the line table in the source manager block. /// \returns true if ther was an error. static bool ParseLineTable(SourceManager &SourceMgr, llvm::SmallVectorImpl<uint64_t> &Record) { unsigned Idx = 0; LineTableInfo &LineTable = SourceMgr.getLineTable(); // Parse the file names std::map<int, int> FileIDs; for (int I = 0, N = Record[Idx++]; I != N; ++I) { // Extract the file name unsigned FilenameLen = Record[Idx++]; std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen); Idx += FilenameLen; FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(), Filename.size()); } // Parse the line entries std::vector<LineEntry> Entries; while (Idx < Record.size()) { int FID = FileIDs[Record[Idx++]]; // Extract the line entries unsigned NumEntries = Record[Idx++]; Entries.clear(); Entries.reserve(NumEntries); for (unsigned I = 0; I != NumEntries; ++I) { unsigned FileOffset = Record[Idx++]; unsigned LineNo = Record[Idx++]; int FilenameID = Record[Idx++]; SrcMgr::CharacteristicKind FileKind = (SrcMgr::CharacteristicKind)Record[Idx++]; unsigned IncludeOffset = Record[Idx++]; Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID, FileKind, IncludeOffset)); } LineTable.AddEntry(FID, Entries); } return false; } /// \brief Read the source manager block PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() { using namespace SrcMgr; if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) { Error("Malformed source manager block record"); return Failure; } SourceManager &SourceMgr = Context.getSourceManager(); RecordData Record; while (true) { unsigned Code = Stream.ReadCode(); if (Code == llvm::bitc::END_BLOCK) { if (Stream.ReadBlockEnd()) { Error("Error at end of Source Manager block"); return Failure; } return Success; } if (Code == llvm::bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. Stream.ReadSubBlockID(); if (Stream.SkipBlock()) { Error("Malformed block record"); return Failure; } continue; } if (Code == llvm::bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } // Read a record. const char *BlobStart; unsigned BlobLen; Record.clear(); switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) { default: // Default behavior: ignore. break; case pch::SM_SLOC_FILE_ENTRY: { // FIXME: We would really like to delay the creation of this // FileEntry until it is actually required, e.g., when producing // a diagnostic with a source location in this file. const FileEntry *File = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen); // FIXME: Error recovery if file cannot be found. FileID ID = SourceMgr.createFileID(File, SourceLocation::getFromRawEncoding(Record[1]), (CharacteristicKind)Record[2]); if (Record[3]) const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile()) .setHasLineDirectives(); break; } case pch::SM_SLOC_BUFFER_ENTRY: { const char *Name = BlobStart; unsigned Code = Stream.ReadCode(); Record.clear(); unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen); assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file"); (void)RecCode; llvm::MemoryBuffer *Buffer = llvm::MemoryBuffer::getMemBuffer(BlobStart, BlobStart + BlobLen - 1, Name); FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer); if (strcmp(Name, "<built-in>") == 0 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID)) return IgnorePCH; break; } case pch::SM_SLOC_INSTANTIATION_ENTRY: { SourceLocation SpellingLoc = SourceLocation::getFromRawEncoding(Record[1]); SourceMgr.createInstantiationLoc( SpellingLoc, SourceLocation::getFromRawEncoding(Record[2]), SourceLocation::getFromRawEncoding(Record[3]), Record[4]); break; } case pch::SM_LINE_TABLE: if (ParseLineTable(SourceMgr, Record)) return Failure; break; } } } bool PCHReader::ReadPreprocessorBlock() { if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) return Error("Malformed preprocessor block record"); RecordData Record; llvm::SmallVector<IdentifierInfo*, 16> MacroArgs; MacroInfo *LastMacro = 0; while (true) { unsigned Code = Stream.ReadCode(); switch (Code) { case llvm::bitc::END_BLOCK: if (Stream.ReadBlockEnd()) return Error("Error at end of preprocessor block"); return false; case llvm::bitc::ENTER_SUBBLOCK: // No known subblocks, always skip them. Stream.ReadSubBlockID(); if (Stream.SkipBlock()) return Error("Malformed block record"); continue; case llvm::bitc::DEFINE_ABBREV: Stream.ReadAbbrevRecord(); continue; default: break; } // Read a record. Record.clear(); pch::PreprocessorRecordTypes RecType = (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record); switch (RecType) { default: // Default behavior: ignore unknown records. break; case pch::PP_COUNTER_VALUE: if (!Record.empty()) PP.setCounterValue(Record[0]); break; case pch::PP_MACRO_OBJECT_LIKE: case pch::PP_MACRO_FUNCTION_LIKE: { IdentifierInfo *II = DecodeIdentifierInfo(Record[0]); if (II == 0) return Error("Macro must have a name"); SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]); bool isUsed = Record[2]; MacroInfo *MI = PP.AllocateMacroInfo(Loc); MI->setIsUsed(isUsed); if (RecType == pch::PP_MACRO_FUNCTION_LIKE) { // Decode function-like macro info. bool isC99VarArgs = Record[3]; bool isGNUVarArgs = Record[4]; MacroArgs.clear(); unsigned NumArgs = Record[5]; for (unsigned i = 0; i != NumArgs; ++i) MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i])); // Install function-like macro info. MI->setIsFunctionLike(); if (isC99VarArgs) MI->setIsC99Varargs(); if (isGNUVarArgs) MI->setIsGNUVarargs(); MI->setArgumentList(&MacroArgs[0], MacroArgs.size(), PP.getPreprocessorAllocator()); } // Finally, install the macro. PP.setMacroInfo(II, MI); // Remember that we saw this macro last so that we add the tokens that // form its body to it. LastMacro = MI; break; } case pch::PP_TOKEN: { // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just // pretend we didn't see this. if (LastMacro == 0) break; Token Tok; Tok.startToken(); Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0])); Tok.setLength(Record[1]); if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2])) Tok.setIdentifierInfo(II); Tok.setKind((tok::TokenKind)Record[3]); Tok.setFlag((Token::TokenFlags)Record[4]); LastMacro->AddTokenToBody(Tok); break; } } } } PCHReader::PCHReadResult PCHReader::ReadPCHBlock() { if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) { Error("Malformed block record"); return Failure; } uint64_t PreprocessorBlockBit = 0; // Read all of the records and blocks for the PCH file. RecordData Record; while (!Stream.AtEndOfStream()) { unsigned Code = Stream.ReadCode(); if (Code == llvm::bitc::END_BLOCK) { // If we saw the preprocessor block, read it now. if (PreprocessorBlockBit) { uint64_t SavedPos = Stream.GetCurrentBitNo(); Stream.JumpToBit(PreprocessorBlockBit); if (ReadPreprocessorBlock()) { Error("Malformed preprocessor block"); return Failure; } Stream.JumpToBit(SavedPos); } if (Stream.ReadBlockEnd()) { Error("Error at end of module block"); return Failure; } return Success; } if (Code == llvm::bitc::ENTER_SUBBLOCK) { switch (Stream.ReadSubBlockID()) { case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded) case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded) default: // Skip unknown content. if (Stream.SkipBlock()) { Error("Malformed block record"); return Failure; } break; case pch::PREPROCESSOR_BLOCK_ID: // Skip the preprocessor block for now, but remember where it is. We // want to read it in after the identifier table. if (PreprocessorBlockBit) { Error("Multiple preprocessor blocks found."); return Failure; } PreprocessorBlockBit = Stream.GetCurrentBitNo(); if (Stream.SkipBlock()) { Error("Malformed block record"); return Failure; } break; case pch::SOURCE_MANAGER_BLOCK_ID: switch (ReadSourceManagerBlock()) { case Success: break; case Failure: Error("Malformed source manager block"); return Failure; case IgnorePCH: return IgnorePCH; } break; } continue; } if (Code == llvm::bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } // Read and process a record. Record.clear(); const char *BlobStart = 0; unsigned BlobLen = 0; switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) { default: // Default behavior: ignore. break; case pch::TYPE_OFFSET: if (!TypeOffsets.empty()) { Error("Duplicate TYPE_OFFSET record in PCH file"); return Failure; } TypeOffsets.swap(Record); TypeAlreadyLoaded.resize(TypeOffsets.size(), false); break; case pch::DECL_OFFSET: if (!DeclOffsets.empty()) { Error("Duplicate DECL_OFFSET record in PCH file"); return Failure; } DeclOffsets.swap(Record); DeclAlreadyLoaded.resize(DeclOffsets.size(), false); break; case pch::LANGUAGE_OPTIONS: if (ParseLanguageOptions(Record)) return IgnorePCH; break; case pch::TARGET_TRIPLE: { std::string TargetTriple(BlobStart, BlobLen); if (TargetTriple != Context.Target.getTargetTriple()) { Diag(diag::warn_pch_target_triple) << TargetTriple << Context.Target.getTargetTriple(); Diag(diag::note_ignoring_pch) << FileName; return IgnorePCH; } break; } case pch::IDENTIFIER_TABLE: IdentifierTable = BlobStart; break; case pch::IDENTIFIER_OFFSET: if (!IdentifierData.empty()) { Error("Duplicate IDENTIFIER_OFFSET record in PCH file"); return Failure; } IdentifierData.swap(Record); #ifndef NDEBUG for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) { if ((IdentifierData[I] & 0x01) == 0) { Error("Malformed identifier table in the precompiled header"); return Failure; } } #endif break; case pch::EXTERNAL_DEFINITIONS: if (!ExternalDefinitions.empty()) { Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file"); return Failure; } ExternalDefinitions.swap(Record); break; } } Error("Premature end of bitstream"); return Failure; } PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) { // Set the PCH file name. this->FileName = FileName; // Open the PCH file. std::string ErrStr; Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr)); if (!Buffer) { Error(ErrStr.c_str()); return IgnorePCH; } // Initialize the stream Stream.init((const unsigned char *)Buffer->getBufferStart(), (const unsigned char *)Buffer->getBufferEnd()); // Sniff for the signature. if (Stream.Read(8) != 'C' || Stream.Read(8) != 'P' || Stream.Read(8) != 'C' || Stream.Read(8) != 'H') { Error("Not a PCH file"); return IgnorePCH; } // We expect a number of well-defined blocks, though we don't necessarily // need to understand them all. while (!Stream.AtEndOfStream()) { unsigned Code = Stream.ReadCode(); if (Code != llvm::bitc::ENTER_SUBBLOCK) { Error("Invalid record at top-level"); return Failure; } unsigned BlockID = Stream.ReadSubBlockID(); // We only know the PCH subblock ID. switch (BlockID) { case llvm::bitc::BLOCKINFO_BLOCK_ID: if (Stream.ReadBlockInfoBlock()) { Error("Malformed BlockInfoBlock"); return Failure; } break; case pch::PCH_BLOCK_ID: switch (ReadPCHBlock()) { case Success: break; case Failure: return Failure; case IgnorePCH: // FIXME: We could consider reading through to the end of this // PCH block, skipping subblocks, to see if there are other // PCH blocks elsewhere. return IgnorePCH; } break; default: if (Stream.SkipBlock()) { Error("Malformed block record"); return Failure; } break; } } // Load the translation unit declaration ReadDeclRecord(DeclOffsets[0], 0); return Success; } namespace { /// \brief Helper class that saves the current stream position and /// then restores it when destroyed. struct VISIBILITY_HIDDEN SavedStreamPosition { explicit SavedStreamPosition(llvm::BitstreamReader &Stream) : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { } ~SavedStreamPosition() { Stream.JumpToBit(Offset); } private: llvm::BitstreamReader &Stream; uint64_t Offset; }; } /// \brief Parse the record that corresponds to a LangOptions data /// structure. /// /// This routine compares the language options used to generate the /// PCH file against the language options set for the current /// compilation. For each option, we classify differences between the /// two compiler states as either "benign" or "important". Benign /// differences don't matter, and we accept them without complaint /// (and without modifying the language options). Differences between /// the states for important options cause the PCH file to be /// unusable, so we emit a warning and return true to indicate that /// there was an error. /// /// \returns true if the PCH file is unacceptable, false otherwise. bool PCHReader::ParseLanguageOptions( const llvm::SmallVectorImpl<uint64_t> &Record) { const LangOptions &LangOpts = Context.getLangOptions(); #define PARSE_LANGOPT_BENIGN(Option) ++Idx #define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \ if (Record[Idx] != LangOpts.Option) { \ Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \ Diag(diag::note_ignoring_pch) << FileName; \ return true; \ } \ ++Idx unsigned Idx = 0; PARSE_LANGOPT_BENIGN(Trigraphs); PARSE_LANGOPT_BENIGN(BCPLComment); PARSE_LANGOPT_BENIGN(DollarIdents); PARSE_LANGOPT_BENIGN(AsmPreprocessor); PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions); PARSE_LANGOPT_BENIGN(ImplicitInt); PARSE_LANGOPT_BENIGN(Digraphs); PARSE_LANGOPT_BENIGN(HexFloats); PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99); PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions); PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus); PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x); PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions); PARSE_LANGOPT_BENIGN(CXXOperatorName); PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c); PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2); PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi); PARSE_LANGOPT_BENIGN(PascalStrings); PARSE_LANGOPT_BENIGN(Boolean); PARSE_LANGOPT_BENIGN(WritableStrings); PARSE_LANGOPT_IMPORTANT(LaxVectorConversions, diag::warn_pch_lax_vector_conversions); PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions); PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime); PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding); PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins); PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics, diag::warn_pch_thread_safe_statics); PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks); PARSE_LANGOPT_BENIGN(EmitAllDecls); PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno); PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking); PARSE_LANGOPT_IMPORTANT(HeinousExtensions, diag::warn_pch_heinous_extensions); // FIXME: Most of the options below are benign if the macro wasn't // used. Unfortunately, this means that a PCH compiled without // optimization can't be used with optimization turned on, even // though the only thing that changes is whether __OPTIMIZE__ was // defined... but if __OPTIMIZE__ never showed up in the header, it // doesn't matter. We could consider making this some special kind // of check. PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize); PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size); PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static); PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level); PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline); PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline); if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) { Diag(diag::warn_pch_gc_mode) << (unsigned)Record[Idx] << LangOpts.getGCMode(); Diag(diag::note_ignoring_pch) << FileName; return true; } ++Idx; PARSE_LANGOPT_BENIGN(getVisibilityMode()); PARSE_LANGOPT_BENIGN(InstantiationDepth); #undef PARSE_LANGOPT_IRRELEVANT #undef PARSE_LANGOPT_BENIGN return false; } /// \brief Read and return the type at the given offset. /// /// This routine actually reads the record corresponding to the type /// at the given offset in the bitstream. It is a helper routine for /// GetType, which deals with reading type IDs. QualType PCHReader::ReadTypeRecord(uint64_t Offset) { // Keep track of where we are in the stream, then jump back there // after reading this type. SavedStreamPosition SavedPosition(Stream); Stream.JumpToBit(Offset); RecordData Record; unsigned Code = Stream.ReadCode(); switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) { case pch::TYPE_EXT_QUAL: { assert(Record.size() == 3 && "Incorrect encoding of extended qualifier type"); QualType Base = GetType(Record[0]); QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1]; unsigned AddressSpace = Record[2]; QualType T = Base; if (GCAttr != QualType::GCNone) T = Context.getObjCGCQualType(T, GCAttr); if (AddressSpace) T = Context.getAddrSpaceQualType(T, AddressSpace); return T; } case pch::TYPE_FIXED_WIDTH_INT: { assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type"); return Context.getFixedWidthIntType(Record[0], Record[1]); } case pch::TYPE_COMPLEX: { assert(Record.size() == 1 && "Incorrect encoding of complex type"); QualType ElemType = GetType(Record[0]); return Context.getComplexType(ElemType); } case pch::TYPE_POINTER: { assert(Record.size() == 1 && "Incorrect encoding of pointer type"); QualType PointeeType = GetType(Record[0]); return Context.getPointerType(PointeeType); } case pch::TYPE_BLOCK_POINTER: { assert(Record.size() == 1 && "Incorrect encoding of block pointer type"); QualType PointeeType = GetType(Record[0]); return Context.getBlockPointerType(PointeeType); } case pch::TYPE_LVALUE_REFERENCE: { assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type"); QualType PointeeType = GetType(Record[0]); return Context.getLValueReferenceType(PointeeType); } case pch::TYPE_RVALUE_REFERENCE: { assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type"); QualType PointeeType = GetType(Record[0]); return Context.getRValueReferenceType(PointeeType); } case pch::TYPE_MEMBER_POINTER: { assert(Record.size() == 1 && "Incorrect encoding of member pointer type"); QualType PointeeType = GetType(Record[0]); QualType ClassType = GetType(Record[1]); return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr()); } case pch::TYPE_CONSTANT_ARRAY: { QualType ElementType = GetType(Record[0]); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; unsigned Idx = 3; llvm::APInt Size = ReadAPInt(Record, Idx); return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals); } case pch::TYPE_INCOMPLETE_ARRAY: { QualType ElementType = GetType(Record[0]); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals); } case pch::TYPE_VARIABLE_ARRAY: { QualType ElementType = GetType(Record[0]); ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1]; unsigned IndexTypeQuals = Record[2]; return Context.getVariableArrayType(ElementType, ReadExpr(), ASM, IndexTypeQuals); } case pch::TYPE_VECTOR: { if (Record.size() != 2) { Error("Incorrect encoding of vector type in PCH file"); return QualType(); } QualType ElementType = GetType(Record[0]); unsigned NumElements = Record[1]; return Context.getVectorType(ElementType, NumElements); } case pch::TYPE_EXT_VECTOR: { if (Record.size() != 2) { Error("Incorrect encoding of extended vector type in PCH file"); return QualType(); } QualType ElementType = GetType(Record[0]); unsigned NumElements = Record[1]; return Context.getExtVectorType(ElementType, NumElements); } case pch::TYPE_FUNCTION_NO_PROTO: { if (Record.size() != 1) { Error("Incorrect encoding of no-proto function type"); return QualType(); } QualType ResultType = GetType(Record[0]); return Context.getFunctionNoProtoType(ResultType); } case pch::TYPE_FUNCTION_PROTO: { QualType ResultType = GetType(Record[0]); unsigned Idx = 1; unsigned NumParams = Record[Idx++]; llvm::SmallVector<QualType, 16> ParamTypes; for (unsigned I = 0; I != NumParams; ++I) ParamTypes.push_back(GetType(Record[Idx++])); bool isVariadic = Record[Idx++]; unsigned Quals = Record[Idx++]; return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams, isVariadic, Quals); } case pch::TYPE_TYPEDEF: assert(Record.size() == 1 && "Incorrect encoding of typedef type"); return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0]))); case pch::TYPE_TYPEOF_EXPR: return Context.getTypeOfExprType(ReadExpr()); case pch::TYPE_TYPEOF: { if (Record.size() != 1) { Error("Incorrect encoding of typeof(type) in PCH file"); return QualType(); } QualType UnderlyingType = GetType(Record[0]); return Context.getTypeOfType(UnderlyingType); } case pch::TYPE_RECORD: assert(Record.size() == 1 && "Incorrect encoding of record type"); return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0]))); case pch::TYPE_ENUM: assert(Record.size() == 1 && "Incorrect encoding of enum type"); return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0]))); case pch::TYPE_OBJC_INTERFACE: // FIXME: Deserialize ObjCInterfaceType assert(false && "Cannot de-serialize ObjC interface types yet"); return QualType(); case pch::TYPE_OBJC_QUALIFIED_INTERFACE: // FIXME: Deserialize ObjCQualifiedInterfaceType assert(false && "Cannot de-serialize ObjC qualified interface types yet"); return QualType(); case pch::TYPE_OBJC_QUALIFIED_ID: // FIXME: Deserialize ObjCQualifiedIdType assert(false && "Cannot de-serialize ObjC qualified id types yet"); return QualType(); case pch::TYPE_OBJC_QUALIFIED_CLASS: // FIXME: Deserialize ObjCQualifiedClassType assert(false && "Cannot de-serialize ObjC qualified class types yet"); return QualType(); } // Suppress a GCC warning return QualType(); } /// \brief Note that we have loaded the declaration with the given /// Index. /// /// This routine notes that this declaration has already been loaded, /// so that future GetDecl calls will return this declaration rather /// than trying to load a new declaration. inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) { assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?"); DeclAlreadyLoaded[Index] = true; DeclOffsets[Index] = reinterpret_cast<uint64_t>(D); } /// \brief Read the declaration at the given offset from the PCH file. Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) { // Keep track of where we are in the stream, then jump back there // after reading this declaration. SavedStreamPosition SavedPosition(Stream); Decl *D = 0; Stream.JumpToBit(Offset); RecordData Record; unsigned Code = Stream.ReadCode(); unsigned Idx = 0; PCHDeclReader Reader(*this, Record, Idx); switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) { case pch::DECL_ATTR: case pch::DECL_CONTEXT_LEXICAL: case pch::DECL_CONTEXT_VISIBLE: assert(false && "Record cannot be de-serialized with ReadDeclRecord"); break; case pch::DECL_TRANSLATION_UNIT: assert(Index == 0 && "Translation unit must be at index 0"); Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl()); D = Context.getTranslationUnitDecl(); LoadedDecl(Index, D); break; case pch::DECL_TYPEDEF: { TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(), 0, QualType()); LoadedDecl(Index, Typedef); Reader.VisitTypedefDecl(Typedef); D = Typedef; break; } case pch::DECL_ENUM: { EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0); LoadedDecl(Index, Enum); Reader.VisitEnumDecl(Enum); D = Enum; break; } case pch::DECL_RECORD: { RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct, 0, SourceLocation(), 0, 0); LoadedDecl(Index, Record); Reader.VisitRecordDecl(Record); D = Record; break; } case pch::DECL_ENUM_CONSTANT: { EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0, SourceLocation(), 0, QualType(), 0, llvm::APSInt()); LoadedDecl(Index, ECD); Reader.VisitEnumConstantDecl(ECD); D = ECD; break; } case pch::DECL_FUNCTION: { FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(), DeclarationName(), QualType()); LoadedDecl(Index, Function); Reader.VisitFunctionDecl(Function); D = Function; break; } case pch::DECL_FIELD: { FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0, QualType(), 0, false); LoadedDecl(Index, Field); Reader.VisitFieldDecl(Field); D = Field; break; } case pch::DECL_VAR: { VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(), VarDecl::None, SourceLocation()); LoadedDecl(Index, Var); Reader.VisitVarDecl(Var); D = Var; break; } case pch::DECL_PARM_VAR: { ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0, QualType(), VarDecl::None, 0); LoadedDecl(Index, Parm); Reader.VisitParmVarDecl(Parm); D = Parm; break; } case pch::DECL_ORIGINAL_PARM_VAR: { OriginalParmVarDecl *Parm = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0, QualType(), QualType(), VarDecl::None, 0); LoadedDecl(Index, Parm); Reader.VisitOriginalParmVarDecl(Parm); D = Parm; break; } case pch::DECL_FILE_SCOPE_ASM: { FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0, SourceLocation(), 0); LoadedDecl(Index, Asm); Reader.VisitFileScopeAsmDecl(Asm); D = Asm; break; } case pch::DECL_BLOCK: { BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation()); LoadedDecl(Index, Block); Reader.VisitBlockDecl(Block); D = Block; break; } } // If this declaration is also a declaration context, get the // offsets for its tables of lexical and visible declarations. if (DeclContext *DC = dyn_cast<DeclContext>(D)) { std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC); if (Offsets.first || Offsets.second) { DC->setHasExternalLexicalStorage(Offsets.first != 0); DC->setHasExternalVisibleStorage(Offsets.second != 0); DeclContextOffsets[DC] = Offsets; } } assert(Idx == Record.size()); return D; } QualType PCHReader::GetType(pch::TypeID ID) { unsigned Quals = ID & 0x07; unsigned Index = ID >> 3; if (Index < pch::NUM_PREDEF_TYPE_IDS) { QualType T; switch ((pch::PredefinedTypeIDs)Index) { case pch::PREDEF_TYPE_NULL_ID: return QualType(); case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break; case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break; case pch::PREDEF_TYPE_CHAR_U_ID: case pch::PREDEF_TYPE_CHAR_S_ID: // FIXME: Check that the signedness of CharTy is correct! T = Context.CharTy; break; case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break; case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break; case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break; case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break; case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break; case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break; case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break; case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break; case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break; case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break; case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break; case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break; case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break; case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break; case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break; case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break; } assert(!T.isNull() && "Unknown predefined type"); return T.getQualifiedType(Quals); } Index -= pch::NUM_PREDEF_TYPE_IDS; if (!TypeAlreadyLoaded[Index]) { // Load the type from the PCH file. TypeOffsets[Index] = reinterpret_cast<uint64_t>( ReadTypeRecord(TypeOffsets[Index]).getTypePtr()); TypeAlreadyLoaded[Index] = true; } return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals); } Decl *PCHReader::GetDecl(pch::DeclID ID) { if (ID == 0) return 0; unsigned Index = ID - 1; if (DeclAlreadyLoaded[Index]) return reinterpret_cast<Decl *>(DeclOffsets[Index]); // Load the declaration from the PCH file. return ReadDeclRecord(DeclOffsets[Index], Index); } bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC, llvm::SmallVectorImpl<pch::DeclID> &Decls) { assert(DC->hasExternalLexicalStorage() && "DeclContext has no lexical decls in storage"); uint64_t Offset = DeclContextOffsets[DC].first; assert(Offset && "DeclContext has no lexical decls in storage"); // Keep track of where we are in the stream, then jump back there // after reading this context. SavedStreamPosition SavedPosition(Stream); // Load the record containing all of the declarations lexically in // this context. Stream.JumpToBit(Offset); RecordData Record; unsigned Code = Stream.ReadCode(); unsigned RecCode = Stream.ReadRecord(Code, Record); (void)RecCode; assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block"); // Load all of the declaration IDs Decls.clear(); Decls.insert(Decls.end(), Record.begin(), Record.end()); return false; } bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC, llvm::SmallVectorImpl<VisibleDeclaration> & Decls) { assert(DC->hasExternalVisibleStorage() && "DeclContext has no visible decls in storage"); uint64_t Offset = DeclContextOffsets[DC].second; assert(Offset && "DeclContext has no visible decls in storage"); // Keep track of where we are in the stream, then jump back there // after reading this context. SavedStreamPosition SavedPosition(Stream); // Load the record containing all of the declarations visible in // this context. Stream.JumpToBit(Offset); RecordData Record; unsigned Code = Stream.ReadCode(); unsigned RecCode = Stream.ReadRecord(Code, Record); (void)RecCode; assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block"); if (Record.size() == 0) return false; Decls.clear(); unsigned Idx = 0; while (Idx < Record.size()) { Decls.push_back(VisibleDeclaration()); Decls.back().Name = ReadDeclarationName(Record, Idx); unsigned Size = Record[Idx++]; llvm::SmallVector<unsigned, 4> & LoadedDecls = Decls.back().Declarations; LoadedDecls.reserve(Size); for (unsigned I = 0; I < Size; ++I) LoadedDecls.push_back(Record[Idx++]); } return false; } void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) { if (!Consumer) return; for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) { Decl *D = GetDecl(ExternalDefinitions[I]); DeclGroupRef DG(D); Consumer->HandleTopLevelDecl(DG); } } void PCHReader::PrintStats() { std::fprintf(stderr, "*** PCH Statistics:\n"); unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(), TypeAlreadyLoaded.end(), true); unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(), DeclAlreadyLoaded.end(), true); unsigned NumIdentifiersLoaded = 0; for (unsigned I = 0; I < IdentifierData.size(); ++I) { if ((IdentifierData[I] & 0x01) == 0) ++NumIdentifiersLoaded; } std::fprintf(stderr, " %u/%u types read (%f%%)\n", NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(), ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100)); std::fprintf(stderr, " %u/%u declarations read (%f%%)\n", NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(), ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100)); std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n", NumIdentifiersLoaded, (unsigned)IdentifierData.size(), ((float)NumIdentifiersLoaded/IdentifierData.size() * 100)); std::fprintf(stderr, "\n"); } IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) { if (ID == 0) return 0; if (!IdentifierTable || IdentifierData.empty()) { Error("No identifier table in PCH file"); return 0; } if (IdentifierData[ID - 1] & 0x01) { uint64_t Offset = IdentifierData[ID - 1]; IdentifierData[ID - 1] = reinterpret_cast<uint64_t>( &Context.Idents.get(IdentifierTable + Offset)); } return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]); } DeclarationName PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) { DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++]; switch (Kind) { case DeclarationName::Identifier: return DeclarationName(GetIdentifierInfo(Record, Idx)); case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: assert(false && "Unable to de-serialize Objective-C selectors"); break; case DeclarationName::CXXConstructorName: return Context.DeclarationNames.getCXXConstructorName( GetType(Record[Idx++])); case DeclarationName::CXXDestructorName: return Context.DeclarationNames.getCXXDestructorName( GetType(Record[Idx++])); case DeclarationName::CXXConversionFunctionName: return Context.DeclarationNames.getCXXConversionFunctionName( GetType(Record[Idx++])); case DeclarationName::CXXOperatorName: return Context.DeclarationNames.getCXXOperatorName( (OverloadedOperatorKind)Record[Idx++]); case DeclarationName::CXXUsingDirective: return DeclarationName::getUsingDirectiveName(); } // Required to silence GCC warning return DeclarationName(); } /// \brief Read an integral value llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) { unsigned BitWidth = Record[Idx++]; unsigned NumWords = llvm::APInt::getNumWords(BitWidth); llvm::APInt Result(BitWidth, NumWords, &Record[Idx]); Idx += NumWords; return Result; } /// \brief Read a signed integral value llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) { bool isUnsigned = Record[Idx++]; return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned); } /// \brief Read a floating-point value llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) { return llvm::APFloat(ReadAPInt(Record, Idx)); } // \brief Read a string std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) { unsigned Len = Record[Idx++]; std::string Result(&Record[Idx], &Record[Idx] + Len); Idx += Len; return Result; } /// \brief Reads attributes from the current stream position. Attr *PCHReader::ReadAttributes() { unsigned Code = Stream.ReadCode(); assert(Code == llvm::bitc::UNABBREV_RECORD && "Expected unabbreviated record"); (void)Code; RecordData Record; unsigned Idx = 0; unsigned RecCode = Stream.ReadRecord(Code, Record); assert(RecCode == pch::DECL_ATTR && "Expected attribute record"); (void)RecCode; #define SIMPLE_ATTR(Name) \ case Attr::Name: \ New = ::new (Context) Name##Attr(); \ break #define STRING_ATTR(Name) \ case Attr::Name: \ New = ::new (Context) Name##Attr(ReadString(Record, Idx)); \ break #define UNSIGNED_ATTR(Name) \ case Attr::Name: \ New = ::new (Context) Name##Attr(Record[Idx++]); \ break Attr *Attrs = 0; while (Idx < Record.size()) { Attr *New = 0; Attr::Kind Kind = (Attr::Kind)Record[Idx++]; bool IsInherited = Record[Idx++]; switch (Kind) { STRING_ATTR(Alias); UNSIGNED_ATTR(Aligned); SIMPLE_ATTR(AlwaysInline); SIMPLE_ATTR(AnalyzerNoReturn); STRING_ATTR(Annotate); STRING_ATTR(AsmLabel); case Attr::Blocks: New = ::new (Context) BlocksAttr( (BlocksAttr::BlocksAttrTypes)Record[Idx++]); break; case Attr::Cleanup: New = ::new (Context) CleanupAttr( cast<FunctionDecl>(GetDecl(Record[Idx++]))); break; SIMPLE_ATTR(Const); UNSIGNED_ATTR(Constructor); SIMPLE_ATTR(DLLExport); SIMPLE_ATTR(DLLImport); SIMPLE_ATTR(Deprecated); UNSIGNED_ATTR(Destructor); SIMPLE_ATTR(FastCall); case Attr::Format: { std::string Type = ReadString(Record, Idx); unsigned FormatIdx = Record[Idx++]; unsigned FirstArg = Record[Idx++]; New = ::new (Context) FormatAttr(Type, FormatIdx, FirstArg); break; } SIMPLE_ATTR(GNUCInline); case Attr::IBOutletKind: New = ::new (Context) IBOutletAttr(); break; SIMPLE_ATTR(NoReturn); SIMPLE_ATTR(NoThrow); SIMPLE_ATTR(Nodebug); SIMPLE_ATTR(Noinline); case Attr::NonNull: { unsigned Size = Record[Idx++]; llvm::SmallVector<unsigned, 16> ArgNums; ArgNums.insert(ArgNums.end(), &Record[Idx], &Record[Idx] + Size); Idx += Size; New = ::new (Context) NonNullAttr(&ArgNums[0], Size); break; } SIMPLE_ATTR(ObjCException); SIMPLE_ATTR(ObjCNSObject); SIMPLE_ATTR(Overloadable); UNSIGNED_ATTR(Packed); SIMPLE_ATTR(Pure); UNSIGNED_ATTR(Regparm); STRING_ATTR(Section); SIMPLE_ATTR(StdCall); SIMPLE_ATTR(TransparentUnion); SIMPLE_ATTR(Unavailable); SIMPLE_ATTR(Unused); SIMPLE_ATTR(Used); case Attr::Visibility: New = ::new (Context) VisibilityAttr( (VisibilityAttr::VisibilityTypes)Record[Idx++]); break; SIMPLE_ATTR(WarnUnusedResult); SIMPLE_ATTR(Weak); SIMPLE_ATTR(WeakImport); } assert(New && "Unable to decode attribute?"); New->setInherited(IsInherited); New->setNext(Attrs); Attrs = New; } #undef UNSIGNED_ATTR #undef STRING_ATTR #undef SIMPLE_ATTR // The list of attributes was built backwards. Reverse the list // before returning it. Attr *PrevAttr = 0, *NextAttr = 0; while (Attrs) { NextAttr = Attrs->getNext(); Attrs->setNext(PrevAttr); PrevAttr = Attrs; Attrs = NextAttr; } return PrevAttr; } Expr *PCHReader::ReadExpr() { // Within the bitstream, expressions are stored in Reverse Polish // Notation, with each of the subexpressions preceding the // expression they are stored in. To evaluate expressions, we // continue reading expressions and placing them on the stack, with // expressions having operands removing those operands from the // stack. Evaluation terminates when we see a EXPR_STOP record, and // the single remaining expression on the stack is our result. RecordData Record; unsigned Idx; llvm::SmallVector<Expr *, 16> ExprStack; PCHStmtReader Reader(*this, Record, Idx, ExprStack); Stmt::EmptyShell Empty; while (true) { unsigned Code = Stream.ReadCode(); if (Code == llvm::bitc::END_BLOCK) { if (Stream.ReadBlockEnd()) { Error("Error at end of Source Manager block"); return 0; } break; } if (Code == llvm::bitc::ENTER_SUBBLOCK) { // No known subblocks, always skip them. Stream.ReadSubBlockID(); if (Stream.SkipBlock()) { Error("Malformed block record"); return 0; } continue; } if (Code == llvm::bitc::DEFINE_ABBREV) { Stream.ReadAbbrevRecord(); continue; } Expr *E = 0; Idx = 0; Record.clear(); bool Finished = false; switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) { case pch::EXPR_STOP: Finished = true; break; case pch::EXPR_NULL: E = 0; break; case pch::EXPR_PREDEFINED: // FIXME: untested (until we can serialize function bodies). E = new (Context) PredefinedExpr(Empty); break; case pch::EXPR_DECL_REF: E = new (Context) DeclRefExpr(Empty); break; case pch::EXPR_INTEGER_LITERAL: E = new (Context) IntegerLiteral(Empty); break; case pch::EXPR_FLOATING_LITERAL: E = new (Context) FloatingLiteral(Empty); break; case pch::EXPR_IMAGINARY_LITERAL: E = new (Context) ImaginaryLiteral(Empty); break; case pch::EXPR_STRING_LITERAL: E = StringLiteral::CreateEmpty(Context, Record[PCHStmtReader::NumExprFields + 1]); break; case pch::EXPR_CHARACTER_LITERAL: E = new (Context) CharacterLiteral(Empty); break; case pch::EXPR_PAREN: E = new (Context) ParenExpr(Empty); break; case pch::EXPR_UNARY_OPERATOR: E = new (Context) UnaryOperator(Empty); break; case pch::EXPR_SIZEOF_ALIGN_OF: E = new (Context) SizeOfAlignOfExpr(Empty); break; case pch::EXPR_ARRAY_SUBSCRIPT: E = new (Context) ArraySubscriptExpr(Empty); break; case pch::EXPR_CALL: E = new (Context) CallExpr(Context, Empty); break; case pch::EXPR_MEMBER: E = new (Context) MemberExpr(Empty); break; case pch::EXPR_BINARY_OPERATOR: E = new (Context) BinaryOperator(Empty); break; case pch::EXPR_COMPOUND_ASSIGN_OPERATOR: E = new (Context) CompoundAssignOperator(Empty); break; case pch::EXPR_CONDITIONAL_OPERATOR: E = new (Context) ConditionalOperator(Empty); break; case pch::EXPR_IMPLICIT_CAST: E = new (Context) ImplicitCastExpr(Empty); break; case pch::EXPR_CSTYLE_CAST: E = new (Context) CStyleCastExpr(Empty); break; case pch::EXPR_COMPOUND_LITERAL: E = new (Context) CompoundLiteralExpr(Empty); break; case pch::EXPR_EXT_VECTOR_ELEMENT: E = new (Context) ExtVectorElementExpr(Empty); break; case pch::EXPR_INIT_LIST: E = new (Context) InitListExpr(Empty); break; case pch::EXPR_DESIGNATED_INIT: E = DesignatedInitExpr::CreateEmpty(Context, Record[PCHStmtReader::NumExprFields] - 1); break; case pch::EXPR_IMPLICIT_VALUE_INIT: E = new (Context) ImplicitValueInitExpr(Empty); break; case pch::EXPR_VA_ARG: // FIXME: untested; we need function bodies first E = new (Context) VAArgExpr(Empty); break; case pch::EXPR_TYPES_COMPATIBLE: E = new (Context) TypesCompatibleExpr(Empty); break; case pch::EXPR_CHOOSE: E = new (Context) ChooseExpr(Empty); break; case pch::EXPR_GNU_NULL: E = new (Context) GNUNullExpr(Empty); break; case pch::EXPR_SHUFFLE_VECTOR: E = new (Context) ShuffleVectorExpr(Empty); break; case pch::EXPR_BLOCK_DECL_REF: // FIXME: untested until we have statement and block support E = new (Context) BlockDeclRefExpr(Empty); break; } // We hit an EXPR_STOP, so we're done with this expression. if (Finished) break; if (E) { unsigned NumSubExprs = Reader.Visit(E); while (NumSubExprs > 0) { ExprStack.pop_back(); --NumSubExprs; } } assert(Idx == Record.size() && "Invalid deserialization of expression"); ExprStack.push_back(E); } assert(ExprStack.size() == 1 && "Extra expressions on stack!"); return ExprStack.back(); } DiagnosticBuilder PCHReader::Diag(unsigned DiagID) { return Diag(SourceLocation(), DiagID); } DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) { return PP.getDiagnostics().Report(FullSourceLoc(Loc, Context.getSourceManager()), DiagID); } <file_sep>/test/CodeGen/unwind-attr.c // RUN: clang-cc -fexceptions -emit-llvm -o - %s | grep "@foo() {" | count 1 && // RUN: clang-cc -emit-llvm -o - %s | grep "@foo() nounwind {" | count 1 int foo(void) { } <file_sep>/test/CodeGen/dllimport-dllexport.c // RUN: clang-cc -emit-llvm < %s -o %t && // RUN: grep 'dllexport' %t | count 1 && // RUN: not grep 'dllimport' %t void __attribute__((dllimport)) foo1(); void __attribute__((dllexport)) foo1(){} void __attribute__((dllexport)) foo2(); <file_sep>/lib/Sema/SemaExprObjC.cpp //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for Objective-C expressions. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ExprObjC.h" #include "llvm/ADT/SmallString.h" #include "clang/Lex/Preprocessor.h" using namespace clang; Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, ExprTy **strings, unsigned NumStrings) { StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings); // Most ObjC strings are formed out of a single piece. However, we *can* // have strings formed out of multiple @ strings with multiple pptokens in // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one // StringLiteral for ObjCStringLiteral to hold onto. StringLiteral *S = Strings[0]; // If we have a multi-part string, merge it all together. if (NumStrings != 1) { // Concatenate objc strings. llvm::SmallString<128> StrBuf; llvm::SmallVector<SourceLocation, 8> StrLocs; for (unsigned i = 0; i != NumStrings; ++i) { S = Strings[i]; // ObjC strings can't be wide. if (S->isWide()) { Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant) << S->getSourceRange(); return true; } // Get the string data. StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength()); // Get the locations of the string tokens. StrLocs.append(S->tokloc_begin(), S->tokloc_end()); // Free the temporary string. S->Destroy(Context); } // Create the aggregate string with the appropriate content and location // information. S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false, Context.getPointerType(Context.CharTy), &StrLocs[0], StrLocs.size()); } // Verify that this composite string is acceptable for ObjC strings. if (CheckObjCString(S)) return true; // Initialize the constant string interface lazily. This assumes // the NSString interface is seen in this translation unit. Note: We // don't use NSConstantString, since the runtime team considers this // interface private (even though it appears in the header files). QualType Ty = Context.getObjCConstantStringInterface(); if (!Ty.isNull()) { Ty = Context.getPointerType(Ty); } else { IdentifierInfo *NSIdent = &Context.Idents.get("NSString"); NamedDecl *IF = LookupName(TUScope, NSIdent, LookupOrdinaryName); if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { Context.setObjCConstantStringInterface(StrIF); Ty = Context.getObjCConstantStringInterface(); Ty = Context.getPointerType(Ty); } else { // If there is no NSString interface defined then treat constant // strings as untyped objects and let the runtime figure it out later. Ty = Context.getObjCIdType(); } } return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]); } Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, TypeTy *ty, SourceLocation RParenLoc) { QualType EncodedType = QualType::getFromOpaquePtr(ty); std::string Str; Context.getObjCEncodingForType(EncodedType, Str); // The type of @encode is the same as the type of the corresponding string, // which is an array type. QualType StrTy = Context.CharTy; // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). if (getLangOptions().CPlusPlus) StrTy.addConst(); StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1), ArrayType::Normal, 0); return new (Context) ObjCEncodeExpr(StrTy, EncodedType, AtLoc, RParenLoc); } Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { QualType Ty = Context.getObjCSelType(); return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); } Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { ObjCProtocolDecl* PDecl = ObjCProtocols[ProtocolId]; if (!PDecl) { Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; return true; } QualType Ty = Context.getObjCProtoType(); if (Ty.isNull()) return true; Ty = Context.getPointerType(Ty); return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc); } bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs, Selector Sel, ObjCMethodDecl *Method, bool isClassMessage, SourceLocation lbrac, SourceLocation rbrac, QualType &ReturnType) { if (!Method) { // Apply default argument promotion as for (C99 6.5.2.2p6). for (unsigned i = 0; i != NumArgs; i++) DefaultArgumentPromotion(Args[i]); unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found : diag::warn_inst_method_not_found; Diag(lbrac, DiagID) << Sel << isClassMessage << SourceRange(lbrac, rbrac); ReturnType = Context.getObjCIdType(); return false; } ReturnType = Method->getResultType(); unsigned NumNamedArgs = Sel.getNumArgs(); assert(NumArgs >= NumNamedArgs && "Too few arguments for selector!"); bool IsError = false; for (unsigned i = 0; i < NumNamedArgs; i++) { Expr *argExpr = Args[i]; assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); QualType lhsType = Method->param_begin()[i]->getType(); QualType rhsType = argExpr->getType(); // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8]. if (lhsType->isArrayType()) lhsType = Context.getArrayDecayedType(lhsType); else if (lhsType->isFunctionType()) lhsType = Context.getPointerType(lhsType); AssignConvertType Result = CheckSingleAssignmentConstraints(lhsType, argExpr); if (Args[i] != argExpr) // The expression was converted. Args[i] = argExpr; // Make sure we store the converted expression. IsError |= DiagnoseAssignmentResult(Result, argExpr->getLocStart(), lhsType, rhsType, argExpr, "sending"); } // Promote additional arguments to variadic methods. if (Method->isVariadic()) { for (unsigned i = NumNamedArgs; i < NumArgs; ++i) IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod); } else { // Check for extra arguments to non-variadic methods. if (NumArgs != NumNamedArgs) { Diag(Args[NumNamedArgs]->getLocStart(), diag::err_typecheck_call_too_many_args) << 2 /*method*/ << Method->getSourceRange() << SourceRange(Args[NumNamedArgs]->getLocStart(), Args[NumArgs-1]->getLocEnd()); } } return IsError; } bool Sema::isSelfExpr(Expr *RExpr) { if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr)) if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self")) return true; return false; } // Helper method for ActOnClassMethod/ActOnInstanceMethod. // Will search "local" class/category implementations for a method decl. // If failed, then we search in class's root for an instance method. // Returns 0 if no method is found. ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel, ObjCInterfaceDecl *ClassDecl) { ObjCMethodDecl *Method = 0; // lookup in class and all superclasses while (ClassDecl && !Method) { if (ObjCImplementationDecl *ImpDecl = ObjCImplementations[ClassDecl->getIdentifier()]) Method = ImpDecl->getClassMethod(Sel); // Look through local category implementations associated with the class. if (!Method) { for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) { if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl) Method = ObjCCategoryImpls[i]->getClassMethod(Sel); } } // Before we give up, check if the selector is an instance method. // But only in the root. This matches gcc's behaviour and what the // runtime expects. if (!Method && !ClassDecl->getSuperClass()) { Method = ClassDecl->lookupInstanceMethod(Context, Sel); // Look through local category implementations associated // with the root class. if (!Method) Method = LookupPrivateInstanceMethod(Sel, ClassDecl); } ClassDecl = ClassDecl->getSuperClass(); } return Method; } ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel, ObjCInterfaceDecl *ClassDecl) { ObjCMethodDecl *Method = 0; while (ClassDecl && !Method) { // If we have implementations in scope, check "private" methods. if (ObjCImplementationDecl *ImpDecl = ObjCImplementations[ClassDecl->getIdentifier()]) Method = ImpDecl->getInstanceMethod(Sel); // Look through local category implementations associated with the class. if (!Method) { for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) { if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl) Method = ObjCCategoryImpls[i]->getInstanceMethod(Sel); } } ClassDecl = ClassDecl->getSuperClass(); } return Method; } Action::OwningExprResult Sema::ActOnClassPropertyRefExpr( IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation &receiverNameLoc, SourceLocation &propertyNameLoc) { ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(&receiverName); // Search for a declared property first. Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName); ObjCMethodDecl *Getter = IFace->lookupClassMethod(Context, Sel); // If this reference is in an @implementation, check for 'private' methods. if (!Getter) if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) if (ObjCImplementationDecl *ImpDecl = ObjCImplementations[ClassDecl->getIdentifier()]) Getter = ImpDecl->getClassMethod(Sel); if (Getter) { // FIXME: refactor/share with ActOnMemberReference(). // Check if we can reference this property. if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) return ExprError(); } // Look for the matching setter, in case it is needed. Selector SetterSel = SelectorTable::constructSetterName(PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName); ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel); if (!Setter) { // If this reference is in an @implementation, also check for 'private' // methods. if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) if (ObjCImplementationDecl *ImpDecl = ObjCImplementations[ClassDecl->getIdentifier()]) Setter = ImpDecl->getClassMethod(SetterSel); } // Look through local category implementations associated with the class. if (!Setter) { for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { if (ObjCCategoryImpls[i]->getClassInterface() == IFace) Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel); } } if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) return ExprError(); if (Getter || Setter) { QualType PType; if (Getter) PType = Getter->getResultType(); else { for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), E = Setter->param_end(); PI != E; ++PI) PType = (*PI)->getType(); } return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, Setter, propertyNameLoc, IFace, receiverNameLoc)); } return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) << &propertyName << Context.getObjCInterfaceType(IFace)); } // ActOnClassMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from Sel.getNumArgs(). Sema::ExprResult Sema::ActOnClassMessage( Scope *S, IdentifierInfo *receiverName, Selector Sel, SourceLocation lbrac, SourceLocation receiverLoc, SourceLocation selectorLoc, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs) { assert(receiverName && "missing receiver class name"); Expr **ArgExprs = reinterpret_cast<Expr **>(Args); ObjCInterfaceDecl* ClassDecl = 0; bool isSuper = false; if (receiverName->isStr("super")) { if (getCurMethodDecl()) { isSuper = true; ObjCInterfaceDecl *OID = getCurMethodDecl()->getClassInterface(); if (!OID) return Diag(lbrac, diag::error_no_super_class_message) << getCurMethodDecl()->getDeclName(); ClassDecl = OID->getSuperClass(); if (!ClassDecl) return Diag(lbrac, diag::error_no_super_class) << OID->getDeclName(); if (getCurMethodDecl()->isInstanceMethod()) { QualType superTy = Context.getObjCInterfaceType(ClassDecl); superTy = Context.getPointerType(superTy); ExprResult ReceiverExpr = new (Context) ObjCSuperExpr(SourceLocation(), superTy); // We are really in an instance method, redirect. return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac, selectorLoc, rbrac, Args, NumArgs); } // We are sending a message to 'super' within a class method. Do nothing, // the receiver will pass through as 'super' (how convenient:-). } else { // 'super' has been used outside a method context. If a variable named // 'super' has been declared, redirect. If not, produce a diagnostic. NamedDecl *SuperDecl = LookupName(S, receiverName, LookupOrdinaryName); ValueDecl *VD = dyn_cast_or_null<ValueDecl>(SuperDecl); if (VD) { ExprResult ReceiverExpr = new (Context) DeclRefExpr(VD, VD->getType(), receiverLoc); // We are really in an instance method, redirect. return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac, selectorLoc, rbrac, Args, NumArgs); } return Diag(receiverLoc, diag::err_undeclared_var_use) << receiverName; } } else ClassDecl = getObjCInterfaceDecl(receiverName); // The following code allows for the following GCC-ism: // // typedef XCElementDisplayRect XCElementGraphicsRect; // // @implementation XCRASlice // - whatever { // Note that XCElementGraphicsRect is a typedef name. // _sGraphicsDelegate =[[XCElementGraphicsRect alloc] init]; // } // // If necessary, the following lookup could move to getObjCInterfaceDecl(). if (!ClassDecl) { NamedDecl *IDecl = LookupName(TUScope, receiverName, LookupOrdinaryName); if (TypedefDecl *OCTD = dyn_cast_or_null<TypedefDecl>(IDecl)) { const ObjCInterfaceType *OCIT; OCIT = OCTD->getUnderlyingType()->getAsObjCInterfaceType(); if (!OCIT) { Diag(receiverLoc, diag::err_invalid_receiver_to_message); return true; } ClassDecl = OCIT->getDecl(); } } assert(ClassDecl && "missing interface declaration"); ObjCMethodDecl *Method = 0; QualType returnType; Method = ClassDecl->lookupClassMethod(Context, Sel); // If we have an implementation in scope, check "private" methods. if (!Method) Method = LookupPrivateClassMethod(Sel, ClassDecl); if (Method && DiagnoseUseOfDecl(Method, receiverLoc)) return true; if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, true, lbrac, rbrac, returnType)) return true; // If we have the ObjCInterfaceDecl* for the class that is receiving // the message, use that to construct the ObjCMessageExpr. Otherwise // pass on the IdentifierInfo* for the class. // FIXME: need to do a better job handling 'super' usage within a class // For now, we simply pass the "super" identifier through (which isn't // consistent with instance methods. if (isSuper) return new (Context) ObjCMessageExpr(receiverName, Sel, returnType, Method, lbrac, rbrac, ArgExprs, NumArgs); else return new (Context) ObjCMessageExpr(ClassDecl, Sel, returnType, Method, lbrac, rbrac, ArgExprs, NumArgs); } // ActOnInstanceMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from Sel.getNumArgs(). Sema::ExprResult Sema::ActOnInstanceMessage(ExprTy *receiver, Selector Sel, SourceLocation lbrac, SourceLocation receiverLoc, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs) { assert(receiver && "missing receiver expression"); Expr **ArgExprs = reinterpret_cast<Expr **>(Args); Expr *RExpr = static_cast<Expr *>(receiver); QualType returnType; QualType ReceiverCType = Context.getCanonicalType(RExpr->getType()).getUnqualifiedType(); // Handle messages to 'super'. if (isa<ObjCSuperExpr>(RExpr)) { ObjCMethodDecl *Method = 0; if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { // If we have an interface in scope, check 'super' methods. if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) if (ObjCInterfaceDecl *SuperDecl = ClassDecl->getSuperClass()) { Method = SuperDecl->lookupInstanceMethod(Context, Sel); if (!Method) // If we have implementations in scope, check "private" methods. Method = LookupPrivateInstanceMethod(Sel, SuperDecl); } } if (Method && DiagnoseUseOfDecl(Method, receiverLoc)) return true; if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, lbrac, rbrac, returnType)) return true; return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac, ArgExprs, NumArgs); } // Handle messages to id. if (ReceiverCType == Context.getCanonicalType(Context.getObjCIdType()) || ReceiverCType->isBlockPointerType()) { ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool( Sel, SourceRange(lbrac,rbrac)); if (!Method) Method = FactoryMethodPool[Sel].Method; if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, lbrac, rbrac, returnType)) return true; return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac, ArgExprs, NumArgs); } // Handle messages to Class. if (ReceiverCType == Context.getCanonicalType(Context.getObjCClassType())) { ObjCMethodDecl *Method = 0; if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { // First check the public methods in the class interface. Method = ClassDecl->lookupClassMethod(Context, Sel); if (!Method) Method = LookupPrivateClassMethod(Sel, ClassDecl); } if (Method && DiagnoseUseOfDecl(Method, receiverLoc)) return true; } if (!Method) { // If not messaging 'self', look for any factory method named 'Sel'. if (!isSelfExpr(RExpr)) { Method = FactoryMethodPool[Sel].Method; if (!Method) { Method = LookupInstanceMethodInGlobalPool( Sel, SourceRange(lbrac,rbrac)); } } } if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, lbrac, rbrac, returnType)) return true; return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac, ArgExprs, NumArgs); } ObjCMethodDecl *Method = 0; ObjCInterfaceDecl* ClassDecl = 0; // We allow sending a message to a qualified ID ("id<foo>"), which is ok as // long as one of the protocols implements the selector (if not, warn). if (ObjCQualifiedIdType *QIT = dyn_cast<ObjCQualifiedIdType>(ReceiverCType)) { // Search protocols for instance methods. for (unsigned i = 0; i < QIT->getNumProtocols(); i++) { ObjCProtocolDecl *PDecl = QIT->getProtocols(i); if (PDecl && (Method = PDecl->lookupInstanceMethod(Context, Sel))) break; // Since we aren't supporting "Class<foo>", look for a class method. if (PDecl && (Method = PDecl->lookupClassMethod(Context, Sel))) break; } } else if (const ObjCInterfaceType *OCIType = ReceiverCType->getAsPointerToObjCInterfaceType()) { // We allow sending a message to a pointer to an interface (an object). ClassDecl = OCIType->getDecl(); // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be // faster than the following method (which can do *many* linear searches). // The idea is to add class info to InstanceMethodPool. Method = ClassDecl->lookupInstanceMethod(Context, Sel); if (!Method) { // Search protocol qualifiers. for (ObjCQualifiedInterfaceType::qual_iterator QI = OCIType->qual_begin(), E = OCIType->qual_end(); QI != E; ++QI) { if ((Method = (*QI)->lookupInstanceMethod(Context, Sel))) break; } } if (!Method) { // If we have implementations in scope, check "private" methods. Method = LookupPrivateInstanceMethod(Sel, ClassDecl); if (!Method && !isSelfExpr(RExpr)) { // If we still haven't found a method, look in the global pool. This // behavior isn't very desirable, however we need it for GCC // compatibility. FIXME: should we deviate?? if (OCIType->qual_empty()) { Method = LookupInstanceMethodInGlobalPool( Sel, SourceRange(lbrac,rbrac)); if (Method && !OCIType->getDecl()->isForwardDecl()) Diag(lbrac, diag::warn_maynot_respond) << OCIType->getDecl()->getIdentifier()->getName() << Sel; } } } if (Method && DiagnoseUseOfDecl(Method, receiverLoc)) return true; } else if (!Context.getObjCIdType().isNull() && (ReceiverCType->isPointerType() || (ReceiverCType->isIntegerType() && ReceiverCType->isScalarType()))) { // Implicitly convert integers and pointers to 'id' but emit a warning. Diag(lbrac, diag::warn_bad_receiver_type) << RExpr->getType() << RExpr->getSourceRange(); ImpCastExprToType(RExpr, Context.getObjCIdType()); } else { // Reject other random receiver types (e.g. structs). Diag(lbrac, diag::err_bad_receiver_type) << RExpr->getType() << RExpr->getSourceRange(); return true; } if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, lbrac, rbrac, returnType)) return true; return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac, ArgExprs, NumArgs); } //===----------------------------------------------------------------------===// // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. //===----------------------------------------------------------------------===// /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the /// inheritance hierarchy of 'rProto'. static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) { if (lProto == rProto) return true; for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), E = rProto->protocol_end(); PI != E; ++PI) if (ProtocolCompatibleWithProtocol(lProto, *PI)) return true; return false; } /// ClassImplementsProtocol - Checks that 'lProto' protocol /// has been implemented in IDecl class, its super class or categories (if /// lookupCategory is true). static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, ObjCInterfaceDecl *IDecl, bool lookupCategory, bool RHSIsQualifiedID = false) { // 1st, look up the class. const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(), E = Protocols.end(); PI != E; ++PI) { if (ProtocolCompatibleWithProtocol(lProto, *PI)) return true; // This is dubious and is added to be compatible with gcc. // In gcc, it is also allowed assigning a protocol-qualified 'id' // type to a LHS object when protocol in qualified LHS is in list // of protocols in the rhs 'id' object. This IMO, should be a bug. // FIXME: Treat this as an extension, and flag this as an error when // GCC extensions are not enabled. if (RHSIsQualifiedID && ProtocolCompatibleWithProtocol(*PI, lProto)) return true; } // 2nd, look up the category. if (lookupCategory) for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl; CDecl = CDecl->getNextClassCategory()) { for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(), E = CDecl->protocol_end(); PI != E; ++PI) if (ProtocolCompatibleWithProtocol(lProto, *PI)) return true; } // 3rd, look up the super class(s) if (IDecl->getSuperClass()) return ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory, RHSIsQualifiedID); return false; } /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an /// ObjCQualifiedIDType. /// FIXME: Move to ASTContext::typesAreCompatible() and friends. bool Sema::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, bool compare) { // Allow id<P..> and an 'id' or void* type in all cases. if (const PointerType *PT = lhs->getAsPointerType()) { QualType PointeeTy = PT->getPointeeType(); if (PointeeTy->isVoidType() || Context.isObjCIdStructType(PointeeTy) || Context.isObjCClassStructType(PointeeTy)) return true; } else if (const PointerType *PT = rhs->getAsPointerType()) { QualType PointeeTy = PT->getPointeeType(); if (PointeeTy->isVoidType() || Context.isObjCIdStructType(PointeeTy) || Context.isObjCClassStructType(PointeeTy)) return true; } if (const ObjCQualifiedIdType *lhsQID = lhs->getAsObjCQualifiedIdType()) { const ObjCQualifiedIdType *rhsQID = rhs->getAsObjCQualifiedIdType(); const ObjCQualifiedInterfaceType *rhsQI = 0; QualType rtype; if (!rhsQID) { // Not comparing two ObjCQualifiedIdType's? if (!rhs->isPointerType()) return false; rtype = rhs->getAsPointerType()->getPointeeType(); rhsQI = rtype->getAsObjCQualifiedInterfaceType(); if (rhsQI == 0) { // If the RHS is a unqualified interface pointer "NSString*", // make sure we check the class hierarchy. if (const ObjCInterfaceType *IT = rtype->getAsObjCInterfaceType()) { ObjCInterfaceDecl *rhsID = IT->getDecl(); for (unsigned i = 0; i != lhsQID->getNumProtocols(); ++i) { // when comparing an id<P> on lhs with a static type on rhs, // see if static class implements all of id's protocols, directly or // through its super class and categories. if (!ClassImplementsProtocol(lhsQID->getProtocols(i), rhsID, true)) return false; } return true; } } } ObjCQualifiedIdType::qual_iterator RHSProtoI, RHSProtoE; if (rhsQI) { // We have a qualified interface (e.g. "NSObject<Proto> *"). RHSProtoI = rhsQI->qual_begin(); RHSProtoE = rhsQI->qual_end(); } else if (rhsQID) { // We have a qualified id (e.g. "id<Proto> *"). RHSProtoI = rhsQID->qual_begin(); RHSProtoE = rhsQID->qual_end(); } else { return false; } for (unsigned i =0; i < lhsQID->getNumProtocols(); i++) { ObjCProtocolDecl *lhsProto = lhsQID->getProtocols(i); bool match = false; // when comparing an id<P> on lhs with a static type on rhs, // see if static class implements all of id's protocols, directly or // through its super class and categories. for (; RHSProtoI != RHSProtoE; ++RHSProtoI) { ObjCProtocolDecl *rhsProto = *RHSProtoI; if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { match = true; break; } } if (rhsQI) { // If the RHS is a qualified interface pointer "NSString<P>*", // make sure we check the class hierarchy. if (const ObjCInterfaceType *IT = rtype->getAsObjCInterfaceType()) { ObjCInterfaceDecl *rhsID = IT->getDecl(); for (unsigned i = 0; i != lhsQID->getNumProtocols(); ++i) { // when comparing an id<P> on lhs with a static type on rhs, // see if static class implements all of id's protocols, directly or // through its super class and categories. if (ClassImplementsProtocol(lhsQID->getProtocols(i), rhsID, true)) { match = true; break; } } } } if (!match) return false; } return true; } const ObjCQualifiedIdType *rhsQID = rhs->getAsObjCQualifiedIdType(); assert(rhsQID && "One of the LHS/RHS should be id<x>"); if (!lhs->isPointerType()) return false; QualType ltype = lhs->getAsPointerType()->getPointeeType(); if (const ObjCQualifiedInterfaceType *lhsQI = ltype->getAsObjCQualifiedInterfaceType()) { ObjCQualifiedIdType::qual_iterator LHSProtoI = lhsQI->qual_begin(); ObjCQualifiedIdType::qual_iterator LHSProtoE = lhsQI->qual_end(); for (; LHSProtoI != LHSProtoE; ++LHSProtoI) { bool match = false; ObjCProtocolDecl *lhsProto = *LHSProtoI; for (unsigned j = 0; j < rhsQID->getNumProtocols(); j++) { ObjCProtocolDecl *rhsProto = rhsQID->getProtocols(j); if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { match = true; break; } } if (!match) return false; } return true; } if (const ObjCInterfaceType *IT = ltype->getAsObjCInterfaceType()) { // for static type vs. qualified 'id' type, check that class implements // all of 'id's protocols. ObjCInterfaceDecl *lhsID = IT->getDecl(); for (unsigned j = 0; j < rhsQID->getNumProtocols(); j++) { ObjCProtocolDecl *rhsProto = rhsQID->getProtocols(j); if (!ClassImplementsProtocol(rhsProto, lhsID, compare, true)) return false; } return true; } return false; } <file_sep>/lib/Sema/Sema.cpp //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the actions class which performs semantic analysis and // builds an AST out of a parse stream. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Expr.h" #include "clang/Lex/Preprocessor.h" using namespace clang; /// ConvertQualTypeToStringFn - This function is used to pretty print the /// specified QualType as a string in diagnostics. static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val, const char *Modifier, unsigned ModLen, const char *Argument, unsigned ArgLen, llvm::SmallVectorImpl<char> &Output, void *Cookie) { ASTContext &Context = *static_cast<ASTContext*>(Cookie); std::string S; if (Kind == Diagnostic::ak_qualtype) { assert(ModLen == 0 && ArgLen == 0 && "Invalid modifier for QualType argument"); QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); // FIXME: Playing with std::string is really slow. S = Ty.getAsString(); // If this is a sugared type (like a typedef, typeof, etc), then unwrap one // level of the sugar so that the type is more obvious to the user. QualType DesugaredTy = Ty->getDesugaredType(true); DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() | Ty.getCVRQualifiers()); if (Ty != DesugaredTy && // If the desugared type is a vector type, we don't want to expand it, // it will turn into an attribute mess. People want their "vec4". !isa<VectorType>(DesugaredTy) && // Don't desugar magic Objective-C types. Ty.getUnqualifiedType() != Context.getObjCIdType() && Ty.getUnqualifiedType() != Context.getObjCSelType() && Ty.getUnqualifiedType() != Context.getObjCProtoType() && Ty.getUnqualifiedType() != Context.getObjCClassType() && // Not va_list. Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) { S = "'"+S+"' (aka '"; S += DesugaredTy.getAsString(); S += "')"; Output.append(S.begin(), S.end()); return; } } else if (Kind == Diagnostic::ak_declarationname) { DeclarationName N = DeclarationName::getFromOpaqueInteger(Val); S = N.getAsString(); if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0) S = '+' + S; else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0) S = '-' + S; else assert(ModLen == 0 && ArgLen == 0 && "Invalid modifier for DeclarationName argument"); } else { assert(Kind == Diagnostic::ak_nameddecl); if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0) S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString(); else { assert(ModLen == 0 && ArgLen == 0 && "Invalid modifier for NamedDecl* argument"); S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString(); } } Output.push_back('\''); Output.append(S.begin(), S.end()); Output.push_back('\''); } static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) { if (C.getLangOptions().CPlusPlus) return CXXRecordDecl::Create(C, TagDecl::TK_struct, C.getTranslationUnitDecl(), SourceLocation(), &C.Idents.get(Name)); return RecordDecl::Create(C, TagDecl::TK_struct, C.getTranslationUnitDecl(), SourceLocation(), &C.Idents.get(Name)); } void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { TUScope = S; PushDeclContext(S, Context.getTranslationUnitDecl()); if (!PP.getLangOptions().ObjC1) return; // Synthesize "typedef struct objc_selector *SEL;" RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector"); PushOnScopeChains(SelTag, TUScope); QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag)); TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext, SourceLocation(), &Context.Idents.get("SEL"), SelT); PushOnScopeChains(SelTypedef, TUScope); Context.setObjCSelType(SelTypedef); // FIXME: Make sure these don't leak! RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class"); QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag)); TypedefDecl *ClassTypedef = TypedefDecl::Create(Context, CurContext, SourceLocation(), &Context.Idents.get("Class"), ClassT); PushOnScopeChains(ClassTag, TUScope); PushOnScopeChains(ClassTypedef, TUScope); Context.setObjCClassType(ClassTypedef); // Synthesize "@class Protocol; ObjCInterfaceDecl *ProtocolDecl = ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), &Context.Idents.get("Protocol"), SourceLocation(), true); Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); PushOnScopeChains(ProtocolDecl, TUScope); // Synthesize "typedef struct objc_object { Class isa; } *id;" RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object"); QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag)); PushOnScopeChains(ObjectTag, TUScope); TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext, SourceLocation(), &Context.Idents.get("id"), ObjT); PushOnScopeChains(IdTypedef, TUScope); Context.setObjCIdType(IdTypedef); } Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, bool CompleteTranslationUnit) : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), CurContext(0), PreDeclaratorDC(0), CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()), GlobalNewDeleteDeclared(false), CompleteTranslationUnit(CompleteTranslationUnit) { // Get IdentifierInfo objects for known functions for which we // do extra checking. IdentifierTable &IT = PP.getIdentifierTable(); KnownFunctionIDs[id_NSLog] = &IT.get("NSLog"); KnownFunctionIDs[id_NSLogv] = &IT.get("NSLogv"); KnownFunctionIDs[id_asprintf] = &IT.get("asprintf"); KnownFunctionIDs[id_vasprintf] = &IT.get("vasprintf"); StdNamespace = 0; TUScope = 0; if (getLangOptions().CPlusPlus) FieldCollector.reset(new CXXFieldCollector()); // Tell diagnostics how to render things from the AST library. PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context); } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. /// If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) { QualType ExprTy = Context.getCanonicalType(Expr->getType()); QualType TypeTy = Context.getCanonicalType(Ty); if (ExprTy == TypeTy) return; if (Expr->getType().getTypePtr()->isPointerType() && Ty.getTypePtr()->isPointerType()) { QualType ExprBaseType = cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType(); QualType BaseType = cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType(); if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) << Expr->getSourceRange(); } } if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { ImpCast->setType(Ty); ImpCast->setLvalueCast(isLvalue); } else Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue); } void Sema::DeleteExpr(ExprTy *E) { if (E) static_cast<Expr*>(E)->Destroy(Context); } void Sema::DeleteStmt(StmtTy *S) { if (S) static_cast<Stmt*>(S)->Destroy(Context); } /// ActOnEndOfTranslationUnit - This is called at the very end of the /// translation unit when EOF is reached and all but the top-level scope is /// popped. void Sema::ActOnEndOfTranslationUnit() { if (!CompleteTranslationUnit) return; // C99 6.9.2p2: // A declaration of an identifier for an object that has file // scope without an initializer, and without a storage-class // specifier or with the storage-class specifier static, // constitutes a tentative definition. If a translation unit // contains one or more tentative definitions for an identifier, // and the translation unit contains no external definition for // that identifier, then the behavior is exactly as if the // translation unit contains a file scope declaration of that // identifier, with the composite type as of the end of the // translation unit, with an initializer equal to 0. if (!getLangOptions().CPlusPlus) { // Note: we traverse the scope's list of declarations rather than // the DeclContext's list, because we only want to see the most // recent declaration of each identifier. for (Scope::decl_iterator I = TUScope->decl_begin(), IEnd = TUScope->decl_end(); I != IEnd; ++I) { Decl *D = (*I).getAs<Decl>(); if (D->isInvalidDecl()) continue; if (VarDecl *VD = dyn_cast<VarDecl>(D)) { if (VD->isTentativeDefinition(Context)) { if (const IncompleteArrayType *ArrayT = Context.getAsIncompleteArrayType(VD->getType())) { if (RequireCompleteType(VD->getLocation(), ArrayT->getElementType(), diag::err_tentative_def_incomplete_type_arr)) VD->setInvalidDecl(); else { // Set the length of the array to 1 (C99 6.9.2p5). Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One, ArrayType::Normal, 0); VD->setType(T); } } else if (RequireCompleteType(VD->getLocation(), VD->getType(), diag::err_tentative_def_incomplete_type)) VD->setInvalidDecl(); } } } } } //===----------------------------------------------------------------------===// // Helper functions. //===----------------------------------------------------------------------===// /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *Sema::getCurFunctionDecl() { DeclContext *DC = CurContext; while (isa<BlockDecl>(DC)) DC = DC->getParent(); return dyn_cast<FunctionDecl>(DC); } ObjCMethodDecl *Sema::getCurMethodDecl() { DeclContext *DC = CurContext; while (isa<BlockDecl>(DC)) DC = DC->getParent(); return dyn_cast<ObjCMethodDecl>(DC); } NamedDecl *Sema::getCurFunctionOrMethodDecl() { DeclContext *DC = CurContext; while (isa<BlockDecl>(DC)) DC = DC->getParent(); if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) return cast<NamedDecl>(DC); return 0; } Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { this->Emit(); // If this is not a note, and we're in a template instantiation // that is different from the last template instantiation where // we emitted an error, print a template instantiation // backtrace. if (!SemaRef.Diags.isBuiltinNote(DiagID) && !SemaRef.ActiveTemplateInstantiations.empty() && SemaRef.ActiveTemplateInstantiations.back() != SemaRef.LastTemplateInstantiationErrorContext) { SemaRef.PrintInstantiationStack(); SemaRef.LastTemplateInstantiationErrorContext = SemaRef.ActiveTemplateInstantiations.back(); } } <file_sep>/include/clang/Frontend/PCHReader.h //===--- PCHReader.h - Precompiled Headers Reader ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PCHReader class, which reads a precompiled header. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_PCH_READER_H #define LLVM_CLANG_FRONTEND_PCH_READER_H #include "clang/Frontend/PCHBitCodes.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/Type.h" #include "clang/Basic/Diagnostic.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/Support/DataTypes.h" #include <string> #include <utility> #include <vector> namespace llvm { class MemoryBuffer; } namespace clang { class ASTContext; class Attr; class Decl; class DeclContext; class Preprocessor; /// \brief Reads a precompiled head containing the contents of a /// translation unit. /// /// The PCHReader class reads a bitstream (produced by the PCHWriter /// class) containing the serialized representation of a given /// abstract syntax tree and its supporting data structures. An /// instance of the PCHReader can be attached to an ASTContext object, /// which will provide access to the contents of the PCH file. /// /// The PCH reader provides lazy de-serialization of declarations, as /// required when traversing the AST. Only those AST nodes that are /// actually required will be de-serialized. class PCHReader : public ExternalASTSource { public: enum PCHReadResult { Success, Failure, IgnorePCH }; private: /// \brief The preprocessor that will be loading the source file. Preprocessor &PP; /// \brief The AST context into which we'll read the PCH file. ASTContext &Context; /// \brief The bitstream reader from which we'll read the PCH file. llvm::BitstreamReader Stream; /// \brief The file name of the PCH file. std::string FileName; /// \brief The memory buffer that stores the data associated with /// this PCH file. llvm::OwningPtr<llvm::MemoryBuffer> Buffer; /// \brief Offset of each type within the bitstream, indexed by the /// type ID, or the representation of a Type*. llvm::SmallVector<uint64_t, 16> TypeOffsets; /// \brief Whether the type with a given index has already been loaded. /// /// When the bit at a given index I is true, then TypeOffsets[I] is /// the already-loaded Type*. Otherwise, TypeOffsets[I] is the /// location of the type's record in the PCH file. /// /// FIXME: We can probably eliminate this, e.g., by bitmangling the /// values in TypeOffsets. std::vector<bool> TypeAlreadyLoaded; /// \brief Offset of each declaration within the bitstream, indexed /// by the declaration ID. llvm::SmallVector<uint64_t, 16> DeclOffsets; /// \brief Whether the declaration with a given index has already /// been loaded. /// /// When the bit at the given index I is true, then DeclOffsets[I] /// is the already-loaded Decl*. Otherwise, DeclOffsets[I] is the /// location of the declaration's record in the PCH file. /// /// FIXME: We can probably eliminate this, e.g., by bitmangling the /// values in DeclOffsets. std::vector<bool> DeclAlreadyLoaded; typedef llvm::DenseMap<const DeclContext *, std::pair<uint64_t, uint64_t> > DeclContextOffsetsMap; /// \brief Offsets of the lexical and visible declarations for each /// DeclContext. DeclContextOffsetsMap DeclContextOffsets; /// \brief String data for the identifiers in the PCH file. const char *IdentifierTable; /// \brief String data for identifiers, indexed by the identifier ID /// minus one. /// /// Each element in this array is either an offset into /// IdentifierTable that contains the string data (if the lowest bit /// is set) or is an IdentifierInfo* that has already been resolved. llvm::SmallVector<uint64_t, 16> IdentifierData; /// \brief The set of external definitions stored in the the PCH /// file. llvm::SmallVector<uint64_t, 16> ExternalDefinitions; PCHReadResult ReadPCHBlock(); bool CheckPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID); PCHReadResult ReadSourceManagerBlock(); bool ReadPreprocessorBlock(); bool ParseLanguageOptions(const llvm::SmallVectorImpl<uint64_t> &Record); QualType ReadTypeRecord(uint64_t Offset); void LoadedDecl(unsigned Index, Decl *D); Decl *ReadDeclRecord(uint64_t Offset, unsigned Index); PCHReader(const PCHReader&); // do not implement PCHReader &operator=(const PCHReader &); // do not implement public: typedef llvm::SmallVector<uint64_t, 64> RecordData; PCHReader(Preprocessor &PP, ASTContext &Context) : PP(PP), Context(Context), IdentifierTable(0) { } ~PCHReader() {} PCHReadResult ReadPCH(const std::string &FileName); /// \brief Resolve a type ID into a type, potentially building a new /// type. virtual QualType GetType(pch::TypeID ID); /// \brief Resolve a declaration ID into a declaration, potentially /// building a new declaration. virtual Decl *GetDecl(pch::DeclID ID); /// \brief Read all of the declarations lexically stored in a /// declaration context. /// /// \param DC The declaration context whose declarations will be /// read. /// /// \param Decls Vector that will contain the declarations loaded /// from the external source. The caller is responsible for merging /// these declarations with any declarations already stored in the /// declaration context. /// /// \returns true if there was an error while reading the /// declarations for this declaration context. virtual bool ReadDeclsLexicallyInContext(DeclContext *DC, llvm::SmallVectorImpl<unsigned> &Decls); /// \brief Read all of the declarations visible from a declaration /// context. /// /// \param DC The declaration context whose visible declarations /// will be read. /// /// \param Decls A vector of visible declaration structures, /// providing the mapping from each name visible in the declaration /// context to the declaration IDs of declarations with that name. /// /// \returns true if there was an error while reading the /// declarations for this declaration context. /// /// FIXME: Using this intermediate data structure results in an /// extraneous copying of the data. Could we pass in a reference to /// the StoredDeclsMap instead? virtual bool ReadDeclsVisibleInContext(DeclContext *DC, llvm::SmallVectorImpl<VisibleDeclaration> & Decls); /// \brief Function that will be invoked when we begin parsing a new /// translation unit involving this external AST source. /// /// This function will provide all of the external definitions to /// the ASTConsumer. virtual void StartTranslationUnit(ASTConsumer *Consumer); /// \brief Print some statistics about PCH usage. virtual void PrintStats(); /// \brief Report a diagnostic. DiagnosticBuilder Diag(unsigned DiagID); /// \brief Report a diagnostic. DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); IdentifierInfo *DecodeIdentifierInfo(unsigned Idx); IdentifierInfo *GetIdentifierInfo(const RecordData &Record, unsigned &Idx) { return DecodeIdentifierInfo(Record[Idx++]); } DeclarationName ReadDeclarationName(const RecordData &Record, unsigned &Idx); /// \brief Read an integral value llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx); /// \brief Read a signed integral value llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx); /// \brief Read a floating-point value llvm::APFloat ReadAPFloat(const RecordData &Record, unsigned &Idx); // \brief Read a string std::string ReadString(const RecordData &Record, unsigned &Idx); /// \brief Reads attributes from the current stream position. Attr *ReadAttributes(); /// \brief Reads an expression from the current stream position. Expr *ReadExpr(); /// \brief Retrieve the AST context that this PCH reader /// supplements. ASTContext &getContext() { return Context; } }; } // end namespace clang #endif <file_sep>/lib/Sema/SemaType.cpp //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements type-related semantic analysis. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/Parse/DeclSpec.h" using namespace clang; /// \brief Perform adjustment on the parameter type of a function. /// /// This routine adjusts the given parameter type @p T to the actual /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], /// C++ [dcl.fct]p3). The adjusted parameter type is returned. QualType Sema::adjustParameterType(QualType T) { // C99 6.7.5.3p7: if (T->isArrayType()) { // C99 6.7.5.3p7: // A declaration of a parameter as "array of type" shall be // adjusted to "qualified pointer to type", where the type // qualifiers (if any) are those specified within the [ and ] of // the array type derivation. return Context.getArrayDecayedType(T); } else if (T->isFunctionType()) // C99 6.7.5.3p8: // A declaration of a parameter as "function returning type" // shall be adjusted to "pointer to function returning type", as // in 6.3.2.1. return Context.getPointerType(T); return T; } /// \brief Convert the specified declspec to the appropriate type /// object. /// \param DS the declaration specifiers /// \returns The type described by the declaration specifiers, or NULL /// if there was an error. QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS) { // FIXME: Should move the logic from DeclSpec::Finish to here for validity // checking. QualType Result; switch (DS.getTypeSpecType()) { case DeclSpec::TST_void: Result = Context.VoidTy; break; case DeclSpec::TST_char: if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) Result = Context.CharTy; else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) Result = Context.SignedCharTy; else { assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && "Unknown TSS value"); Result = Context.UnsignedCharTy; } break; case DeclSpec::TST_wchar: if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) Result = Context.WCharTy; else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) << DS.getSpecifierName(DS.getTypeSpecType()); Result = Context.getSignedWCharType(); } else { assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && "Unknown TSS value"); Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) << DS.getSpecifierName(DS.getTypeSpecType()); Result = Context.getUnsignedWCharType(); } break; case DeclSpec::TST_unspecified: // "<proto1,proto2>" is an objc qualified ID with a missing id. if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers()); break; } // Unspecified typespec defaults to int in C90. However, the C90 grammar // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, // type-qualifier, or storage-class-specifier. If not, emit an extwarn. // Note that the one exception to this is function definitions, which are // allowed to be completely missing a declspec. This is handled in the // parser already though by it pretending to have seen an 'int' in this // case. if (getLangOptions().ImplicitInt) { // In C89 mode, we only warn if there is a completely missing declspec // when one is not allowed. if (DS.isEmpty()) Diag(DS.getSourceRange().getBegin(), diag::warn_missing_declspec) << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(), "int"); } else if (!DS.hasTypeSpecifier()) { // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: // "At least one type specifier shall be given in the declaration // specifiers in each declaration, and in the specifier-qualifier list in // each struct declaration and type name." // FIXME: Does Microsoft really have the implicit int extension in C++? unsigned DK = getLangOptions().CPlusPlus && !getLangOptions().Microsoft? diag::err_missing_type_specifier : diag::warn_missing_type_specifier; Diag(DS.getSourceRange().getBegin(), DK); // FIXME: If we could guarantee that the result would be // well-formed, it would be useful to have a code insertion hint // here. However, after emitting this warning/error, we often // emit other errors. } // FALL THROUGH. case DeclSpec::TST_int: { if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { switch (DS.getTypeSpecWidth()) { case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; case DeclSpec::TSW_short: Result = Context.ShortTy; break; case DeclSpec::TSW_long: Result = Context.LongTy; break; case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break; } } else { switch (DS.getTypeSpecWidth()) { case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break; } } break; } case DeclSpec::TST_float: Result = Context.FloatTy; break; case DeclSpec::TST_double: if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) Result = Context.LongDoubleTy; else Result = Context.DoubleTy; break; case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool case DeclSpec::TST_decimal32: // _Decimal32 case DeclSpec::TST_decimal64: // _Decimal64 case DeclSpec::TST_decimal128: // _Decimal128 assert(0 && "FIXME: GNU decimal extensions not supported yet!"); case DeclSpec::TST_class: case DeclSpec::TST_enum: case DeclSpec::TST_union: case DeclSpec::TST_struct: { Decl *D = static_cast<Decl *>(DS.getTypeRep()); assert(D && "Didn't get a decl for a class/enum/union/struct?"); assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!"); // TypeQuals handled by caller. Result = Context.getTypeDeclType(cast<TypeDecl>(D)); break; } case DeclSpec::TST_typename: { assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && "Can't handle qualifiers on typedef names yet!"); Result = QualType::getFromOpaquePtr(DS.getTypeRep()); if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so // we have this "hack" for now... if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType()) Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(), (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers()); else if (Result == Context.getObjCIdType()) // id<protocol-list> Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers()); else if (Result == Context.getObjCClassType()) // Class<protocol-list> Diag(DS.getSourceRange().getBegin(), diag::err_qualified_class_unsupported) << DS.getSourceRange(); else Diag(DS.getSourceRange().getBegin(), diag::err_invalid_protocol_qualifiers) << DS.getSourceRange(); } // TypeQuals handled by caller. break; } case DeclSpec::TST_typeofType: Result = QualType::getFromOpaquePtr(DS.getTypeRep()); assert(!Result.isNull() && "Didn't get a type for typeof?"); // TypeQuals handled by caller. Result = Context.getTypeOfType(Result); break; case DeclSpec::TST_typeofExpr: { Expr *E = static_cast<Expr *>(DS.getTypeRep()); assert(E && "Didn't get an expression for typeof?"); // TypeQuals handled by caller. Result = Context.getTypeOfExprType(E); break; } case DeclSpec::TST_error: return QualType(); } // Handle complex types. if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { if (getLangOptions().Freestanding) Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); Result = Context.getComplexType(Result); } assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary && "FIXME: imaginary types not supported yet!"); // See if there are any attributes on the declspec that apply to the type (as // opposed to the decl). if (const AttributeList *AL = DS.getAttributes()) ProcessTypeAttributeList(Result, AL); // Apply const/volatile/restrict qualifiers to T. if (unsigned TypeQuals = DS.getTypeQualifiers()) { // Enforce C99 6.7.3p2: "Types other than pointer types derived from object // or incomplete types shall not be restrict-qualified." C++ also allows // restrict-qualified references. if (TypeQuals & QualType::Restrict) { if (Result->isPointerType() || Result->isReferenceType()) { QualType EltTy = Result->isPointerType() ? Result->getAsPointerType()->getPointeeType() : Result->getAsReferenceType()->getPointeeType(); // If we have a pointer or reference, the pointee must have an object // incomplete type. if (!EltTy->isIncompleteOrObjectType()) { Diag(DS.getRestrictSpecLoc(), diag::err_typecheck_invalid_restrict_invalid_pointee) << EltTy << DS.getSourceRange(); TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. } } else { Diag(DS.getRestrictSpecLoc(), diag::err_typecheck_invalid_restrict_not_pointer) << Result << DS.getSourceRange(); TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. } } // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification // of a function type includes any type qualifiers, the behavior is // undefined." if (Result->isFunctionType() && TypeQuals) { // Get some location to point at, either the C or V location. SourceLocation Loc; if (TypeQuals & QualType::Const) Loc = DS.getConstSpecLoc(); else { assert((TypeQuals & QualType::Volatile) && "Has CV quals but not C or V?"); Loc = DS.getVolatileSpecLoc(); } Diag(Loc, diag::warn_typecheck_function_qualifiers) << Result << DS.getSourceRange(); } // C++ [dcl.ref]p1: // Cv-qualified references are ill-formed except when the // cv-qualifiers are introduced through the use of a typedef // (7.1.3) or of a template type argument (14.3), in which // case the cv-qualifiers are ignored. // FIXME: Shouldn't we be checking SCS_typedef here? if (DS.getTypeSpecType() == DeclSpec::TST_typename && TypeQuals && Result->isReferenceType()) { TypeQuals &= ~QualType::Const; TypeQuals &= ~QualType::Volatile; } Result = Result.getQualifiedType(TypeQuals); } return Result; } static std::string getPrintableNameForEntity(DeclarationName Entity) { if (Entity) return Entity.getAsString(); return "type name"; } /// \brief Build a pointer type. /// /// \param T The type to which we'll be building a pointer. /// /// \param Quals The cvr-qualifiers to be applied to the pointer type. /// /// \param Loc The location of the entity whose type involves this /// pointer type or, if there is no such entity, the location of the /// type that will have pointer type. /// /// \param Entity The name of the entity that involves the pointer /// type, if known. /// /// \returns A suitable pointer type, if there are no /// errors. Otherwise, returns a NULL type. QualType Sema::BuildPointerType(QualType T, unsigned Quals, SourceLocation Loc, DeclarationName Entity) { if (T->isReferenceType()) { // C++ 8.3.2p4: There shall be no ... pointers to references ... Diag(Loc, diag::err_illegal_decl_pointer_to_reference) << getPrintableNameForEntity(Entity); return QualType(); } // Enforce C99 6.7.3p2: "Types other than pointer types derived from // object or incomplete types shall not be restrict-qualified." if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) << T; Quals &= ~QualType::Restrict; } // Build the pointer type. return Context.getPointerType(T).getQualifiedType(Quals); } /// \brief Build a reference type. /// /// \param T The type to which we'll be building a reference. /// /// \param Quals The cvr-qualifiers to be applied to the reference type. /// /// \param Loc The location of the entity whose type involves this /// reference type or, if there is no such entity, the location of the /// type that will have reference type. /// /// \param Entity The name of the entity that involves the reference /// type, if known. /// /// \returns A suitable reference type, if there are no /// errors. Otherwise, returns a NULL type. QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals, SourceLocation Loc, DeclarationName Entity) { if (LValueRef) { if (const RValueReferenceType *R = T->getAsRValueReferenceType()) { // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a // reference to a type T, and attempt to create the type "lvalue // reference to cv TD" creates the type "lvalue reference to T". // We use the qualifiers (restrict or none) of the original reference, // not the new ones. This is consistent with GCC. return Context.getLValueReferenceType(R->getPointeeType()). getQualifiedType(T.getCVRQualifiers()); } } if (T->isReferenceType()) { // C++ [dcl.ref]p4: There shall be no references to references. // // According to C++ DR 106, references to references are only // diagnosed when they are written directly (e.g., "int & &"), // but not when they happen via a typedef: // // typedef int& intref; // typedef intref& intref2; // // Parser::ParserDeclaratorInternal diagnoses the case where // references are written directly; here, we handle the // collapsing of references-to-references as described in C++ // DR 106 and amended by C++ DR 540. return T; } // C++ [dcl.ref]p1: // A declarator that specifies the type “reference to cv void” // is ill-formed. if (T->isVoidType()) { Diag(Loc, diag::err_reference_to_void); return QualType(); } // Enforce C99 6.7.3p2: "Types other than pointer types derived from // object or incomplete types shall not be restrict-qualified." if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) << T; Quals &= ~QualType::Restrict; } // C++ [dcl.ref]p1: // [...] Cv-qualified references are ill-formed except when the // cv-qualifiers are introduced through the use of a typedef // (7.1.3) or of a template type argument (14.3), in which case // the cv-qualifiers are ignored. // // We diagnose extraneous cv-qualifiers for the non-typedef, // non-template type argument case within the parser. Here, we just // ignore any extraneous cv-qualifiers. Quals &= ~QualType::Const; Quals &= ~QualType::Volatile; // Handle restrict on references. if (LValueRef) return Context.getLValueReferenceType(T).getQualifiedType(Quals); return Context.getRValueReferenceType(T).getQualifiedType(Quals); } /// \brief Build an array type. /// /// \param T The type of each element in the array. /// /// \param ASM C99 array size modifier (e.g., '*', 'static'). /// /// \param ArraySize Expression describing the size of the array. /// /// \param Quals The cvr-qualifiers to be applied to the array's /// element type. /// /// \param Loc The location of the entity whose type involves this /// array type or, if there is no such entity, the location of the /// type that will have array type. /// /// \param Entity The name of the entity that involves the array /// type, if known. /// /// \returns A suitable array type, if there are no errors. Otherwise, /// returns a NULL type. QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceLocation Loc, DeclarationName Entity) { // C99 6.7.5.2p1: If the element type is an incomplete or function type, // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) if (RequireCompleteType(Loc, T, diag::err_illegal_decl_array_incomplete_type)) return QualType(); if (T->isFunctionType()) { Diag(Loc, diag::err_illegal_decl_array_of_functions) << getPrintableNameForEntity(Entity); return QualType(); } // C++ 8.3.2p4: There shall be no ... arrays of references ... if (T->isReferenceType()) { Diag(Loc, diag::err_illegal_decl_array_of_references) << getPrintableNameForEntity(Entity); return QualType(); } if (const RecordType *EltTy = T->getAsRecordType()) { // If the element type is a struct or union that contains a variadic // array, accept it as a GNU extension: C99 6.7.2.1p2. if (EltTy->getDecl()->hasFlexibleArrayMember()) Diag(Loc, diag::ext_flexible_array_in_array) << T; } else if (T->isObjCInterfaceType()) { Diag(Loc, diag::warn_objc_array_of_interfaces) << T; } // C99 6.7.5.2p1: The size expression shall have integer type. if (ArraySize && !ArraySize->isTypeDependent() && !ArraySize->getType()->isIntegerType()) { Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) << ArraySize->getType() << ArraySize->getSourceRange(); ArraySize->Destroy(Context); return QualType(); } llvm::APSInt ConstVal(32); if (!ArraySize) { T = Context.getIncompleteArrayType(T, ASM, Quals); } else if (ArraySize->isValueDependent()) { T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals); } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || (!T->isDependentType() && !T->isConstantSizeType())) { // Per C99, a variable array is an array with either a non-constant // size or an element type that has a non-constant-size T = Context.getVariableArrayType(T, ArraySize, ASM, Quals); } else { // C99 6.7.5.2p1: If the expression is a constant expression, it shall // have a value greater than zero. if (ConstVal.isSigned()) { if (ConstVal.isNegative()) { Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) << ArraySize->getSourceRange(); return QualType(); } else if (ConstVal == 0) { // GCC accepts zero sized static arrays. Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size) << ArraySize->getSourceRange(); } } T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); } // If this is not C99, extwarn about VLA's and C99 array size modifiers. if (!getLangOptions().C99) { if (ArraySize && !ArraySize->isTypeDependent() && !ArraySize->isValueDependent() && !ArraySize->isIntegerConstantExpr(Context)) Diag(Loc, diag::ext_vla); else if (ASM != ArrayType::Normal || Quals != 0) Diag(Loc, diag::ext_c99_array_usage); } return T; } /// \brief Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param NumParamTypes The number of parameter types in ParamTypes. /// /// \param Variadic Whether this is a variadic function type. /// /// \param Quals The cvr-qualifiers to be applied to the function type. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \returns A suitable function type, if there are no /// errors. Otherwise, returns a NULL type. QualType Sema::BuildFunctionType(QualType T, QualType *ParamTypes, unsigned NumParamTypes, bool Variadic, unsigned Quals, SourceLocation Loc, DeclarationName Entity) { if (T->isArrayType() || T->isFunctionType()) { Diag(Loc, diag::err_func_returning_array_function) << T; return QualType(); } bool Invalid = false; for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { QualType ParamType = adjustParameterType(ParamTypes[Idx]); if (ParamType->isVoidType()) { Diag(Loc, diag::err_param_with_void_type); Invalid = true; } ParamTypes[Idx] = ParamType; } if (Invalid) return QualType(); return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic, Quals); } /// GetTypeForDeclarator - Convert the type for the specified /// declarator to Type instances. Skip the outermost Skip type /// objects. QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip) { bool OmittedReturnType = false; if (D.getContext() == Declarator::BlockLiteralContext && Skip == 0 && !D.getDeclSpec().hasTypeSpecifier() && (D.getNumTypeObjects() == 0 || (D.getNumTypeObjects() == 1 && D.getTypeObject(0).Kind == DeclaratorChunk::Function))) OmittedReturnType = true; // long long is a C99 feature. if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong) Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong); // Determine the type of the declarator. Not all forms of declarator // have a type. QualType T; switch (D.getKind()) { case Declarator::DK_Abstract: case Declarator::DK_Normal: case Declarator::DK_Operator: { const DeclSpec& DS = D.getDeclSpec(); if (OmittedReturnType) // We default to a dependent type initially. Can be modified by // the first return statement. T = Context.DependentTy; else { T = ConvertDeclSpecToType(DS); if (T.isNull()) return T; } break; } case Declarator::DK_Constructor: case Declarator::DK_Destructor: case Declarator::DK_Conversion: // Constructors and destructors don't have return types. Use // "void" instead. Conversion operators will check their return // types separately. T = Context.VoidTy; break; } // The name we're declaring, if any. DeclarationName Name; if (D.getIdentifier()) Name = D.getIdentifier(); // Walk the DeclTypeInfo, building the recursive type as we go. // DeclTypeInfos are ordered from the identifier out, which is // opposite of what we want :). for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) { DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip); switch (DeclType.Kind) { default: assert(0 && "Unknown decltype!"); case DeclaratorChunk::BlockPointer: // If blocks are disabled, emit an error. if (!LangOpts.Blocks) Diag(DeclType.Loc, diag::err_blocks_disable); if (DeclType.Cls.TypeQuals) Diag(D.getIdentifierLoc(), diag::err_qualified_block_pointer_type); if (!T.getTypePtr()->isFunctionType()) Diag(D.getIdentifierLoc(), diag::err_nonfunction_block_type); else T = Context.getBlockPointerType(T); break; case DeclaratorChunk::Pointer: T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name); break; case DeclaratorChunk::Reference: T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Ref.HasRestrict ? QualType::Restrict : 0, DeclType.Loc, Name); break; case DeclaratorChunk::Array: { DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); ArrayType::ArraySizeModifier ASM; if (ATI.isStar) ASM = ArrayType::Star; else if (ATI.hasStatic) ASM = ArrayType::Static; else ASM = ArrayType::Normal; T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name); break; } case DeclaratorChunk::Function: { // If the function declarator has a prototype (i.e. it is not () and // does not have a K&R-style identifier list), then the arguments are part // of the type, otherwise the argument list is (). const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; // C99 6.7.5.3p1: The return type may not be a function or array type. if (T->isArrayType() || T->isFunctionType()) { Diag(DeclType.Loc, diag::err_func_returning_array_function) << T; T = Context.IntTy; D.setInvalidType(true); } if (FTI.NumArgs == 0) { if (getLangOptions().CPlusPlus) { // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the // function takes no arguments. T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic,FTI.TypeQuals); } else if (FTI.isVariadic) { // We allow a zero-parameter variadic function in C if the // function is marked with the "overloadable" // attribute. Scan for this attribute now. bool Overloadable = false; for (const AttributeList *Attrs = D.getAttributes(); Attrs; Attrs = Attrs->getNext()) { if (Attrs->getKind() == AttributeList::AT_overloadable) { Overloadable = true; break; } } if (!Overloadable) Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0); } else { // Simple void foo(), where the incoming T is the result type. T = Context.getFunctionNoProtoType(T); } } else if (FTI.ArgInfo[0].Param == 0) { // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition. Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); } else { // Otherwise, we have a function with an argument list that is // potentially variadic. llvm::SmallVector<QualType, 16> ArgTys; for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>()); QualType ArgTy = Param->getType(); assert(!ArgTy.isNull() && "Couldn't parse type?"); // Adjust the parameter type. assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); // Look for 'void'. void is allowed only as a single argument to a // function with no other parameters (C99 6.7.5.3p10). We record // int(void) as a FunctionProtoType with an empty argument list. if (ArgTy->isVoidType()) { // If this is something like 'float(int, void)', reject it. 'void' // is an incomplete type (C99 6.2.5p19) and function decls cannot // have arguments of incomplete type. if (FTI.NumArgs != 1 || FTI.isVariadic) { Diag(DeclType.Loc, diag::err_void_only_param); ArgTy = Context.IntTy; Param->setType(ArgTy); } else if (FTI.ArgInfo[i].Ident) { // Reject, but continue to parse 'int(void abc)'. Diag(FTI.ArgInfo[i].IdentLoc, diag::err_param_with_void_type); ArgTy = Context.IntTy; Param->setType(ArgTy); } else { // Reject, but continue to parse 'float(const void)'. if (ArgTy.getCVRQualifiers()) Diag(DeclType.Loc, diag::err_void_param_qualified); // Do not add 'void' to the ArgTys list. break; } } else if (!FTI.hasPrototype) { if (ArgTy->isPromotableIntegerType()) { ArgTy = Context.IntTy; } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) { if (BTy->getKind() == BuiltinType::Float) ArgTy = Context.DoubleTy; } } ArgTys.push_back(ArgTy); } T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), FTI.isVariadic, FTI.TypeQuals); } break; } case DeclaratorChunk::MemberPointer: // The scope spec must refer to a class, or be dependent. DeclContext *DC = computeDeclContext(DeclType.Mem.Scope()); QualType ClsType; // FIXME: Extend for dependent types when it's actually supported. // See ActOnCXXNestedNameSpecifier. if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC)) { ClsType = Context.getTagDeclType(RD); } else { if (DC) { Diag(DeclType.Mem.Scope().getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass) << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") << DeclType.Mem.Scope().getRange(); } D.setInvalidType(true); ClsType = Context.IntTy; } // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member // with reference type, or "cv void." if (T->isReferenceType()) { Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference) << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); D.setInvalidType(true); T = Context.IntTy; } if (T->isVoidType()) { Diag(DeclType.Loc, diag::err_illegal_decl_mempointer_to_void) << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); T = Context.IntTy; } // Enforce C99 6.7.3p2: "Types other than pointer types derived from // object or incomplete types shall not be restrict-qualified." if ((DeclType.Mem.TypeQuals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) << T; DeclType.Mem.TypeQuals &= ~QualType::Restrict; } T = Context.getMemberPointerType(T, ClsType.getTypePtr()). getQualifiedType(DeclType.Mem.TypeQuals); break; } if (T.isNull()) { D.setInvalidType(true); T = Context.IntTy; } // See if there are any attributes on this declarator chunk. if (const AttributeList *AL = DeclType.getAttrs()) ProcessTypeAttributeList(T, AL); } if (getLangOptions().CPlusPlus && T->isFunctionType()) { const FunctionProtoType *FnTy = T->getAsFunctionProtoType(); assert(FnTy && "Why oh why is there not a FunctionProtoType here ?"); // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type // for a nonstatic member function, the function type to which a pointer // to member refers, or the top-level function type of a function typedef // declaration. if (FnTy->getTypeQuals() != 0 && D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && ((D.getContext() != Declarator::MemberContext && (!D.getCXXScopeSpec().isSet() || !computeDeclContext(D.getCXXScopeSpec())->isRecord())) || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { if (D.isFunctionDeclarator()) Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); else Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_typedef_function_type_use); // Strip the cv-quals from the type. T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), FnTy->getNumArgs(), FnTy->isVariadic(), 0); } } // If there were any type attributes applied to the decl itself (not the // type, apply the type attribute to the type!) if (const AttributeList *Attrs = D.getAttributes()) ProcessTypeAttributeList(T, Attrs); return T; } /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition /// declarator QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) { ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>()); QualType T = MDecl->getResultType(); llvm::SmallVector<QualType, 16> ArgTys; // Add the first two invisible argument types for self and _cmd. if (MDecl->isInstanceMethod()) { QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface()); selfTy = Context.getPointerType(selfTy); ArgTys.push_back(selfTy); } else ArgTys.push_back(Context.getObjCIdType()); ArgTys.push_back(Context.getObjCSelType()); for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), E = MDecl->param_end(); PI != E; ++PI) { QualType ArgTy = (*PI)->getType(); assert(!ArgTy.isNull() && "Couldn't parse type?"); ArgTy = adjustParameterType(ArgTy); ArgTys.push_back(ArgTy); } T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), MDecl->isVariadic(), 0); return T; } /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that /// may be similar (C++ 4.4), replaces T1 and T2 with the type that /// they point to and return true. If T1 and T2 aren't pointer types /// or pointer-to-member types, or if they are not similar at this /// level, returns false and leaves T1 and T2 unchanged. Top-level /// qualifiers on T1 and T2 are ignored. This function will typically /// be called in a loop that successively "unwraps" pointer and /// pointer-to-member types to compare them at each level. bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) { const PointerType *T1PtrType = T1->getAsPointerType(), *T2PtrType = T2->getAsPointerType(); if (T1PtrType && T2PtrType) { T1 = T1PtrType->getPointeeType(); T2 = T2PtrType->getPointeeType(); return true; } const MemberPointerType *T1MPType = T1->getAsMemberPointerType(), *T2MPType = T2->getAsMemberPointerType(); if (T1MPType && T2MPType && Context.getCanonicalType(T1MPType->getClass()) == Context.getCanonicalType(T2MPType->getClass())) { T1 = T1MPType->getPointeeType(); T2 = T2MPType->getPointeeType(); return true; } return false; } Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { // C99 6.7.6: Type names have no identifier. This is already validated by // the parser. assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); QualType T = GetTypeForDeclarator(D, S); if (T.isNull()) return true; // Check that there are no default arguments (C++ only). if (getLangOptions().CPlusPlus) CheckExtraCXXDefaultArguments(D); return T.getAsOpaquePtr(); } //===----------------------------------------------------------------------===// // Type Attribute Processing //===----------------------------------------------------------------------===// /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the /// specified type. The attribute contains 1 argument, the id of the address /// space for the type. static void HandleAddressSpaceTypeAttribute(QualType &Type, const AttributeList &Attr, Sema &S){ // If this type is already address space qualified, reject it. // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers // for two or more different address spaces." if (Type.getAddressSpace()) { S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); return; } // Check the attribute arguments. if (Attr.getNumArgs() != 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; return; } Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); llvm::APSInt addrSpace(32); if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) << ASArgExpr->getSourceRange(); return; } unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); Type = S.Context.getAddrSpaceQualType(Type, ASIdx); } /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the /// specified type. The attribute contains 1 argument, weak or strong. static void HandleObjCGCTypeAttribute(QualType &Type, const AttributeList &Attr, Sema &S) { if (Type.getObjCGCAttr() != QualType::GCNone) { S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc); return; } // Check the attribute arguments. if (!Attr.getParameterName()) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string) << "objc_gc" << 1; return; } QualType::GCAttrTypes GCAttr; if (Attr.getNumArgs() != 0) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; return; } if (Attr.getParameterName()->isStr("weak")) GCAttr = QualType::Weak; else if (Attr.getParameterName()->isStr("strong")) GCAttr = QualType::Strong; else { S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) << "objc_gc" << Attr.getParameterName(); return; } Type = S.Context.getObjCGCQualType(Type, GCAttr); } void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) { // Scan through and apply attributes to this type where it makes sense. Some // attributes (such as __address_space__, __vector_size__, etc) apply to the // type, but others can be present in the type specifiers even though they // apply to the decl. Here we apply type attributes and ignore the rest. for (; AL; AL = AL->getNext()) { // If this is an attribute we can handle, do so now, otherwise, add it to // the LeftOverAttrs list for rechaining. switch (AL->getKind()) { default: break; case AttributeList::AT_address_space: HandleAddressSpaceTypeAttribute(Result, *AL, *this); break; case AttributeList::AT_objc_gc: HandleObjCGCTypeAttribute(Result, *AL, *this); break; } } } /// @brief Ensure that the type T is a complete type. /// /// This routine checks whether the type @p T is complete in any /// context where a complete type is required. If @p T is a complete /// type, returns false. If @p T is a class template specialization, /// this routine then attempts to perform class template /// instantiation. If instantiation fails, or if @p T is incomplete /// and cannot be completed, issues the diagnostic @p diag (giving it /// the type @p T) and returns true. /// /// @param Loc The location in the source that the incomplete type /// diagnostic should refer to. /// /// @param T The type that this routine is examining for completeness. /// /// @param diag The diagnostic value (e.g., /// @c diag::err_typecheck_decl_incomplete_type) that will be used /// for the error message if @p T is incomplete. /// /// @param Range1 An optional range in the source code that will be a /// part of the "incomplete type" error message. /// /// @param Range2 An optional range in the source code that will be a /// part of the "incomplete type" error message. /// /// @param PrintType If non-NULL, the type that should be printed /// instead of @p T. This parameter should be used when the type that /// we're checking for incompleteness isn't the type that should be /// displayed to the user, e.g., when T is a type and PrintType is a /// pointer to T. /// /// @returns @c true if @p T is incomplete and a diagnostic was emitted, /// @c false otherwise. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag, SourceRange Range1, SourceRange Range2, QualType PrintType) { // If we have a complete type, we're done. if (!T->isIncompleteType()) return false; // If we have a class template specialization or a class member of a // class template specialization, try to instantiate it. if (const RecordType *Record = T->getAsRecordType()) { if (ClassTemplateSpecializationDecl *ClassTemplateSpec = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { // Update the class template specialization's location to // refer to the point of instantiation. if (Loc.isValid()) ClassTemplateSpec->setLocation(Loc); return InstantiateClassTemplateSpecialization(ClassTemplateSpec, /*ExplicitInstantiation=*/false); } } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Record->getDecl())) { if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { // Find the class template specialization that surrounds this // member class. ClassTemplateSpecializationDecl *Spec = 0; for (DeclContext *Parent = Rec->getDeclContext(); Parent && !Spec; Parent = Parent->getParent()) Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent); assert(Spec && "Not a member of a class template specialization?"); return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(), Spec->getNumTemplateArgs()); } } } if (PrintType.isNull()) PrintType = T; // We have an incomplete type. Produce a diagnostic. Diag(Loc, diag) << PrintType << Range1 << Range2; // If the type was a forward declaration of a class/struct/union // type, produce const TagType *Tag = 0; if (const RecordType *Record = T->getAsRecordType()) Tag = Record; else if (const EnumType *Enum = T->getAsEnumType()) Tag = Enum; if (Tag && !Tag->getDecl()->isInvalidDecl()) Diag(Tag->getDecl()->getLocation(), Tag->isBeingDefined() ? diag::note_type_being_defined : diag::note_forward_declaration) << QualType(Tag, 0); return true; } /// \brief Retrieve a version of the type 'T' that is qualified by the /// nested-name-specifier contained in SS. QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) { if (!SS.isSet() || SS.isInvalid() || T.isNull()) return T; NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); return Context.getQualifiedNameType(NNS, T); } <file_sep>/test/Sema/attr-aligned.c // RUN: clang-cc -triple i386-apple-darwin9 -fsyntax-only -verify %s int x __attribute__((aligned(3))); // expected-error {{requested alignment is not a power of 2}} // PR3254 short g0[3] __attribute__((aligned)); short g0_chk[__alignof__(g0) == 16 ? 1 : -1]; <file_sep>/include/clang/AST/Attr.h //===--- Attr.h - Classes for representing expressions ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Attr interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_ATTR_H #define LLVM_CLANG_AST_ATTR_H #include <cassert> #include <cstring> #include <string> #include <algorithm> namespace clang { class ASTContext; /// Attr - This represents one attribute. class Attr { public: enum Kind { Alias, Aligned, AlwaysInline, AnalyzerNoReturn, // Clang-specific. Annotate, AsmLabel, // Represent GCC asm label extension. Blocks, Cleanup, Const, Constructor, DLLExport, DLLImport, Deprecated, Destructor, FastCall, Format, GNUCInline, IBOutletKind, // Clang-specific. Use "Kind" suffix to not conflict with NoReturn, NoThrow, Nodebug, Noinline, NonNull, ObjCException, ObjCNSObject, Overloadable, // Clang-specific Packed, Pure, Regparm, Section, StdCall, TransparentUnion, Unavailable, Unused, Used, Visibility, WarnUnusedResult, Weak, WeakImport }; private: Attr *Next; Kind AttrKind; bool Inherited : 1; protected: void* operator new(size_t bytes) throw() { assert(0 && "Attrs cannot be allocated with regular 'new'."); return 0; } void operator delete(void* data) throw() { assert(0 && "Attrs cannot be released with regular 'delete'."); } protected: Attr(Kind AK) : Next(0), AttrKind(AK), Inherited(false) {} virtual ~Attr() { assert(Next == 0 && "Destroy didn't work"); } public: void Destroy(ASTContext &C); /// \brief Whether this attribute should be merged to new /// declarations. virtual bool isMerged() const { return true; } Kind getKind() const { return AttrKind; } Attr *getNext() { return Next; } const Attr *getNext() const { return Next; } void setNext(Attr *next) { Next = next; } bool isInherited() const { return Inherited; } void setInherited(bool value) { Inherited = value; } void addAttr(Attr *attr) { assert((attr != 0) && "addAttr(): attr is null"); // FIXME: This doesn't preserve the order in any way. attr->Next = Next; Next = attr; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *) { return true; } }; class PackedAttr : public Attr { unsigned Alignment; public: PackedAttr(unsigned alignment) : Attr(Packed), Alignment(alignment) {} /// getAlignment - The specified alignment in bits. unsigned getAlignment() const { return Alignment; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Packed; } static bool classof(const PackedAttr *A) { return true; } }; class AlignedAttr : public Attr { unsigned Alignment; public: AlignedAttr(unsigned alignment) : Attr(Aligned), Alignment(alignment) {} /// getAlignment - The specified alignment in bits. unsigned getAlignment() const { return Alignment; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Aligned; } static bool classof(const AlignedAttr *A) { return true; } }; class AnnotateAttr : public Attr { std::string Annotation; public: AnnotateAttr(const std::string &ann) : Attr(Annotate), Annotation(ann) {} const std::string& getAnnotation() const { return Annotation; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Annotate; } static bool classof(const AnnotateAttr *A) { return true; } }; class AsmLabelAttr : public Attr { std::string Label; public: AsmLabelAttr(const std::string &L) : Attr(AsmLabel), Label(L) {} const std::string& getLabel() const { return Label; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == AsmLabel; } static bool classof(const AsmLabelAttr *A) { return true; } }; class AlwaysInlineAttr : public Attr { public: AlwaysInlineAttr() : Attr(AlwaysInline) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == AlwaysInline; } static bool classof(const AlwaysInlineAttr *A) { return true; } }; class AliasAttr : public Attr { std::string Aliasee; public: AliasAttr(const std::string &aliasee) : Attr(Alias), Aliasee(aliasee) {} const std::string& getAliasee() const { return Aliasee; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Alias; } static bool classof(const AliasAttr *A) { return true; } }; class ConstructorAttr : public Attr { int priority; public: ConstructorAttr(int p) : Attr(Constructor), priority(p) {} int getPriority() const { return priority; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Constructor; } static bool classof(const ConstructorAttr *A) { return true; } }; class DestructorAttr : public Attr { int priority; public: DestructorAttr(int p) : Attr(Destructor), priority(p) {} int getPriority() const { return priority; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Destructor; } static bool classof(const DestructorAttr *A) { return true; } }; class GNUCInlineAttr : public Attr { public: GNUCInlineAttr() : Attr(GNUCInline) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == GNUCInline; } static bool classof(const GNUCInlineAttr *A) { return true; } }; class IBOutletAttr : public Attr { public: IBOutletAttr() : Attr(IBOutletKind) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == IBOutletKind; } static bool classof(const IBOutletAttr *A) { return true; } }; class NoReturnAttr : public Attr { public: NoReturnAttr() : Attr(NoReturn) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == NoReturn; } static bool classof(const NoReturnAttr *A) { return true; } }; class AnalyzerNoReturnAttr : public Attr { public: AnalyzerNoReturnAttr() : Attr(AnalyzerNoReturn) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == AnalyzerNoReturn; } static bool classof(const AnalyzerNoReturnAttr *A) { return true; } }; class DeprecatedAttr : public Attr { public: DeprecatedAttr() : Attr(Deprecated) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Deprecated; } static bool classof(const DeprecatedAttr *A) { return true; } }; class SectionAttr : public Attr { std::string Name; public: SectionAttr(const std::string &N) : Attr(Section), Name(N) {} const std::string& getName() const { return Name; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Section; } static bool classof(const SectionAttr *A) { return true; } }; class UnavailableAttr : public Attr { public: UnavailableAttr() : Attr(Unavailable) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Unavailable; } static bool classof(const UnavailableAttr *A) { return true; } }; class UnusedAttr : public Attr { public: UnusedAttr() : Attr(Unused) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Unused; } static bool classof(const UnusedAttr *A) { return true; } }; class UsedAttr : public Attr { public: UsedAttr() : Attr(Used) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Used; } static bool classof(const UsedAttr *A) { return true; } }; class WeakAttr : public Attr { public: WeakAttr() : Attr(Weak) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Weak; } static bool classof(const WeakAttr *A) { return true; } }; class WeakImportAttr : public Attr { public: WeakImportAttr() : Attr(WeakImport) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == WeakImport; } static bool classof(const WeakImportAttr *A) { return true; } }; class NoThrowAttr : public Attr { public: NoThrowAttr() : Attr(NoThrow) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == NoThrow; } static bool classof(const NoThrowAttr *A) { return true; } }; class ConstAttr : public Attr { public: ConstAttr() : Attr(Const) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Const; } static bool classof(const ConstAttr *A) { return true; } }; class PureAttr : public Attr { public: PureAttr() : Attr(Pure) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Pure; } static bool classof(const PureAttr *A) { return true; } }; class NonNullAttr : public Attr { unsigned* ArgNums; unsigned Size; public: NonNullAttr(unsigned* arg_nums = 0, unsigned size = 0) : Attr(NonNull), ArgNums(0), Size(0) { if (size == 0) return; assert(arg_nums); ArgNums = new unsigned[size]; Size = size; memcpy(ArgNums, arg_nums, sizeof(*ArgNums)*size); } virtual ~NonNullAttr() { delete [] ArgNums; } typedef const unsigned *iterator; iterator begin() const { return ArgNums; } iterator end() const { return ArgNums + Size; } unsigned size() const { return Size; } bool isNonNull(unsigned arg) const { return ArgNums ? std::binary_search(ArgNums, ArgNums+Size, arg) : true; } static bool classof(const Attr *A) { return A->getKind() == NonNull; } static bool classof(const NonNullAttr *A) { return true; } }; class FormatAttr : public Attr { std::string Type; int formatIdx, firstArg; public: FormatAttr(const std::string &type, int idx, int first) : Attr(Format), Type(type), formatIdx(idx), firstArg(first) {} const std::string& getType() const { return Type; } void setType(const std::string &type) { Type = type; } int getFormatIdx() const { return formatIdx; } int getFirstArg() const { return firstArg; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Format; } static bool classof(const FormatAttr *A) { return true; } }; class VisibilityAttr : public Attr { public: /// @brief An enumeration for the kinds of visibility of symbols. enum VisibilityTypes { DefaultVisibility = 0, HiddenVisibility, ProtectedVisibility }; private: VisibilityTypes VisibilityType; public: VisibilityAttr(VisibilityTypes v) : Attr(Visibility), VisibilityType(v) {} VisibilityTypes getVisibility() const { return VisibilityType; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Visibility; } static bool classof(const VisibilityAttr *A) { return true; } }; class DLLImportAttr : public Attr { public: DLLImportAttr() : Attr(DLLImport) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == DLLImport; } static bool classof(const DLLImportAttr *A) { return true; } }; class DLLExportAttr : public Attr { public: DLLExportAttr() : Attr(DLLExport) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == DLLExport; } static bool classof(const DLLExportAttr *A) { return true; } }; class FastCallAttr : public Attr { public: FastCallAttr() : Attr(FastCall) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == FastCall; } static bool classof(const FastCallAttr *A) { return true; } }; class StdCallAttr : public Attr { public: StdCallAttr() : Attr(StdCall) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == StdCall; } static bool classof(const StdCallAttr *A) { return true; } }; class TransparentUnionAttr : public Attr { public: TransparentUnionAttr() : Attr(TransparentUnion) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == TransparentUnion; } static bool classof(const TransparentUnionAttr *A) { return true; } }; class ObjCNSObjectAttr : public Attr { // Implement isa/cast/dyncast/etc. public: ObjCNSObjectAttr() : Attr(ObjCNSObject) {} static bool classof(const Attr *A) { return A->getKind() == ObjCNSObject; } static bool classof(const ObjCNSObjectAttr *A) { return true; } }; class ObjCExceptionAttr : public Attr { public: ObjCExceptionAttr() : Attr(ObjCException) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == ObjCException; } static bool classof(const ObjCExceptionAttr *A) { return true; } }; class OverloadableAttr : public Attr { public: OverloadableAttr() : Attr(Overloadable) { } virtual bool isMerged() const { return false; } static bool classof(const Attr *A) { return A->getKind() == Overloadable; } static bool classof(const OverloadableAttr *) { return true; } }; class BlocksAttr : public Attr { public: enum BlocksAttrTypes { ByRef = 0 }; private: BlocksAttrTypes BlocksAttrType; public: BlocksAttr(BlocksAttrTypes t) : Attr(Blocks), BlocksAttrType(t) {} BlocksAttrTypes getType() const { return BlocksAttrType; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Blocks; } static bool classof(const BlocksAttr *A) { return true; } }; class FunctionDecl; class CleanupAttr : public Attr { FunctionDecl *FD; public: CleanupAttr(FunctionDecl *fd) : Attr(Cleanup), FD(fd) {} const FunctionDecl *getFunctionDecl() const { return FD; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Cleanup; } static bool classof(const CleanupAttr *A) { return true; } }; class NodebugAttr : public Attr { public: NodebugAttr() : Attr(Nodebug) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Nodebug; } static bool classof(const NodebugAttr *A) { return true; } }; class WarnUnusedResultAttr : public Attr { public: WarnUnusedResultAttr() : Attr(WarnUnusedResult) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == WarnUnusedResult;} static bool classof(const WarnUnusedResultAttr *A) { return true; } }; class NoinlineAttr : public Attr { public: NoinlineAttr() : Attr(Noinline) {} // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Noinline; } static bool classof(const NoinlineAttr *A) { return true; } }; class RegparmAttr : public Attr { unsigned NumParams; public: RegparmAttr(unsigned np) : Attr(Regparm), NumParams(np) {} unsigned getNumParams() const { return NumParams; } // Implement isa/cast/dyncast/etc. static bool classof(const Attr *A) { return A->getKind() == Regparm; } static bool classof(const RegparmAttr *A) { return true; } }; } // end namespace clang #endif <file_sep>/lib/Driver/Makefile ##===- clang/lib/Driver/Makefile ---------------------------*- Makefile -*-===## # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # ##===----------------------------------------------------------------------===## LEVEL = ../../../.. LIBRARYNAME := clangDriver BUILD_ARCHIVE = 1 CXXFLAGS = -fno-rtti include $(LEVEL)/Makefile.common SVN_REVISION := $(shell cd $(PROJ_SRC_DIR)/../.. && svnversion) CPP.Defines += -I$(PROJ_SRC_DIR)/../../include -I$(PROJ_OBJ_DIR)/../../include \ -DSVN_REVISION='"$(SVN_REVISION)"' $(ObjDir)/.ver-svn .ver: @if [ '$(SVN_REVISION)' != '$(shell cat $(ObjDir)/.ver-svn 2>/dev/null)' ]; then\ echo '$(SVN_REVISION)' > $(ObjDir)/.ver-svn; \ fi $(ObjDir)/.ver-svn: .ver $(ObjDir)/Driver.o: $(ObjDir)/.ver-svn <file_sep>/test/Analysis/exercise-ps.c // RUN: clang-cc -analyze -checker-simple -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify %s // // Just exercise the analyzer on code that has at one point caused issues // (i.e., no assertions or crashes). static const char * f1(const char *x, char *y) { while (*x != 0) { *y++ = *x++; } } // This following case checks that we properly handle typedefs when getting // the RvalueType of an ElementRegion. typedef struct F12_struct {} F12_typedef; typedef void* void_typedef; void_typedef f2_helper(); static void f2(void *buf) { F12_typedef* x; x = f2_helper(); memcpy((&x[1]), (buf), 1); // expected-warning{{implicitly declaring C library function 'memcpy' with type 'void *(void *, void const *}} \ // expected-note{{please include the header <string.h> or explicitly provide a declaration for 'memcpy'}} } <file_sep>/tools/clang-cc/RewriteBlocks.cpp //===--- RewriteBlocks.cpp ----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Hacks and fun related to the closure rewriter. // //===----------------------------------------------------------------------===// #include "ASTConsumers.h" #include "clang/Rewrite/Rewriter.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/LangOptions.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include <sstream> using namespace clang; using llvm::utostr; namespace { class RewriteBlocks : public ASTConsumer { Rewriter Rewrite; Diagnostic &Diags; const LangOptions &LangOpts; unsigned RewriteFailedDiag; ASTContext *Context; SourceManager *SM; FileID MainFileID; const char *MainFileStart, *MainFileEnd; // Block expressions. llvm::SmallVector<BlockExpr *, 32> Blocks; llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs; llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs; // Block related declarations. llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls; llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls; llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; // The function/method we are rewriting. FunctionDecl *CurFunctionDef; ObjCMethodDecl *CurMethodDef; bool IsHeader; std::string InFileName; std::string OutFileName; std::string Preamble; public: RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D, const LangOptions &LOpts); ~RewriteBlocks() { // Get the buffer corresponding to MainFileID. // If we haven't changed it, then we are done. if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(MainFileID)) { std::string S(RewriteBuf->begin(), RewriteBuf->end()); printf("%s\n", S.c_str()); } else { printf("No changes\n"); } } void Initialize(ASTContext &context); void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen); void ReplaceText(SourceLocation Start, unsigned OrigLength, const char *NewStr, unsigned NewLength); // Top Level Driver code. virtual void HandleTopLevelDecl(DeclGroupRef D) { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) HandleTopLevelSingleDecl(*I); } void HandleTopLevelSingleDecl(Decl *D); void HandleDeclInMainFile(Decl *D); // Top level Stmt *RewriteFunctionBody(Stmt *S); void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); // Block specific rewrite rules. std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0); void RewriteBlockCall(CallExpr *Exp); void RewriteBlockPointerDecl(NamedDecl *VD); void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, const char *funcName, std::string Tag); std::string SynthesizeBlockFunc(BlockExpr *CE, int i, const char *funcName, std::string Tag); std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, bool hasCopyDisposeHelpers); std::string SynthesizeBlockCall(CallExpr *Exp); void SynthesizeBlockLiterals(SourceLocation FunLocStart, const char *FunName); void CollectBlockDeclRefInfo(BlockExpr *Exp); void GetBlockCallExprs(Stmt *S); void GetBlockDeclRefExprs(Stmt *S); // We avoid calling Type::isBlockPointerType(), since it operates on the // canonical type. We only care if the top-level type is a closure pointer. bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); } // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC1 && !LangOpts.ObjC2) return false; QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || OCT == Context->getCanonicalType(Context->getObjCClassType())) return true; if (const PointerType *PT = OCT->getAsPointerType()) { if (isa<ObjCInterfaceType>(PT->getPointeeType()) || isa<ObjCQualifiedIdType>(PT->getPointeeType())) return true; } return false; } // ObjC rewrite methods. void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl); void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl); void RewriteProtocolDecl(ObjCProtocolDecl *PDecl); void RewriteMethodDecl(ObjCMethodDecl *MDecl); void RewriteFunctionProtoType(QualType funcType, NamedDecl *D); void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); void RewriteCastExpr(CastExpr *CE); bool PointerTypeTakesAnyBlockArguments(QualType QT); void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); }; } static bool IsHeaderFile(const std::string &Filename) { std::string::size_type DotPos = Filename.rfind('.'); if (DotPos == std::string::npos) { // no file extension return false; } std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end()); // C header: .h // C++ header: .hh or .H; return Ext == "h" || Ext == "hh" || Ext == "H"; } RewriteBlocks::RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D, const LangOptions &LOpts) : Diags(D), LangOpts(LOpts) { IsHeader = IsHeaderFile(inFile); InFileName = inFile; OutFileName = outFile; CurFunctionDef = 0; CurMethodDef = 0; RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning, "rewriting failed"); } ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile, const std::string& OutFile, Diagnostic &Diags, const LangOptions &LangOpts) { return new RewriteBlocks(InFile, OutFile, Diags, LangOpts); } void RewriteBlocks::Initialize(ASTContext &context) { Context = &context; SM = &Context->getSourceManager(); // Get the ID and start/end of the main file. MainFileID = SM->getMainFileID(); const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID); MainFileStart = MainBuf->getBufferStart(); MainFileEnd = MainBuf->getBufferEnd(); Rewrite.setSourceMgr(Context->getSourceManager(), LangOpts); if (IsHeader) Preamble = "#pragma once\n"; Preamble += "#ifndef BLOCK_IMPL\n"; Preamble += "#define BLOCK_IMPL\n"; Preamble += "struct __block_impl {\n"; Preamble += " void *isa;\n"; Preamble += " int Flags;\n"; Preamble += " int Size;\n"; Preamble += " void *FuncPtr;\n"; Preamble += "};\n"; Preamble += "enum {\n"; Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n"; Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n"; Preamble += "};\n"; if (LangOpts.Microsoft) Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n"; else Preamble += "#define __OBJC_RW_EXTERN extern\n"; Preamble += "// Runtime copy/destroy helper functions\n"; Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n"; Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n"; Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n"; Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n"; Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n"; Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n"; Preamble += "#endif\n"; InsertText(SM->getLocForStartOfFile(MainFileID), Preamble.c_str(), Preamble.size()); } void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) { if (!Rewrite.InsertText(Loc, StrData, StrLen)) return; Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); } void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength, const char *NewStr, unsigned NewLength) { if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength)) return; Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); } void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) { bool haveBlockPtrs = false; for (ObjCMethodDecl::param_iterator I = Method->param_begin(), E = Method->param_end(); I != E; ++I) if (isBlockPointerType((*I)->getType())) haveBlockPtrs = true; if (!haveBlockPtrs) return; // Do a fuzzy rewrite. // We have 1 or more arguments that have closure pointers. SourceLocation Loc = Method->getLocStart(); SourceLocation LocEnd = Method->getLocEnd(); const char *startBuf = SM->getCharacterData(Loc); const char *endBuf = SM->getCharacterData(LocEnd); const char *methodPtr = startBuf; std::string Tag = "struct __block_impl *"; while (*methodPtr++ && (methodPtr != endBuf)) { switch (*methodPtr) { case ':': methodPtr++; if (*methodPtr == '(') { const char *scanType = ++methodPtr; bool foundBlockPointer = false; unsigned parenCount = 1; while (parenCount) { switch (*scanType) { case '(': parenCount++; break; case ')': parenCount--; break; case '^': foundBlockPointer = true; break; } scanType++; } if (foundBlockPointer) { // advance the location to startArgList. Loc = Loc.getFileLocWithOffset(methodPtr-startBuf); assert((Loc.isValid()) && "Invalid Loc"); ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size()); // Advance startBuf. Since the underlying buffer has changed, // it's very important to advance startBuf (so we can correctly // compute a relative Loc the next time around). startBuf = methodPtr; } // Advance the method ptr to the end of the type. methodPtr = scanType; } break; } } return; } void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(*Context), E = ClassDecl->instmeth_end(*Context); I != E; ++I) RewriteMethodDecl(*I); for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(*Context), E = ClassDecl->classmeth_end(*Context); I != E; ++I) RewriteMethodDecl(*I); } void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(*Context), E = CatDecl->instmeth_end(*Context); I != E; ++I) RewriteMethodDecl(*I); for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(*Context), E = CatDecl->classmeth_end(*Context); I != E; ++I) RewriteMethodDecl(*I); } void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(*Context), E = PDecl->instmeth_end(*Context); I != E; ++I) RewriteMethodDecl(*I); for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(*Context), E = PDecl->classmeth_end(*Context); I != E; ++I) RewriteMethodDecl(*I); } //===----------------------------------------------------------------------===// // Top Level Driver Code //===----------------------------------------------------------------------===// void RewriteBlocks::HandleTopLevelSingleDecl(Decl *D) { // Two cases: either the decl could be in the main file, or it could be in a // #included file. If the former, rewrite it now. If the later, check to see // if we rewrote the #include/#import. SourceLocation Loc = D->getLocation(); Loc = SM->getInstantiationLoc(Loc); // If this is for a builtin, ignore it. if (Loc.isInvalid()) return; if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) RewriteInterfaceDecl(MD); else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) RewriteCategoryDecl(CD); else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) RewriteProtocolDecl(PD); // If we have a decl in the main file, see if we should rewrite it. if (SM->isFromMainFile(Loc)) HandleDeclInMainFile(D); return; } std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i, const char *funcName, std::string Tag) { const FunctionType *AFT = CE->getFunctionType(); QualType RT = AFT->getResultType(); std::string StructRef = "struct " + Tag; std::string S = "static " + RT.getAsString() + " __" + funcName + "_" + "block_func_" + utostr(i); BlockDecl *BD = CE->getBlockDecl(); if (isa<FunctionNoProtoType>(AFT)) { S += "()"; } else if (BD->param_empty()) { S += "(" + StructRef + " *__cself)"; } else { const FunctionProtoType *FT = cast<FunctionProtoType>(AFT); assert(FT && "SynthesizeBlockFunc: No function proto"); S += '('; // first add the implicit argument. S += StructRef + " *__cself, "; std::string ParamStr; for (BlockDecl::param_iterator AI = BD->param_begin(), E = BD->param_end(); AI != E; ++AI) { if (AI != BD->param_begin()) S += ", "; ParamStr = (*AI)->getNameAsString(); (*AI)->getType().getAsStringInternal(ParamStr); S += ParamStr; } if (FT->isVariadic()) { if (!BD->param_empty()) S += ", "; S += "..."; } S += ')'; } S += " {\n"; // Create local declarations to avoid rewriting all closure decl ref exprs. // First, emit a declaration for all "by ref" decls. for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string Name = (*I)->getNameAsString(); Context->getPointerType((*I)->getType()).getAsStringInternal(Name); S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n"; } // Next, emit a declaration for all "by copy" declarations. for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; std::string Name = (*I)->getNameAsString(); // Handle nested closure invocation. For example: // // void (^myImportedClosure)(void); // myImportedClosure = ^(void) { setGlobalInt(x + y); }; // // void (^anotherClosure)(void); // anotherClosure = ^(void) { // myImportedClosure(); // import and invoke the closure // }; // if (isBlockPointerType((*I)->getType())) S += "struct __block_impl *"; else (*I)->getType().getAsStringInternal(Name); S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } std::string RewrittenStr = RewrittenBlockExprs[CE]; const char *cstr = RewrittenStr.c_str(); while (*cstr++ != '{') ; S += cstr; S += "\n"; return S; } std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, const char *funcName, std::string Tag) { std::string StructRef = "struct " + Tag; std::string S = "static void __"; S += funcName; S += "_block_copy_" + utostr(i); S += "(" + StructRef; S += "*dst, " + StructRef; S += "*src) {"; for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(), E = ImportedBlockDecls.end(); I != E; ++I) { S += "_Block_copy_assign(&dst->"; S += (*I)->getNameAsString(); S += ", src->"; S += (*I)->getNameAsString(); S += ");}"; } S += "\nstatic void __"; S += funcName; S += "_block_dispose_" + utostr(i); S += "(" + StructRef; S += "*src) {"; for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(), E = ImportedBlockDecls.end(); I != E; ++I) { S += "_Block_destroy(src->"; S += (*I)->getNameAsString(); S += ");"; } S += "}\n"; return S; } std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, bool hasCopyDisposeHelpers) { std::string S = "struct " + Tag; std::string Constructor = " " + Tag; S += " {\n struct __block_impl impl;\n"; if (hasCopyDisposeHelpers) S += " void *copy;\n void *dispose;\n"; Constructor += "(void *fp"; if (hasCopyDisposeHelpers) Constructor += ", void *copyHelp, void *disposeHelp"; if (BlockDeclRefs.size()) { // Output all "by copy" declarations. for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); std::string ArgName = "_" + FieldName; // Handle nested closure invocation. For example: // // void (^myImportedBlock)(void); // myImportedBlock = ^(void) { setGlobalInt(x + y); }; // // void (^anotherBlock)(void); // anotherBlock = ^(void) { // myImportedBlock(); // import and invoke the closure // }; // if (isBlockPointerType((*I)->getType())) { S += "struct __block_impl *"; Constructor += ", void *" + ArgName; } else { (*I)->getType().getAsStringInternal(FieldName); (*I)->getType().getAsStringInternal(ArgName); Constructor += ", " + ArgName; } S += FieldName + ";\n"; } // Output all "by ref" declarations. for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); std::string ArgName = "_" + FieldName; // Handle nested closure invocation. For example: // // void (^myImportedBlock)(void); // myImportedBlock = ^(void) { setGlobalInt(x + y); }; // // void (^anotherBlock)(void); // anotherBlock = ^(void) { // myImportedBlock(); // import and invoke the closure // }; // if (isBlockPointerType((*I)->getType())) { S += "struct __block_impl *"; Constructor += ", void *" + ArgName; } else { Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName); Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName); Constructor += ", " + ArgName; } S += FieldName + "; // by ref\n"; } // Finish writing the constructor. // FIXME: handle NSConcreteGlobalBlock. Constructor += ", int flags=0) {\n"; Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof("; Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n"; if (hasCopyDisposeHelpers) Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n"; // Initialize all "by copy" arguments. for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); Constructor += " "; if (isBlockPointerType((*I)->getType())) Constructor += Name + " = (struct __block_impl *)_"; else Constructor += Name + " = _"; Constructor += Name + ";\n"; } // Initialize all "by ref" arguments. for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); Constructor += " "; if (isBlockPointerType((*I)->getType())) Constructor += Name + " = (struct __block_impl *)_"; else Constructor += Name + " = _"; Constructor += Name + ";\n"; } } else { // Finish writing the constructor. // FIXME: handle NSConcreteGlobalBlock. Constructor += ", int flags=0) {\n"; Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof("; Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n"; if (hasCopyDisposeHelpers) Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n"; } Constructor += " "; Constructor += "}\n"; S += Constructor; S += "};\n"; return S; } void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart, const char *FunName) { // Insert closures that were part of the function. for (unsigned i = 0; i < Blocks.size(); i++) { CollectBlockDeclRefInfo(Blocks[i]); std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i); std::string CI = SynthesizeBlockImpl(Blocks[i], Tag, ImportedBlockDecls.size() > 0); InsertText(FunLocStart, CI.c_str(), CI.size()); std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag); InsertText(FunLocStart, CF.c_str(), CF.size()); if (ImportedBlockDecls.size()) { std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag); InsertText(FunLocStart, HF.c_str(), HF.size()); } BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByCopyDecls.clear(); BlockCallExprs.clear(); ImportedBlockDecls.clear(); } Blocks.clear(); RewrittenBlockExprs.clear(); } void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); const char *FuncName = FD->getNameAsCString(); SynthesizeBlockLiterals(FunLocStart, FuncName); } void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { SourceLocation FunLocStart = MD->getLocStart(); std::string FuncName = MD->getSelector().getAsString(); // Convert colons to underscores. std::string::size_type loc = 0; while ((loc = FuncName.find(":", loc)) != std::string::npos) FuncName.replace(loc, 1, "_"); SynthesizeBlockLiterals(FunLocStart, FuncName.c_str()); } void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) { for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; ++CI) if (*CI) { if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) GetBlockDeclRefExprs(CBE->getBody()); else GetBlockDeclRefExprs(*CI); } // Handle specific things. if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) // FIXME: Handle enums. if (!isa<FunctionDecl>(CDRE->getDecl())) BlockDeclRefs.push_back(CDRE); return; } void RewriteBlocks::GetBlockCallExprs(Stmt *S) { for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; ++CI) if (*CI) { if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) GetBlockCallExprs(CBE->getBody()); else GetBlockCallExprs(*CI); } if (CallExpr *CE = dyn_cast<CallExpr>(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE; } } return; } std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) { // Navigate to relevant type information. const char *closureName = 0; const BlockPointerType *CPT = 0; if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) { closureName = DRE->getDecl()->getNameAsCString(); CPT = DRE->getType()->getAsBlockPointerType(); } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) { closureName = CDRE->getDecl()->getNameAsCString(); CPT = CDRE->getType()->getAsBlockPointerType(); } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) { closureName = MExpr->getMemberDecl()->getNameAsCString(); CPT = MExpr->getType()->getAsBlockPointerType(); } else { assert(1 && "RewriteBlockClass: Bad type"); } assert(CPT && "RewriteBlockClass: Bad type"); const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType(); assert(FT && "RewriteBlockClass: Bad type"); const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); // FTP will be null for closures that don't take arguments. // Build a closure call - start with a paren expr to enforce precedence. std::string BlockCall = "("; // Synthesize the cast. BlockCall += "(" + Exp->getType().getAsString() + "(*)"; BlockCall += "(struct __block_impl *"; if (FTP) { for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), E = FTP->arg_type_end(); I && (I != E); ++I) BlockCall += ", " + (*I).getAsString(); } BlockCall += "))"; // close the argument list and paren expression. // Invoke the closure. We need to cast it since the declaration type is // bogus (it's a function pointer type) BlockCall += "((struct __block_impl *)"; std::string closureExprBufStr; llvm::raw_string_ostream closureExprBuf(closureExprBufStr); Exp->getCallee()->printPretty(closureExprBuf); BlockCall += closureExprBuf.str(); BlockCall += ")->FuncPtr)"; // Add the arguments. BlockCall += "((struct __block_impl *)"; BlockCall += closureExprBuf.str(); for (CallExpr::arg_iterator I = Exp->arg_begin(), E = Exp->arg_end(); I != E; ++I) { std::string syncExprBufS; llvm::raw_string_ostream Buf(syncExprBufS); (*I)->printPretty(Buf); BlockCall += ", " + Buf.str(); } return BlockCall; } void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) { std::string BlockCall = SynthesizeBlockCall(Exp); const char *startBuf = SM->getCharacterData(Exp->getLocStart()); const char *endBuf = SM->getCharacterData(Exp->getLocEnd()); ReplaceText(Exp->getLocStart(), endBuf-startBuf, BlockCall.c_str(), BlockCall.size()); } void RewriteBlocks::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) { // FIXME: Add more elaborate code generation required by the ABI. InsertText(BDRE->getLocStart(), "*", 1); } void RewriteBlocks::RewriteCastExpr(CastExpr *CE) { SourceLocation LocStart = CE->getLocStart(); SourceLocation LocEnd = CE->getLocEnd(); if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd)) return; const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); // advance the location to startArgList. const char *argPtr = startBuf; while (*argPtr++ && (argPtr < endBuf)) { switch (*argPtr) { case '^': // Replace the '^' with '*'. LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf); ReplaceText(LocStart, 1, "*", 1); break; } } return; } void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { SourceLocation DeclLoc = FD->getLocation(); unsigned parenCount = 0; // We have 1 or more arguments that have closure pointers. const char *startBuf = SM->getCharacterData(DeclLoc); const char *startArgList = strchr(startBuf, '('); assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); parenCount++; // advance the location to startArgList. DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf); assert((DeclLoc.isValid()) && "Invalid DeclLoc"); const char *argPtr = startArgList; while (*argPtr++ && parenCount) { switch (*argPtr) { case '^': // Replace the '^' with '*'. DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList); ReplaceText(DeclLoc, 1, "*", 1); break; case '(': parenCount++; break; case ')': parenCount--; break; } } return; } bool RewriteBlocks::PointerTypeTakesAnyBlockArguments(QualType QT) { const FunctionProtoType *FTP; const PointerType *PT = QT->getAsPointerType(); if (PT) { FTP = PT->getPointeeType()->getAsFunctionProtoType(); } else { const BlockPointerType *BPT = QT->getAsBlockPointerType(); assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); FTP = BPT->getPointeeType()->getAsFunctionProtoType(); } if (FTP) { for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), E = FTP->arg_type_end(); I != E; ++I) if (isBlockPointerType(*I)) return true; } return false; } void RewriteBlocks::GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen) { const char *argPtr = strchr(Name, '('); assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); LParen = argPtr; // output the start. argPtr++; // skip past the left paren. unsigned parenCount = 1; while (*argPtr && parenCount) { switch (*argPtr) { case '(': parenCount++; break; case ')': parenCount--; break; default: break; } if (parenCount) argPtr++; } assert((*argPtr == ')') && "Rewriter fuzzy parser confused"); RParen = argPtr; // output the end } void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { RewriteBlockPointerFunctionArgs(FD); return; } // Handle Variables and Typedefs. SourceLocation DeclLoc = ND->getLocation(); QualType DeclT; if (VarDecl *VD = dyn_cast<VarDecl>(ND)) DeclT = VD->getType(); else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND)) DeclT = TDD->getUnderlyingType(); else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND)) DeclT = FD->getType(); else assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled"); const char *startBuf = SM->getCharacterData(DeclLoc); const char *endBuf = startBuf; // scan backward (from the decl location) for the end of the previous decl. while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) startBuf--; // *startBuf != '^' if we are dealing with a pointer to function that // may take block argument types (which will be handled below). if (*startBuf == '^') { // Replace the '^' with '*', computing a negative offset. DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf); ReplaceText(DeclLoc, 1, "*", 1); } if (PointerTypeTakesAnyBlockArguments(DeclT)) { // Replace the '^' with '*' for arguments. DeclLoc = ND->getLocation(); startBuf = SM->getCharacterData(DeclLoc); const char *argListBegin, *argListEnd; GetExtentOfArgList(startBuf, argListBegin, argListEnd); while (argListBegin < argListEnd) { if (*argListBegin == '^') { SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf); ReplaceText(CaretLoc, 1, "*", 1); } argListBegin++; } } return; } void RewriteBlocks::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Add initializers for any closure decl refs. GetBlockDeclRefExprs(Exp->getBody()); if (BlockDeclRefs.size()) { // Unique all "by copy" declarations. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (!BlockDeclRefs[i]->isByRef()) BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl()); // Unique all "by ref" declarations. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->isByRef()) { BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl()); } // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (isBlockPointerType(BlockDeclRefs[i]->getType())) { GetBlockCallExprs(Blocks[i]); ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); } } } std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) { Blocks.push_back(Exp); CollectBlockDeclRefInfo(Exp); std::string FuncName; if (CurFunctionDef) FuncName = std::string(CurFunctionDef->getNameAsString()); else if (CurMethodDef) { FuncName = CurMethodDef->getSelector().getAsString(); // Convert colons to underscores. std::string::size_type loc = 0; while ((loc = FuncName.find(":", loc)) != std::string::npos) FuncName.replace(loc, 1, "_"); } else if (VD) FuncName = std::string(VD->getNameAsString()); std::string BlockNumber = utostr(Blocks.size()-1); std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber; std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; std::string FunkTypeStr; // Get a pointer to the function type so we can cast appropriately. Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr); // Rewrite the closure block with a compound literal. The first cast is // to prevent warnings from the C compiler. std::string Init = "(" + FunkTypeStr; Init += ")&" + Tag; // Initialize the block function. Init += "((void*)" + Func; if (ImportedBlockDecls.size()) { std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber; Init += ",(void*)" + Buf; Buf = "__" + FuncName + "_block_dispose_" + BlockNumber; Init += ",(void*)" + Buf; } // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { // Output all "by copy" declarations. for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { Init += ","; if (isObjCType((*I)->getType())) { Init += "[["; Init += (*I)->getNameAsString(); Init += " retain] autorelease]"; } else if (isBlockPointerType((*I)->getType())) { Init += "(void *)"; Init += (*I)->getNameAsString(); } else { Init += (*I)->getNameAsString(); } } // Output all "by ref" declarations. for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { Init += ",&"; Init += (*I)->getNameAsString(); } } Init += ")"; BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByCopyDecls.clear(); ImportedBlockDecls.clear(); return Init; } //===----------------------------------------------------------------------===// // Function Body / Expression rewriting //===----------------------------------------------------------------------===// Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) { // Start by rewriting all children. for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; ++CI) if (*CI) { if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) { Stmt *newStmt = RewriteFunctionBody(CBE->getBody()); if (newStmt) *CI = newStmt; // We've just rewritten the block body in place. // Now we snarf the rewritten text and stash it away for later use. std::string S = Rewrite.getRewritenText(CBE->getSourceRange()); RewrittenBlockExprs[CBE] = S; std::string Init = SynthesizeBlockInitExpr(CBE); // Do the rewrite, using S.size() which contains the rewritten size. ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size()); } else { Stmt *newStmt = RewriteFunctionBody(*CI); if (newStmt) *CI = newStmt; } } // Handle specific things. if (CallExpr *CE = dyn_cast<CallExpr>(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) RewriteBlockCall(CE); } if (CastExpr *CE = dyn_cast<CastExpr>(S)) { RewriteCastExpr(CE); } if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) { for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { Decl *SD = *DI; if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) { if (isBlockPointerType(ND->getType())) RewriteBlockPointerDecl(ND); else if (ND->getType()->isFunctionPointerType()) CheckFunctionPointerDecl(ND->getType(), ND); } if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) { if (isBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); } } } // Handle specific things. if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) { if (BDRE->isByRef()) RewriteBlockDeclRefExpr(BDRE); } // Return this stmt unmodified. return S; } void RewriteBlocks::RewriteFunctionProtoType(QualType funcType, NamedDecl *D) { if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) { for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(), E = fproto->arg_type_end(); I && (I != E); ++I) if (isBlockPointerType(*I)) { // All the args are checked/rewritten. Don't call twice! RewriteBlockPointerDecl(D); break; } } } void RewriteBlocks::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) { const PointerType *PT = funcType->getAsPointerType(); if (PT && PointerTypeTakesAnyBlockArguments(funcType)) RewriteFunctionProtoType(PT->getPointeeType(), ND); } /// HandleDeclInMainFile - This is called for each top-level decl defined in the /// main file of the input. void RewriteBlocks::HandleDeclInMainFile(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { // Since function prototypes don't have ParmDecl's, we check the function // prototype. This enables us to rewrite function declarations and // definitions using the same code. RewriteFunctionProtoType(FD->getType(), FD); if (CompoundStmt *Body = FD->getBody()) { CurFunctionDef = FD; FD->setBody(cast_or_null<CompoundStmt>(RewriteFunctionBody(Body))); // This synthesizes and inserts the block "impl" struct, invoke function, // and any copy/dispose helper functions. InsertBlockLiteralsWithinFunction(FD); CurFunctionDef = 0; } return; } if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { RewriteMethodDecl(MD); if (Stmt *Body = MD->getBody()) { CurMethodDef = MD; RewriteFunctionBody(Body); InsertBlockLiteralsWithinMethod(MD); CurMethodDef = 0; } } if (VarDecl *VD = dyn_cast<VarDecl>(D)) { if (isBlockPointerType(VD->getType())) { RewriteBlockPointerDecl(VD); if (VD->getInit()) { if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) { RewriteFunctionBody(CBE->getBody()); // We've just rewritten the block body in place. // Now we snarf the rewritten text and stash it away for later use. std::string S = Rewrite.getRewritenText(CBE->getSourceRange()); RewrittenBlockExprs[CBE] = S; std::string Init = SynthesizeBlockInitExpr(CBE, VD); // Do the rewrite, using S.size() which contains the rewritten size. ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size()); SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getNameAsCString()); } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) { RewriteCastExpr(CE); } } } else if (VD->getType()->isFunctionPointerType()) { CheckFunctionPointerDecl(VD->getType(), VD); if (VD->getInit()) { if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) { RewriteCastExpr(CE); } } } return; } if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { if (isBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); return; } if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) { if (RD->isDefinition()) { for (RecordDecl::field_iterator i = RD->field_begin(*Context), e = RD->field_end(*Context); i != e; ++i) { FieldDecl *FD = *i; if (isBlockPointerType(FD->getType())) RewriteBlockPointerDecl(FD); } } return; } } <file_sep>/lib/Sema/SemaInherit.h //===------ SemaInherit.h - C++ Inheritance ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides Sema data structures that help analyse C++ // inheritance semantics, including searching the inheritance // hierarchy. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_INHERIT_H #define LLVM_CLANG_SEMA_INHERIT_H #include "Sema.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/DeclBase.h" #include "clang/AST/Type.h" #include "clang/AST/TypeOrdering.h" #include "llvm/ADT/SmallVector.h" #include <list> #include <map> namespace clang { class CXXBaseSpecifier; /// BasePathElement - An element in a path from a derived class to a /// base class. Each step in the path references the link from a /// derived class to one of its direct base classes, along with a /// base "number" that identifies which base subobject of the /// original derived class we are referencing. struct BasePathElement { /// Base - The base specifier that states the link from a derived /// class to a base class, which will be followed by this base /// path element. const CXXBaseSpecifier *Base; /// Class - The record decl of the class that the base is a base of. const CXXRecordDecl *Class; /// SubobjectNumber - Identifies which base class subobject (of type /// @c Base->getType()) this base path element refers to. This /// value is only valid if @c !Base->isVirtual(), because there /// is no base numbering for the zero or one virtual bases of a /// given type. int SubobjectNumber; }; /// BasePath - Represents a path from a specific derived class /// (which is not represented as part of the path) to a particular /// (direct or indirect) base class subobject that contains some /// number of declarations with the same name. Individual elements /// in the path are described by the BasePathElement structure, /// which captures both the link from a derived class to one of its /// direct bases and identification describing which base class /// subobject is being used. struct BasePath : public llvm::SmallVector<BasePathElement, 4> { /// Decls - The set of declarations found inside this base class /// subobject. DeclContext::lookup_result Decls; }; /// BasePaths - Represents the set of paths from a derived class to /// one of its (direct or indirect) bases. For example, given the /// following class hierachy: /// /// @code /// class A { }; /// class B : public A { }; /// class C : public A { }; /// class D : public B, public C{ }; /// @endcode /// /// There are two potential BasePaths to represent paths from D to a /// base subobject of type A. One path is (D,0) -> (B,0) -> (A,0) /// and another is (D,0)->(C,0)->(A,1). These two paths actually /// refer to two different base class subobjects of the same type, /// so the BasePaths object refers to an ambiguous path. On the /// other hand, consider the following class hierarchy: /// /// @code /// class A { }; /// class B : public virtual A { }; /// class C : public virtual A { }; /// class D : public B, public C{ }; /// @endcode /// /// Here, there are two potential BasePaths again, (D, 0) -> (B, 0) /// -> (A,v) and (D, 0) -> (C, 0) -> (A, v), but since both of them /// refer to the same base class subobject of type A (the virtual /// one), there is no ambiguity. class BasePaths { /// Origin - The type from which this search originated. QualType Origin; /// Paths - The actual set of paths that can be taken from the /// derived class to the same base class. std::list<BasePath> Paths; /// ClassSubobjects - Records the class subobjects for each class /// type that we've seen. The first element in the pair says /// whether we found a path to a virtual base for that class type, /// while the element contains the number of non-virtual base /// class subobjects for that class type. The key of the map is /// the cv-unqualified canonical type of the base class subobject. std::map<QualType, std::pair<bool, unsigned>, QualTypeOrdering> ClassSubobjects; /// FindAmbiguities - Whether Sema::IsDerivedFrom should try find /// ambiguous paths while it is looking for a path from a derived /// type to a base type. bool FindAmbiguities; /// RecordPaths - Whether Sema::IsDerivedFrom should record paths /// while it is determining whether there are paths from a derived /// type to a base type. bool RecordPaths; /// DetectVirtual - Whether Sema::IsDerivedFrom should abort the search /// if it finds a path that goes across a virtual base. The virtual class /// is also recorded. bool DetectVirtual; /// ScratchPath - A BasePath that is used by Sema::IsDerivedFrom /// to help build the set of paths. BasePath ScratchPath; /// DetectedVirtual - The base class that is virtual. const RecordType *DetectedVirtual; /// \brief Array of the declarations that have been found. This /// array is constructed only if needed, e.g., to iterate over the /// results within LookupResult. NamedDecl **DeclsFound; unsigned NumDeclsFound; friend class Sema; void ComputeDeclsFound(); public: typedef std::list<BasePath>::const_iterator paths_iterator; /// BasePaths - Construct a new BasePaths structure to record the /// paths for a derived-to-base search. explicit BasePaths(bool FindAmbiguities = true, bool RecordPaths = true, bool DetectVirtual = true) : FindAmbiguities(FindAmbiguities), RecordPaths(RecordPaths), DetectVirtual(DetectVirtual), DetectedVirtual(0), DeclsFound(0), NumDeclsFound(0) {} ~BasePaths() { delete [] DeclsFound; } paths_iterator begin() const { return Paths.begin(); } paths_iterator end() const { return Paths.end(); } BasePath& front() { return Paths.front(); } const BasePath& front() const { return Paths.front(); } NamedDecl **found_decls_begin(); NamedDecl **found_decls_end(); bool isAmbiguous(QualType BaseType); /// isFindingAmbiguities - Whether we are finding multiple paths /// to detect ambiguities. bool isFindingAmbiguities() const { return FindAmbiguities; } /// isRecordingPaths - Whether we are recording paths. bool isRecordingPaths() const { return RecordPaths; } /// setRecordingPaths - Specify whether we should be recording /// paths or not. void setRecordingPaths(bool RP) { RecordPaths = RP; } /// isDetectingVirtual - Whether we are detecting virtual bases. bool isDetectingVirtual() const { return DetectVirtual; } /// getDetectedVirtual - The virtual base discovered on the path. const RecordType* getDetectedVirtual() const { return DetectedVirtual; } /// @brief Retrieve the type from which this base-paths search /// began QualType getOrigin() const { return Origin; } void setOrigin(QualType Type) { Origin = Type; } void clear(); void swap(BasePaths &Other); }; /// MemberLookupCriteria - Criteria for performing lookup of a /// member of a C++ class. Objects of this type are used to direct /// Sema::LookupCXXClassMember. struct MemberLookupCriteria { /// MemberLookupCriteria - Constructs member lookup criteria to /// search for a base class of type Base. explicit MemberLookupCriteria(QualType Base) : LookupBase(true), Base(Base) { } /// MemberLookupCriteria - Constructs member lookup criteria to /// search for a class member with the given Name. explicit MemberLookupCriteria(DeclarationName Name, Sema::LookupNameKind NameKind, unsigned IDNS) : LookupBase(false), Name(Name), NameKind(NameKind), IDNS(IDNS) { } /// LookupBase - True if we are looking for a base class (whose /// type is Base). If false, we are looking for a named member of /// the class (with the name Name). bool LookupBase; /// Base - The type of the base class we're searching for, if /// LookupBase is true. QualType Base; /// Name - The name of the member we're searching for, if /// LookupBase is false. DeclarationName Name; Sema::LookupNameKind NameKind; unsigned IDNS; }; } #endif <file_sep>/test/CodeGen/rdr-6098585-fallthrough-to-empty-range.c // RUN: clang-cc -triple i386-unknown-unknown --emit-llvm-bc -o - %s | opt -std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32 %" %t // Make sure return is not constant (if empty range is skipped or miscompiled) int f0(unsigned x) { switch(x) { case 2: // fallthrough empty range case 10 ... 9: return 10; default: return 0; } } <file_sep>/lib/Analysis/RegionStore.cpp //== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a basic region store model. In this model, we do have field // sensitivity. But we assume nothing about the heap shape. So recursive data // structures are largely ignored. Basically we do 1-limiting analysis. // Parameter pointers are assumed with no aliasing. Pointee objects of // parameters are created lazily. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/MemRegion.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/PathSensitive/GRStateTrait.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/ImmutableList.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Compiler.h" using namespace clang; // Actual Store type. typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy; //===----------------------------------------------------------------------===// // Region "Views" //===----------------------------------------------------------------------===// // // MemRegions can be layered on top of each other. This GDM entry tracks // what are the MemRegions that layer a given MemRegion. // typedef llvm::ImmutableSet<const MemRegion*> RegionViews; namespace { class VISIBILITY_HIDDEN RegionViewMap {}; } static int RegionViewMapIndex = 0; namespace clang { template<> struct GRStateTrait<RegionViewMap> : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*, RegionViews> > { static void* GDMIndex() { return &RegionViewMapIndex; } }; } //===----------------------------------------------------------------------===// // Region "Extents" //===----------------------------------------------------------------------===// // // MemRegions represent chunks of memory with a size (their "extent"). This // GDM entry tracks the extents for regions. Extents are in bytes. // namespace { class VISIBILITY_HIDDEN RegionExtents {}; } static int RegionExtentsIndex = 0; namespace clang { template<> struct GRStateTrait<RegionExtents> : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*, SVal> > { static void* GDMIndex() { return &RegionExtentsIndex; } }; } //===----------------------------------------------------------------------===// // Region "killsets". //===----------------------------------------------------------------------===// // // RegionStore lazily adds value bindings to regions when the analyzer handles // assignment statements. Killsets track which default values have been // killed, thus distinguishing between "unknown" values and default // values. Regions are added to killset only when they are assigned "unknown" // directly, otherwise we should have their value in the region bindings. // namespace { class VISIBILITY_HIDDEN RegionKills {}; } static int RegionKillsIndex = 0; namespace clang { template<> struct GRStateTrait<RegionKills> : public GRStatePartialTrait< llvm::ImmutableSet<const MemRegion*> > { static void* GDMIndex() { return &RegionKillsIndex; } }; } //===----------------------------------------------------------------------===// // Regions with default values. //===----------------------------------------------------------------------===// // // This GDM entry tracks what regions have a default value if they have no bound // value and have not been killed. // namespace { class VISIBILITY_HIDDEN RegionDefaultValue {}; } static int RegionDefaultValueIndex = 0; namespace clang { template<> struct GRStateTrait<RegionDefaultValue> : public GRStatePartialTrait<llvm::ImmutableMap<const MemRegion*, SVal> > { static void* GDMIndex() { return &RegionDefaultValueIndex; } }; } //===----------------------------------------------------------------------===// // Main RegionStore logic. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN RegionStoreSubRegionMap : public SubRegionMap { typedef llvm::DenseMap<const MemRegion*, llvm::ImmutableSet<const MemRegion*> > Map; llvm::ImmutableSet<const MemRegion*>::Factory F; Map M; public: void add(const MemRegion* Parent, const MemRegion* SubRegion) { Map::iterator I = M.find(Parent); M.insert(std::make_pair(Parent, F.Add(I == M.end() ? F.GetEmptySet() : I->second, SubRegion))); } ~RegionStoreSubRegionMap() {} bool iterSubRegions(const MemRegion* Parent, Visitor& V) const { Map::iterator I = M.find(Parent); if (I == M.end()) return true; llvm::ImmutableSet<const MemRegion*> S = I->second; for (llvm::ImmutableSet<const MemRegion*>::iterator SI=S.begin(),SE=S.end(); SI != SE; ++SI) { if (!V.Visit(Parent, *SI)) return false; } return true; } }; class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager { RegionBindingsTy::Factory RBFactory; RegionViews::Factory RVFactory; GRStateManager& StateMgr; const MemRegion* SelfRegion; const ImplicitParamDecl *SelfDecl; public: RegionStoreManager(GRStateManager& mgr) : StoreManager(mgr.getValueManager()), RBFactory(mgr.getAllocator()), RVFactory(mgr.getAllocator()), StateMgr(mgr), SelfRegion(0), SelfDecl(0) { if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(&StateMgr.getCodeDecl())) SelfDecl = MD->getSelfDecl(); } virtual ~RegionStoreManager() {} SubRegionMap* getSubRegionMap(const GRState *state); const GRState* BindCompoundLiteral(const GRState* St, const CompoundLiteralExpr* CL, SVal V); /// getLValueString - Returns an SVal representing the lvalue of a /// StringLiteral. Within RegionStore a StringLiteral has an /// associated StringRegion, and the lvalue of a StringLiteral is /// the lvalue of that region. SVal getLValueString(const GRState* St, const StringLiteral* S); /// getLValueCompoundLiteral - Returns an SVal representing the /// lvalue of a compound literal. Within RegionStore a compound /// literal has an associated region, and the lvalue of the /// compound literal is the lvalue of that region. SVal getLValueCompoundLiteral(const GRState* St, const CompoundLiteralExpr*); /// getLValueVar - Returns an SVal that represents the lvalue of a /// variable. Within RegionStore a variable has an associated /// VarRegion, and the lvalue of the variable is the lvalue of that region. SVal getLValueVar(const GRState* St, const VarDecl* VD); SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base); SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D); SVal getLValueFieldOrIvar(const GRState* St, SVal Base, const Decl* D); SVal getLValueElement(const GRState* St, SVal Base, SVal Offset); SVal getSizeInElements(const GRState* St, const MemRegion* R); /// ArrayToPointer - Emulates the "decay" of an array to a pointer /// type. 'Array' represents the lvalue of the array being decayed /// to a pointer, and the returned SVal represents the decayed /// version of that lvalue (i.e., a pointer to the first element of /// the array). This is called by GRExprEngine when evaluating /// casts from arrays to pointers. SVal ArrayToPointer(Loc Array); /// CastRegion - Used by GRExprEngine::VisitCast to handle casts from /// a MemRegion* to a specific location type. 'R' is the region being /// casted and 'CastToTy' the result type of the cast. CastResult CastRegion(const GRState* state, const MemRegion* R, QualType CastToTy); SVal EvalBinOp(BinaryOperator::Opcode Op, Loc L, NonLoc R); /// The high level logic for this method is this: /// Retrieve (L) /// if L has binding /// return L's binding /// else if L is in killset /// return unknown /// else /// if L is on stack or heap /// return undefined /// else /// return symbolic SVal Retrieve(const GRState* state, Loc L, QualType T = QualType()); const GRState* Bind(const GRState* St, Loc LV, SVal V); Store Remove(Store store, Loc LV); Store getInitialStore() { return RBFactory.GetEmptyMap().getRoot(); } /// getSelfRegion - Returns the region for the 'self' (Objective-C) or /// 'this' object (C++). When used when analyzing a normal function this /// method returns NULL. const MemRegion* getSelfRegion(Store) { if (!SelfDecl) return 0; if (!SelfRegion) { const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(&StateMgr.getCodeDecl()); SelfRegion = MRMgr.getObjCObjectRegion(MD->getClassInterface(), MRMgr.getHeapRegion()); } return SelfRegion; } /// RemoveDeadBindings - Scans the RegionStore of 'state' for dead values. /// It returns a new Store with these values removed, and populates LSymbols // and DSymbols with the known set of live and dead symbols respectively. Store RemoveDeadBindings(const GRState* state, Stmt* Loc, SymbolReaper& SymReaper, llvm::SmallVectorImpl<const MemRegion*>& RegionRoots); const GRState* BindDecl(const GRState* St, const VarDecl* VD, SVal InitVal); const GRState* BindDeclWithNoInit(const GRState* St, const VarDecl* VD) { return St; } const GRState* setExtent(const GRState* St, const MemRegion* R, SVal Extent); static inline RegionBindingsTy GetRegionBindings(Store store) { return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store)); } void print(Store store, std::ostream& Out, const char* nl, const char *sep); void iterBindings(Store store, BindingsHandler& f) { // FIXME: Implement. } private: const GRState* BindArray(const GRState* St, const TypedRegion* R, SVal V); /// Retrieve the values in a struct and return a CompoundVal, used when doing /// struct copy: /// struct s x, y; /// x = y; /// y's value is retrieved by this method. SVal RetrieveStruct(const GRState* St, const TypedRegion* R); const GRState* BindStruct(const GRState* St, const TypedRegion* R, SVal V); /// KillStruct - Set the entire struct to unknown. const GRState* KillStruct(const GRState* St, const TypedRegion* R); // Utility methods. BasicValueFactory& getBasicVals() { return StateMgr.getBasicVals(); } ASTContext& getContext() { return StateMgr.getContext(); } SymbolManager& getSymbolManager() { return StateMgr.getSymbolManager(); } const GRState* AddRegionView(const GRState* St, const MemRegion* View, const MemRegion* Base); const GRState* RemoveRegionView(const GRState* St, const MemRegion* View, const MemRegion* Base); }; } // end anonymous namespace StoreManager* clang::CreateRegionStoreManager(GRStateManager& StMgr) { return new RegionStoreManager(StMgr); } SubRegionMap* RegionStoreManager::getSubRegionMap(const GRState *state) { RegionBindingsTy B = GetRegionBindings(state->getStore()); RegionStoreSubRegionMap *M = new RegionStoreSubRegionMap(); for (RegionBindingsTy::iterator I=B.begin(), E=B.end(); I!=E; ++I) { if (const SubRegion* R = dyn_cast<SubRegion>(I.getKey())) M->add(R->getSuperRegion(), R); } return M; } /// getLValueString - Returns an SVal representing the lvalue of a /// StringLiteral. Within RegionStore a StringLiteral has an /// associated StringRegion, and the lvalue of a StringLiteral is the /// lvalue of that region. SVal RegionStoreManager::getLValueString(const GRState* St, const StringLiteral* S) { return loc::MemRegionVal(MRMgr.getStringRegion(S)); } /// getLValueVar - Returns an SVal that represents the lvalue of a /// variable. Within RegionStore a variable has an associated /// VarRegion, and the lvalue of the variable is the lvalue of that region. SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) { return loc::MemRegionVal(MRMgr.getVarRegion(VD)); } /// getLValueCompoundLiteral - Returns an SVal representing the lvalue /// of a compound literal. Within RegionStore a compound literal /// has an associated region, and the lvalue of the compound literal /// is the lvalue of that region. SVal RegionStoreManager::getLValueCompoundLiteral(const GRState* St, const CompoundLiteralExpr* CL) { return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL)); } SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base) { return getLValueFieldOrIvar(St, Base, D); } SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base, const FieldDecl* D) { return getLValueFieldOrIvar(St, Base, D); } SVal RegionStoreManager::getLValueFieldOrIvar(const GRState* St, SVal Base, const Decl* D) { if (Base.isUnknownOrUndef()) return Base; Loc BaseL = cast<Loc>(Base); const MemRegion* BaseR = 0; switch (BaseL.getSubKind()) { case loc::MemRegionKind: BaseR = cast<loc::MemRegionVal>(BaseL).getRegion(); if (const SymbolicRegion* SR = dyn_cast<SymbolicRegion>(BaseR)) { SymbolRef Sym = SR->getSymbol(); BaseR = MRMgr.getTypedViewRegion(Sym->getType(getContext()), SR); } break; case loc::GotoLabelKind: case loc::FuncValKind: // These are anormal cases. Flag an undefined value. return UndefinedVal(); case loc::ConcreteIntKind: // While these seem funny, this can happen through casts. // FIXME: What we should return is the field offset. For example, // add the field offset to the integer value. That way funny things // like this work properly: &(((struct foo *) 0xa)->f) return Base; default: assert(0 && "Unhandled Base."); return Base; } // NOTE: We must have this check first because ObjCIvarDecl is a subclass // of FieldDecl. if (const ObjCIvarDecl *ID = dyn_cast<ObjCIvarDecl>(D)) return loc::MemRegionVal(MRMgr.getObjCIvarRegion(ID, BaseR)); return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR)); } SVal RegionStoreManager::getLValueElement(const GRState* St, SVal Base, SVal Offset) { // If the base is an unknown or undefined value, just return it back. // FIXME: For absolute pointer addresses, we just return that value back as // well, although in reality we should return the offset added to that // value. if (Base.isUnknownOrUndef() || isa<loc::ConcreteInt>(Base)) return Base; // Only handle integer offsets... for now. if (!isa<nonloc::ConcreteInt>(Offset)) return UnknownVal(); const TypedRegion* BaseRegion = 0; const MemRegion* R = cast<loc::MemRegionVal>(Base).getRegion(); if (const SymbolicRegion* SR = dyn_cast<SymbolicRegion>(R)) { SymbolRef Sym = SR->getSymbol(); BaseRegion = MRMgr.getTypedViewRegion(Sym->getType(getContext()), SR); } else BaseRegion = cast<TypedRegion>(R); // Pointer of any type can be cast and used as array base. const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion); if (!ElemR) { // // If the base region is not an ElementRegion, create one. // This can happen in the following example: // // char *p = __builtin_alloc(10); // p[1] = 8; // // Observe that 'p' binds to an TypedViewRegion<AllocaRegion>. // // Offset might be unsigned. We have to convert it to signed ConcreteInt. if (nonloc::ConcreteInt* CI = dyn_cast<nonloc::ConcreteInt>(&Offset)) { const llvm::APSInt& OffI = CI->getValue(); if (OffI.isUnsigned()) { llvm::APSInt Tmp = OffI; Tmp.setIsSigned(true); Offset = NonLoc::MakeVal(getBasicVals(), Tmp); } } return loc::MemRegionVal(MRMgr.getElementRegion(Offset, BaseRegion)); } SVal BaseIdx = ElemR->getIndex(); if (!isa<nonloc::ConcreteInt>(BaseIdx)) return UnknownVal(); const llvm::APSInt& BaseIdxI = cast<nonloc::ConcreteInt>(BaseIdx).getValue(); const llvm::APSInt& OffI = cast<nonloc::ConcreteInt>(Offset).getValue(); assert(BaseIdxI.isSigned()); // FIXME: This appears to be the assumption of this code. We should review // whether or not BaseIdxI.getBitWidth() < OffI.getBitWidth(). If it // can't we need to put a comment here. If it can, we should handle it. assert(BaseIdxI.getBitWidth() >= OffI.getBitWidth()); const TypedRegion *ArrayR = ElemR->getArrayRegion(); SVal NewIdx; if (OffI.isUnsigned() || OffI.getBitWidth() < BaseIdxI.getBitWidth()) { // 'Offset' might be unsigned. We have to convert it to signed and // possibly extend it. llvm::APSInt Tmp = OffI; if (OffI.getBitWidth() < BaseIdxI.getBitWidth()) Tmp.extend(BaseIdxI.getBitWidth()); Tmp.setIsSigned(true); Tmp += BaseIdxI; // Compute the new offset. NewIdx = NonLoc::MakeVal(getBasicVals(), Tmp); } else NewIdx = nonloc::ConcreteInt(getBasicVals().getValue(BaseIdxI + OffI)); return loc::MemRegionVal(MRMgr.getElementRegion(NewIdx, ArrayR)); } SVal RegionStoreManager::getSizeInElements(const GRState* St, const MemRegion* R) { if (const VarRegion* VR = dyn_cast<VarRegion>(R)) { // Get the type of the variable. QualType T = VR->getDesugaredRValueType(getContext()); // FIXME: Handle variable-length arrays. if (isa<VariableArrayType>(T)) return UnknownVal(); if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(T)) { // return the size as signed integer. return NonLoc::MakeVal(getBasicVals(), CAT->getSize(), false); } // Clients can use ordinary variables as if they were arrays. These // essentially are arrays of size 1. return NonLoc::MakeIntVal(getBasicVals(), 1, false); } if (const StringRegion* SR = dyn_cast<StringRegion>(R)) { const StringLiteral* Str = SR->getStringLiteral(); // We intentionally made the size value signed because it participates in // operations with signed indices. return NonLoc::MakeIntVal(getBasicVals(), Str->getByteLength()+1, false); } if (const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R)) { #if 0 // FIXME: This logic doesn't really work, as we can have all sorts of // weird cases. For example, this crashes on test case 'rdar-6442306-1.m'. // The weird cases come in when arbitrary casting comes into play, violating // any type-safe programming. GRStateRef state(St, StateMgr); // Get the size of the super region in bytes. const SVal* Extent = state.get<RegionExtents>(ATR->getSuperRegion()); assert(Extent && "region extent not exist"); // Assume it's ConcreteInt for now. llvm::APSInt SSize = cast<nonloc::ConcreteInt>(*Extent).getValue(); // Get the size of the element in bits. QualType LvT = ATR->getLValueType(getContext()); QualType ElemTy = cast<PointerType>(LvT.getTypePtr())->getPointeeType(); uint64_t X = getContext().getTypeSize(ElemTy); const llvm::APSInt& ESize = getBasicVals().getValue(X, SSize.getBitWidth(), false); // Calculate the number of elements. // FIXME: What do we do with signed-ness problem? Shall we make all APSInts // signed? if (SSize.isUnsigned()) SSize.setIsSigned(true); // FIXME: move this operation into BasicVals. const llvm::APSInt S = (SSize * getBasicVals().getValue(8, SSize.getBitWidth(), false)) / ESize; return NonLoc::MakeVal(getBasicVals(), S); #else ATR = ATR; return UnknownVal(); #endif } if (const FieldRegion* FR = dyn_cast<FieldRegion>(R)) { // FIXME: Unsupported yet. FR = 0; return UnknownVal(); } if (isa<SymbolicRegion>(R)) { return UnknownVal(); } assert(0 && "Other regions are not supported yet."); return UnknownVal(); } /// ArrayToPointer - Emulates the "decay" of an array to a pointer /// type. 'Array' represents the lvalue of the array being decayed /// to a pointer, and the returned SVal represents the decayed /// version of that lvalue (i.e., a pointer to the first element of /// the array). This is called by GRExprEngine when evaluating casts /// from arrays to pointers. SVal RegionStoreManager::ArrayToPointer(Loc Array) { if (!isa<loc::MemRegionVal>(Array)) return UnknownVal(); const MemRegion* R = cast<loc::MemRegionVal>(&Array)->getRegion(); const TypedRegion* ArrayR = dyn_cast<TypedRegion>(R); if (!ArrayR) return UnknownVal(); nonloc::ConcreteInt Idx(getBasicVals().getZeroWithPtrWidth(false)); ElementRegion* ER = MRMgr.getElementRegion(Idx, ArrayR); return loc::MemRegionVal(ER); } StoreManager::CastResult RegionStoreManager::CastRegion(const GRState* state, const MemRegion* R, QualType CastToTy) { // Return the same region if the region types are compatible. if (const TypedRegion* TR = dyn_cast<TypedRegion>(R)) { ASTContext& Ctx = StateMgr.getContext(); QualType Ta = Ctx.getCanonicalType(TR->getLValueType(Ctx)); QualType Tb = Ctx.getCanonicalType(CastToTy); if (Ta == Tb) return CastResult(state, R); } // FIXME: We should handle the case when we are casting *back* to a // previous type. For example: // // void* x = ...; // char* y = (char*) x; // void* z = (void*) y; // <-- we should get the same region that is // bound to 'x' const MemRegion* ViewR = MRMgr.getTypedViewRegion(CastToTy, R); return CastResult(AddRegionView(state, ViewR, R), ViewR); } SVal RegionStoreManager::EvalBinOp(BinaryOperator::Opcode Op, Loc L, NonLoc R) { // Assume the base location is MemRegionVal(ElementRegion). if (!isa<loc::MemRegionVal>(L)) return UnknownVal(); const MemRegion* MR = cast<loc::MemRegionVal>(L).getRegion(); if (isa<SymbolicRegion>(MR)) return UnknownVal(); const TypedRegion* TR = cast<TypedRegion>(MR); const ElementRegion* ER = dyn_cast<ElementRegion>(TR); if (!ER) { // If the region is not element region, create one with index 0. This can // happen in the following example: // char *p = foo(); // p += 3; // Note that p binds to a TypedViewRegion(SymbolicRegion). nonloc::ConcreteInt Idx(getBasicVals().getZeroWithPtrWidth(false)); ER = MRMgr.getElementRegion(Idx, TR); } SVal Idx = ER->getIndex(); nonloc::ConcreteInt* Base = dyn_cast<nonloc::ConcreteInt>(&Idx); nonloc::ConcreteInt* Offset = dyn_cast<nonloc::ConcreteInt>(&R); // Only support concrete integer indexes for now. if (Base && Offset) { // FIXME: For now, convert the signedness and bitwidth of offset in case // they don't match. This can result from pointer arithmetic. In reality, // we should figure out what are the proper semantics and implement them. // // This addresses the test case test/Analysis/ptr-arith.c // nonloc::ConcreteInt OffConverted(getBasicVals().Convert(Base->getValue(), Offset->getValue())); SVal NewIdx = Base->EvalBinOp(getBasicVals(), Op, OffConverted); const MemRegion* NewER = MRMgr.getElementRegion(NewIdx, ER->getArrayRegion()); return Loc::MakeVal(NewER); } return UnknownVal(); } SVal RegionStoreManager::Retrieve(const GRState* St, Loc L, QualType T) { assert(!isa<UnknownVal>(L) && "location unknown"); assert(!isa<UndefinedVal>(L) && "location undefined"); // FIXME: Is this even possible? Shouldn't this be treated as a null // dereference at a higher level? if (isa<loc::ConcreteInt>(L)) return UndefinedVal(); // FIXME: Should this be refactored into GRExprEngine or GRStateManager? // It seems that all StoreManagers would do the same thing here. if (isa<loc::FuncVal>(L)) return L; const MemRegion* MR = cast<loc::MemRegionVal>(L).getRegion(); // We return unknown for symbolic region for now. This might be improved. // Example: // void f(int* p) { int x = *p; } if (isa<SymbolicRegion>(MR)) return UnknownVal(); // FIXME: Perhaps this method should just take a 'const MemRegion*' argument // instead of 'Loc', and have the other Loc cases handled at a higher level. const TypedRegion* R = cast<TypedRegion>(MR); assert(R && "bad region"); // FIXME: We should eventually handle funny addressing. e.g.: // // int x = ...; // int *p = &x; // char *q = (char*) p; // char c = *q; // returns the first byte of 'x'. // // Such funny addressing will occur due to layering of regions. QualType RTy = R->getRValueType(getContext()); if (RTy->isStructureType()) return RetrieveStruct(St, R); // FIXME: handle Vector types. if (RTy->isVectorType()) return UnknownVal(); RegionBindingsTy B = GetRegionBindings(St->getStore()); RegionBindingsTy::data_type* V = B.lookup(R); // Check if the region has a binding. if (V) return *V; GRStateRef state(St, StateMgr); // Check if the region is in killset. if (state.contains<RegionKills>(R)) return UnknownVal(); // If the region is an element or field, it may have a default value. if (isa<ElementRegion>(R) || isa<FieldRegion>(R)) { const MemRegion* SuperR = cast<SubRegion>(R)->getSuperRegion(); GRStateTrait<RegionDefaultValue>::lookup_type D = state.get<RegionDefaultValue>(SuperR); if (D) return *D; } if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) { const MemRegion *SR = IVR->getSuperRegion(); // If the super region is 'self' then return the symbol representing // the value of the ivar upon entry to the method. if (SR == SelfRegion) { // FIXME: Do we need to handle the case where the super region // has a view? We want to canonicalize the bindings. return ValMgr.getRValueSymbolVal(R); } // Otherwise, we need a new symbol. For now return Unknown. return UnknownVal(); } // The location does not have a bound value. This means that it has // the value it had upon its creation and/or entry to the analyzed // function/method. These are either symbolic values or 'undefined'. // We treat function parameters as symbolic values. if (const VarRegion* VR = dyn_cast<VarRegion>(R)) { const VarDecl *VD = VR->getDecl(); if (VD == SelfDecl) return loc::MemRegionVal(getSelfRegion(0)); if (isa<ParmVarDecl>(VD) || isa<ImplicitParamDecl>(VD) || VD->hasGlobalStorage()) { QualType VTy = VD->getType(); if (Loc::IsLocType(VTy) || VTy->isIntegerType()) return ValMgr.getRValueSymbolVal(VR); else return UnknownVal(); } } if (MRMgr.onStack(R) || MRMgr.onHeap(R)) { // All stack variables are considered to have undefined values // upon creation. All heap allocated blocks are considered to // have undefined values as well unless they are explicitly bound // to specific values. return UndefinedVal(); } // All other integer values are symbolic. if (Loc::IsLocType(RTy) || RTy->isIntegerType()) return ValMgr.getRValueSymbolVal(R); else return UnknownVal(); } SVal RegionStoreManager::RetrieveStruct(const GRState* St,const TypedRegion* R){ Store store = St->getStore(); GRStateRef state(St, StateMgr); // FIXME: Verify we want getRValueType instead of getLValueType. QualType T = R->getRValueType(getContext()); assert(T->isStructureType()); const RecordType* RT = cast<RecordType>(T.getTypePtr()); RecordDecl* RD = RT->getDecl(); assert(RD->isDefinition()); llvm::ImmutableList<SVal> StructVal = getBasicVals().getEmptySValList(); std::vector<FieldDecl *> Fields(RD->field_begin(getContext()), RD->field_end(getContext())); for (std::vector<FieldDecl *>::reverse_iterator Field = Fields.rbegin(), FieldEnd = Fields.rend(); Field != FieldEnd; ++Field) { FieldRegion* FR = MRMgr.getFieldRegion(*Field, R); RegionBindingsTy B = GetRegionBindings(store); RegionBindingsTy::data_type* data = B.lookup(FR); SVal FieldValue; if (data) FieldValue = *data; else if (state.contains<RegionKills>(FR)) FieldValue = UnknownVal(); else { if (MRMgr.onStack(FR) || MRMgr.onHeap(FR)) FieldValue = UndefinedVal(); else FieldValue = ValMgr.getRValueSymbolVal(FR); } StructVal = getBasicVals().consVals(FieldValue, StructVal); } return NonLoc::MakeCompoundVal(T, StructVal, getBasicVals()); } const GRState* RegionStoreManager::Bind(const GRState* St, Loc L, SVal V) { // If we get here, the location should be a region. const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion(); assert(R); // Check if the region is a struct region. if (const TypedRegion* TR = dyn_cast<TypedRegion>(R)) // FIXME: Verify we want getRValueType(). if (TR->getRValueType(getContext())->isStructureType()) return BindStruct(St, TR, V); Store store = St->getStore(); RegionBindingsTy B = GetRegionBindings(store); if (V.isUnknown()) { // Remove the binding. store = RBFactory.Remove(B, R).getRoot(); // Add the region to the killset. GRStateRef state(St, StateMgr); St = state.add<RegionKills>(R); } else store = RBFactory.Add(B, R, V).getRoot(); return StateMgr.MakeStateWithStore(St, store); } Store RegionStoreManager::Remove(Store store, Loc L) { const MemRegion* R = 0; if (isa<loc::MemRegionVal>(L)) R = cast<loc::MemRegionVal>(L).getRegion(); if (R) { RegionBindingsTy B = GetRegionBindings(store); return RBFactory.Remove(B, R).getRoot(); } return store; } const GRState* RegionStoreManager::BindDecl(const GRState* St, const VarDecl* VD, SVal InitVal) { QualType T = VD->getType(); VarRegion* VR = MRMgr.getVarRegion(VD); if (T->isArrayType()) return BindArray(St, VR, InitVal); if (T->isStructureType()) return BindStruct(St, VR, InitVal); return Bind(St, Loc::MakeVal(VR), InitVal); } // FIXME: this method should be merged into Bind(). const GRState* RegionStoreManager::BindCompoundLiteral(const GRState* St, const CompoundLiteralExpr* CL, SVal V) { CompoundLiteralRegion* R = MRMgr.getCompoundLiteralRegion(CL); return Bind(St, loc::MemRegionVal(R), V); } const GRState* RegionStoreManager::setExtent(const GRState* St, const MemRegion* R, SVal Extent) { GRStateRef state(St, StateMgr); return state.set<RegionExtents>(R, Extent); } static void UpdateLiveSymbols(SVal X, SymbolReaper& SymReaper) { if (loc::MemRegionVal *XR = dyn_cast<loc::MemRegionVal>(&X)) { const MemRegion *R = XR->getRegion(); while (R) { if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) { SymReaper.markLive(SR->getSymbol()); return; } if (const SubRegion *SR = dyn_cast<SubRegion>(R)) { R = SR->getSuperRegion(); continue; } break; } return; } for (SVal::symbol_iterator SI=X.symbol_begin(), SE=X.symbol_end();SI!=SE;++SI) SymReaper.markLive(*SI); } Store RegionStoreManager::RemoveDeadBindings(const GRState* state, Stmt* Loc, SymbolReaper& SymReaper, llvm::SmallVectorImpl<const MemRegion*>& RegionRoots) { Store store = state->getStore(); RegionBindingsTy B = GetRegionBindings(store); // Lazily constructed backmap from MemRegions to SubRegions. typedef llvm::ImmutableSet<const MemRegion*> SubRegionsTy; typedef llvm::ImmutableMap<const MemRegion*, SubRegionsTy> SubRegionsMapTy; // FIXME: As a future optimization we can modifiy BumpPtrAllocator to have // the ability to reuse memory. This way we can keep TmpAlloc around as // an instance variable of RegionStoreManager (avoiding repeated malloc // overhead). llvm::BumpPtrAllocator TmpAlloc; // Factory objects. SubRegionsMapTy::Factory SubRegMapF(TmpAlloc); SubRegionsTy::Factory SubRegF(TmpAlloc); // The backmap from regions to subregions. SubRegionsMapTy SubRegMap = SubRegMapF.GetEmptyMap(); // Do a pass over the regions in the store. For VarRegions we check if // the variable is still live and if so add it to the list of live roots. // For other regions we populate our region backmap. llvm::SmallVector<const MemRegion*, 10> IntermediateRoots; for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { IntermediateRoots.push_back(I.getKey()); } while (!IntermediateRoots.empty()) { const MemRegion* R = IntermediateRoots.back(); IntermediateRoots.pop_back(); if (const VarRegion* VR = dyn_cast<VarRegion>(R)) { if (SymReaper.isLive(Loc, VR->getDecl())) RegionRoots.push_back(VR); // This is a live "root". } else { // Get the super region for R. const MemRegion* SuperR = cast<SubRegion>(R)->getSuperRegion(); // Get the current set of subregions for SuperR. const SubRegionsTy* SRptr = SubRegMap.lookup(SuperR); SubRegionsTy SR = SRptr ? *SRptr : SubRegF.GetEmptySet(); // Add R to the subregions of SuperR. SubRegMap = SubRegMapF.Add(SubRegMap, SuperR, SubRegF.Add(SR, R)); // Super region may be VarRegion or subregion of another VarRegion. Add it // to the work list. if (isa<SubRegion>(SuperR)) IntermediateRoots.push_back(SuperR); } } // Process the worklist of RegionRoots. This performs a "mark-and-sweep" // of the store. We want to find all live symbols and dead regions. llvm::SmallPtrSet<const MemRegion*, 10> Marked; while (!RegionRoots.empty()) { // Dequeue the next region on the worklist. const MemRegion* R = RegionRoots.back(); RegionRoots.pop_back(); // Check if we have already processed this region. if (Marked.count(R)) continue; // Mark this region as processed. This is needed for termination in case // a region is referenced more than once. Marked.insert(R); // Mark the symbol for any live SymbolicRegion as "live". This means we // should continue to track that symbol. if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(R)) SymReaper.markLive(SymR->getSymbol()); // Get the data binding for R (if any). RegionBindingsTy::data_type* Xptr = B.lookup(R); if (Xptr) { SVal X = *Xptr; UpdateLiveSymbols(X, SymReaper); // Update the set of live symbols. // If X is a region, then add it the RegionRoots. if (loc::MemRegionVal* RegionX = dyn_cast<loc::MemRegionVal>(&X)) RegionRoots.push_back(RegionX->getRegion()); } // Get the subregions of R. These are RegionRoots as well since they // represent values that are also bound to R. const SubRegionsTy* SRptr = SubRegMap.lookup(R); if (!SRptr) continue; SubRegionsTy SR = *SRptr; for (SubRegionsTy::iterator I=SR.begin(), E=SR.end(); I!=E; ++I) RegionRoots.push_back(*I); } // We have now scanned the store, marking reachable regions and symbols // as live. We now remove all the regions that are dead from the store // as well as update DSymbols with the set symbols that are now dead. for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { const MemRegion* R = I.getKey(); // If this region live? Is so, none of its symbols are dead. if (Marked.count(R)) continue; // Remove this dead region from the store. store = Remove(store, Loc::MakeVal(R)); // Mark all non-live symbols that this region references as dead. if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(R)) SymReaper.maybeDead(SymR->getSymbol()); SVal X = I.getData(); SVal::symbol_iterator SI = X.symbol_begin(), SE = X.symbol_end(); for (; SI != SE; ++SI) SymReaper.maybeDead(*SI); } return store; } void RegionStoreManager::print(Store store, std::ostream& Out, const char* nl, const char *sep) { llvm::raw_os_ostream OS(Out); RegionBindingsTy B = GetRegionBindings(store); OS << "Store:" << nl; for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { OS << ' '; I.getKey()->print(OS); OS << " : "; I.getData().print(OS); OS << nl; } } const GRState* RegionStoreManager::BindArray(const GRState* St, const TypedRegion* R, SVal Init) { // FIXME: Verify we should use getLValueType or getRValueType. QualType T = R->getRValueType(getContext()); assert(T->isArrayType()); // When we are binding the whole array, it always has default value 0. GRStateRef state(St, StateMgr); St = state.set<RegionDefaultValue>(R, NonLoc::MakeIntVal(getBasicVals(), 0, false)); ConstantArrayType* CAT = cast<ConstantArrayType>(T.getTypePtr()); llvm::APSInt Size(CAT->getSize(), false); llvm::APSInt i = getBasicVals().getValue(0, Size.getBitWidth(), Size.isUnsigned()); // Check if the init expr is a StringLiteral. if (isa<loc::MemRegionVal>(Init)) { const MemRegion* InitR = cast<loc::MemRegionVal>(Init).getRegion(); const StringLiteral* S = cast<StringRegion>(InitR)->getStringLiteral(); const char* str = S->getStrData(); unsigned len = S->getByteLength(); unsigned j = 0; // Copy bytes from the string literal into the target array. Trailing bytes // in the array that are not covered by the string literal are initialized // to zero. for (; i < Size; ++i, ++j) { if (j >= len) break; SVal Idx = NonLoc::MakeVal(getBasicVals(), i); ElementRegion* ER = MRMgr.getElementRegion(Idx, R); SVal V = NonLoc::MakeVal(getBasicVals(), str[j], sizeof(char)*8, true); St = Bind(St, loc::MemRegionVal(ER), V); } return St; } nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(Init); nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); for (; i < Size; ++i, ++VI) { // The init list might be shorter than the array decl. if (VI == VE) break; SVal Idx = NonLoc::MakeVal(getBasicVals(), i); ElementRegion* ER = MRMgr.getElementRegion(Idx, R); if (CAT->getElementType()->isStructureType()) St = BindStruct(St, ER, *VI); else St = Bind(St, Loc::MakeVal(ER), *VI); } return St; } const GRState* RegionStoreManager::BindStruct(const GRState* St, const TypedRegion* R, SVal V){ // FIXME: Verify that we should use getRValueType or getLValueType. QualType T = R->getRValueType(getContext()); assert(T->isStructureType()); const RecordType* RT = T->getAsRecordType(); RecordDecl* RD = RT->getDecl(); if (!RD->isDefinition()) return St; if (V.isUnknown()) return KillStruct(St, R); nonloc::CompoundVal& CV = cast<nonloc::CompoundVal>(V); nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); RecordDecl::field_iterator FI = RD->field_begin(getContext()), FE = RD->field_end(getContext()); for (; FI != FE; ++FI, ++VI) { // There may be fewer values than fields only when we are initializing a // struct decl. In this case, mark the region as having default value. if (VI == VE) { GRStateRef state(St, StateMgr); const NonLoc& Idx = NonLoc::MakeIntVal(getBasicVals(), 0, false); St = state.set<RegionDefaultValue>(R, Idx); break; } QualType FTy = (*FI)->getType(); FieldRegion* FR = MRMgr.getFieldRegion(*FI, R); if (Loc::IsLocType(FTy) || FTy->isIntegerType()) St = Bind(St, Loc::MakeVal(FR), *VI); else if (FTy->isArrayType()) St = BindArray(St, FR, *VI); else if (FTy->isStructureType()) St = BindStruct(St, FR, *VI); } return St; } const GRState* RegionStoreManager::KillStruct(const GRState* St, const TypedRegion* R){ GRStateRef state(St, StateMgr); // Kill the struct region because it is assigned "unknown". St = state.add<RegionKills>(R); // Set the default value of the struct region to "unknown". St = state.set<RegionDefaultValue>(R, UnknownVal()); Store store = St->getStore(); RegionBindingsTy B = GetRegionBindings(store); // Remove all bindings for the subregions of the struct. for (RegionBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) { const MemRegion* r = I.getKey(); if (const SubRegion* sr = dyn_cast<SubRegion>(r)) if (sr->isSubRegionOf(R)) store = Remove(store, Loc::MakeVal(sr)); // FIXME: Maybe we should also remove the bindings for the "views" of the // subregions. } return StateMgr.MakeStateWithStore(St, store); } const GRState* RegionStoreManager::AddRegionView(const GRState* St, const MemRegion* View, const MemRegion* Base) { GRStateRef state(St, StateMgr); // First, retrieve the region view of the base region. const RegionViews* d = state.get<RegionViewMap>(Base); RegionViews L = d ? *d : RVFactory.GetEmptySet(); // Now add View to the region view. L = RVFactory.Add(L, View); // Create a new state with the new region view. return state.set<RegionViewMap>(Base, L); } const GRState* RegionStoreManager::RemoveRegionView(const GRState* St, const MemRegion* View, const MemRegion* Base) { GRStateRef state(St, StateMgr); // Retrieve the region view of the base region. const RegionViews* d = state.get<RegionViewMap>(Base); // If the base region has no view, return. if (!d) return St; // Remove the view. RegionViews V = *d; V = RVFactory.Remove(V, View); return state.set<RegionViewMap>(Base, V); } <file_sep>/tools/ccc/test/ccc/analyze.c // RUN: xcc --analyze %s -o %t && // RUN: grep '<string>Dereference of null pointer</string>' %t && // RUN: xcc -### --analyze %s -Xanalyzer -check-that-program-halts &> %t && // RUN: grep 'check-that-program-halts' %t void f(int *p) { if (!p) *p = 0; } <file_sep>/test/Parser/cxx-exception-spec.cpp // RUN: clang-cc -fsyntax-only %s struct X { }; struct Y { }; void f() throw() { } void g(int) throw(X) { } void h() throw(X, Y) { } class Class { void foo() throw (X, Y) { } }; <file_sep>/include/clang/Analysis/PathSensitive/ValueManager.h //== ValueManager.h - Aggregate manager of symbols and SVals ----*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines ValueManager, a class that manages symbolic values // and SVals created for use by GRExprEngine and related classes. It // wraps SymbolManager, MemRegionManager, and BasicValueFactory. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_AGGREGATE_VALUE_MANAGER_H #define LLVM_CLANG_ANALYSIS_AGGREGATE_VALUE_MANAGER_H #include "clang/Analysis/PathSensitive/MemRegion.h" #include "clang/Analysis/PathSensitive/SVals.h" #include "clang/Analysis/PathSensitive/BasicValueFactory.h" #include "clang/Analysis/PathSensitive/SymbolManager.h" namespace llvm { class BumpPtrAllocator; } namespace clang { class ValueManager { ASTContext &Context; BasicValueFactory BasicVals; /// SymMgr - Object that manages the symbol information. SymbolManager SymMgr; MemRegionManager MemMgr; public: ValueManager(llvm::BumpPtrAllocator &alloc, ASTContext &context) : Context(context), BasicVals(Context, alloc), SymMgr(Context, BasicVals, alloc), MemMgr(alloc) {} // Accessors to submanagers. ASTContext &getContext() { return Context; } const ASTContext &getContext() const { return Context; } BasicValueFactory &getBasicValueFactory() { return BasicVals; } const BasicValueFactory &getBasicValueFactory() const { return BasicVals; } SymbolManager &getSymbolManager() { return SymMgr; } const SymbolManager &getSymbolManager() const { return SymMgr; } MemRegionManager &getRegionManager() { return MemMgr; } const MemRegionManager &getRegionManager() const { return MemMgr; } // Forwarding methods to SymbolManager. const SymbolConjured* getConjuredSymbol(const Stmt* E, QualType T, unsigned VisitCount, const void* SymbolTag = 0) { return SymMgr.getConjuredSymbol(E, T, VisitCount, SymbolTag); } const SymbolConjured* getConjuredSymbol(const Expr* E, unsigned VisitCount, const void* SymbolTag = 0) { return SymMgr.getConjuredSymbol(E, VisitCount, SymbolTag); } // Aggregation methods that use multiple submanagers. Loc makeRegionVal(SymbolRef Sym) { return Loc::MakeVal(MemMgr.getSymbolicRegion(Sym)); } /// makeZeroVal - Construct an SVal representing '0' for the specified type. SVal makeZeroVal(QualType T); /// GetRValueSymbolVal - make a unique symbol for value of R. SVal getRValueSymbolVal(const MemRegion* R); SVal getConjuredSymbolVal(const Expr *E, unsigned Count); SVal getConjuredSymbolVal(const Expr* E, QualType T, unsigned Count); SVal getFunctionPointer(const FunctionDecl* FD); NonLoc makeNonLoc(SymbolRef sym); NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType T); NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType T); NonLoc makeTruthVal(bool b, QualType T); }; } // end clang namespace #endif <file_sep>/test/Parser/parmvardecl_conversion.c // RUN: clang-cc -fsyntax-only -verify %s void f (int p[]) { p++; } <file_sep>/test/CodeGen/x86_32-arguments.c // RUN: clang-cc -triple i386-apple-darwin9 -emit-llvm -o %t %s && // RUN: grep 'define signext i8 @f0()' %t && // RUN: grep 'define signext i16 @f1()' %t && // RUN: grep 'define i32 @f2()' %t && // RUN: grep 'define float @f3()' %t && // RUN: grep 'define double @f4()' %t && // RUN: grep 'define x86_fp80 @f5()' %t && // RUN: grep 'define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8\* %a4)' %t && // RUN: grep 'define void @f7(i32 %a0)' %t && // RUN: grep 'define i64 @f8_1()' %t && // RUN: grep 'define void @f8_2(i32 %a0.0, i32 %a0.1)' %t && char f0(void) { } short f1(void) { } int f2(void) { } float f3(void) { } double f4(void) { } long double f5(void) { } void f6(char a0, short a1, int a2, long long a3, void *a4) { } typedef enum { A, B, C } E; void f7(E a0) { } struct s8 { int a; int b; }; struct s8 f8_1(void) { } void f8_2(struct s8 a0) { } // This should be passed just as s8. // FIXME: This is wrong, but we want the coverage of the other // tests. This should be the same as @f8_1. // RUN: grep 'define void @f9_1(%.truct.s9\* noalias sret %agg.result)' %t && // FIXME: This is wrong, but we want the coverage of the other // tests. This should be the same as @f8_2. // RUN: grep 'define void @f9_2(%.truct.s9\* byval %a0)' %t && struct s9 { int a : 17; int b; }; struct s9 f9_1(void) { } void f9_2(struct s9 a0) { } // Return of small structures and unions // RUN: grep 'float @f10()' %t && struct s10 { union { }; float f; } f10(void) {} // Small vectors and 1 x {i64,double} are returned in registers // RUN: grep 'i32 @f11()' %t && // RUN: grep -F 'void @f12(<2 x i32>* noalias sret %agg.result)' %t && // RUN: grep 'i64 @f13()' %t && // RUN: grep 'i64 @f14()' %t && // RUN: grep '<2 x i64> @f15()' %t && // RUN: grep '<2 x i64> @f16()' %t && typedef short T11 __attribute__ ((vector_size (4))); T11 f11(void) {} typedef int T12 __attribute__ ((vector_size (8))); T12 f12(void) {} typedef long long T13 __attribute__ ((vector_size (8))); T13 f13(void) {} typedef double T14 __attribute__ ((vector_size (8))); T14 f14(void) {} typedef long long T15 __attribute__ ((vector_size (16))); T15 f15(void) {} typedef double T16 __attribute__ ((vector_size (16))); T16 f16(void) {} // And when the single element in a struct (but not for 64 and // 128-bits). // RUN: grep 'i32 @f17()' %t && // RUN: grep -F 'void @f18(%3* noalias sret %agg.result)' %t && // RUN: grep -F 'void @f19(%4* noalias sret %agg.result)' %t && // RUN: grep -F 'void @f20(%5* noalias sret %agg.result)' %t && // RUN: grep -F 'void @f21(%6* noalias sret %agg.result)' %t && // RUN: grep -F 'void @f22(%7* noalias sret %agg.result)' %t && struct { T11 a; } f17(void) {} struct { T12 a; } f18(void) {} struct { T13 a; } f19(void) {} struct { T14 a; } f20(void) {} struct { T15 a; } f21(void) {} struct { T16 a; } f22(void) {} // Single element structures are handled specially // RUN: grep -F 'float @f23()' %t && // RUN: grep -F 'float @f24()' %t && // RUN: grep -F 'float @f25()' %t && struct { float a; } f23(void) {} struct { float a[1]; } f24(void) {} struct { struct {} a; struct { float a[1]; } b; } f25(void) {} // Small structures are handled recursively // RUN: grep -F 'i32 @f26()' %t && // RUN: grep 'void @f27(%.truct.s27\* noalias sret %agg.result)' %t && struct s26 { struct { char a, b; } a; struct { char a, b } b; } f26(void) {} struct s27 { struct { char a, b, c; } a; struct { char a } b; } f27(void) {} // RUN: true <file_sep>/test/CodeGen/bitfield.c // RUN: clang-cc -triple i386-unknown-unknown %s -emit-llvm-bc -o - | opt -std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32" %t | count 4 && // RUN: grep "ret i32 1" %t | count 4 static int f0(int n) { struct s0 { int a : 30; int b : 2; long long c : 31; } x = { 0xdeadbeef, 0xdeadbeef, 0xdeadbeef }; x.a += n; x.b += n; x.c += n; return x.a + x.b + x.c; } int g0(void) { return f0(-1) + 44335655; } static int f1(void) { struct s1 { int a:13; char b; unsigned short c:7; } x; x.a = -40; x.b = 10; x.c = 15; return x.a + x.b + x.c; } int g1(void) { return f1() + 16; } static int f2(void) { struct s2 { short a[3]; int b : 15; } x; x.a[0] = x.a[1] = x.a[2] = -40; x.b = 10; return x.b; } int g2(void) { return f2() - 9; } static int f3(int n) { struct s3 { unsigned a:16; unsigned b:28 __attribute__ ((packed)); } x = { 0xdeadbeef, 0xdeadbeef }; struct s4 { signed a:16; signed b:28 __attribute__ ((packed)); } y; y.a = -0x56789abcL; y.b = -0x56789abcL; return ((y.a += x.a += n) + (y.b += x.b += n)); } int g3(void) { return f3(20) + 130725747; } <file_sep>/include/clang/AST/Builtins.def //===--- Builtins.def - Builtin function info database ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the standard builtin function database. Users of this file // must define the BUILTIN macro to make use of this information. // //===----------------------------------------------------------------------===// // FIXME: this needs to be the full list supported by GCC. Right now, I'm just // adding stuff on demand. // // FIXME: This should really be a .td file, but that requires modifying tblgen. // Perhaps tblgen should have plugins. // The first value provided to the macro specifies the function name of the // builtin, and results in a clang::builtin::BIXX enum value for XX. // The second value provided to the macro specifies the type of the function // (result value, then each argument) as follows: // v -> void // b -> boolean // c -> char // s -> short // i -> int // f -> float // d -> double // z -> size_t // F -> constant CFString // a -> __builtin_va_list // A -> "reference" to __builtin_va_list // V -> Vector, following num elements and a base type. // P -> FILE // . -> "...". This may only occur at the end of the function list. // // Types maybe prefixed with the following modifiers: // L -> long (e.g. Li for 'long int') // LL -> long long // S -> signed // U -> unsigned // // Types may be postfixed with the following modifiers: // * -> pointer // & -> reference // C -> const // The third value provided to the macro specifies information about attributes // of the function. These must be kept in sync with the predicates in the // Builtin::Context class. Currently we have: // n -> nothrow // c -> const // F -> this is a libc/libm function with a '__builtin_' prefix added. // f -> this is a libc/libm function without the '__builtin_' prefix. It can // be followed by ':headername:' to state which header this function // comes from. // p:N: -> this is a printf-like function whose Nth argument is the format // string. // P:N: -> similar to the p:N: attribute, but the function is like vprintf // in that it accepts its arguments as a va_list rather than // through an ellipsis // e -> const, but only when -fmath-errno=0 // FIXME: gcc has nonnull #if defined(BUILTIN) && !defined(LIBBUILTIN) # define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) BUILTIN(ID, TYPE, ATTRS) #endif // Standard libc/libm functions: BUILTIN(__builtin_huge_val, "d", "nc") BUILTIN(__builtin_huge_valf, "f", "nc") BUILTIN(__builtin_huge_vall, "Ld", "nc") BUILTIN(__builtin_inf , "d" , "nc") BUILTIN(__builtin_inff , "f" , "nc") BUILTIN(__builtin_infl , "Ld" , "nc") BUILTIN(__builtin_nan, "dcC*" , "ncF") BUILTIN(__builtin_nanf, "fcC*" , "ncF") BUILTIN(__builtin_nanl, "LdcC*", "ncF") BUILTIN(__builtin_nans, "dcC*" , "ncF") BUILTIN(__builtin_nansf, "fcC*" , "ncF") BUILTIN(__builtin_nansl, "LdcC*", "ncF") BUILTIN(__builtin_abs , "ii" , "ncF") BUILTIN(__builtin_fabs , "dd" , "ncF") BUILTIN(__builtin_fabsf, "ff" , "ncF") BUILTIN(__builtin_fabsl, "LdLd", "ncF") BUILTIN(__builtin_copysign, "ddd", "ncF") BUILTIN(__builtin_copysignf, "fff", "ncF") BUILTIN(__builtin_copysignl, "LdLdLd", "ncF") BUILTIN(__builtin_powi , "ddi" , "nc") BUILTIN(__builtin_powif, "ffi" , "nc") BUILTIN(__builtin_powil, "LdLdi", "nc") // FP Comparisons. BUILTIN(__builtin_isgreater , "i.", "nc") BUILTIN(__builtin_isgreaterequal, "i.", "nc") BUILTIN(__builtin_isless , "i.", "nc") BUILTIN(__builtin_islessequal , "i.", "nc") BUILTIN(__builtin_islessgreater , "i.", "nc") BUILTIN(__builtin_isunordered , "i.", "nc") // Builtins for arithmetic. BUILTIN(__builtin_clz , "iUi" , "nc") BUILTIN(__builtin_clzl , "iULi" , "nc") BUILTIN(__builtin_clzll, "iULLi", "nc") // TODO: int clzimax(uintmax_t) BUILTIN(__builtin_ctz , "iUi" , "nc") BUILTIN(__builtin_ctzl , "iULi" , "nc") BUILTIN(__builtin_ctzll, "iULLi", "nc") // TODO: int ctzimax(uintmax_t) BUILTIN(__builtin_ffs , "iUi" , "nc") BUILTIN(__builtin_ffsl , "iULi" , "nc") BUILTIN(__builtin_ffsll, "iULLi", "nc") BUILTIN(__builtin_parity , "iUi" , "nc") BUILTIN(__builtin_parityl , "iULi" , "nc") BUILTIN(__builtin_parityll, "iULLi", "nc") BUILTIN(__builtin_popcount , "iUi" , "nc") BUILTIN(__builtin_popcountl , "iULi" , "nc") BUILTIN(__builtin_popcountll, "iULLi", "nc") // FIXME: These type signatures are not correct for targets with int != 32-bits // or with ULL != 64-bits. BUILTIN(__builtin_bswap32, "UiUi", "nc") BUILTIN(__builtin_bswap64, "ULLiULLi", "nc") // Random GCC builtins BUILTIN(__builtin_constant_p, "Us.", "nc") BUILTIN(__builtin_classify_type, "i.", "nc") BUILTIN(__builtin___CFStringMakeConstantString, "FC*cC*", "nc") BUILTIN(__builtin_va_start, "vA.", "n") BUILTIN(__builtin_va_end, "vA", "n") BUILTIN(__builtin_va_copy, "vAA", "n") BUILTIN(__builtin_stdarg_start, "vA.", "n") BUILTIN(__builtin_bcmp, "iv*v*z", "n") BUILTIN(__builtin_bcopy, "vv*v*z", "n") BUILTIN(__builtin_bzero, "vv*z", "n") BUILTIN(__builtin_memcmp, "ivC*vC*z", "nF") BUILTIN(__builtin_memcpy, "v*v*vC*z", "nF") BUILTIN(__builtin_memmove, "v*v*vC*z", "nF") BUILTIN(__builtin_mempcpy, "v*v*vC*z", "nF") BUILTIN(__builtin_memset, "v*v*iz", "nF") BUILTIN(__builtin_stpcpy, "c*c*cC*", "nF") BUILTIN(__builtin_stpncpy, "c*c*cC*z", "nF") BUILTIN(__builtin_strcasecmp, "icC*cC*", "nF") BUILTIN(__builtin_strcat, "c*c*cC*", "nF") BUILTIN(__builtin_strchr, "c*cC*i", "nF") BUILTIN(__builtin_strcmp, "icC*cC*", "nF") BUILTIN(__builtin_strcpy, "c*c*cC*", "nF") BUILTIN(__builtin_strcspn, "zcC*cC*", "nF") BUILTIN(__builtin_strdup, "c*cC*", "nF") BUILTIN(__builtin_strlen, "zcC*", "nF") BUILTIN(__builtin_strncasecmp, "icC*cC*z", "nF") BUILTIN(__builtin_strncat, "c*c*cC*z", "nF") BUILTIN(__builtin_strncmp, "icC*cC*z", "nF") BUILTIN(__builtin_strncpy, "c*c*cC*z", "nF") BUILTIN(__builtin_strndup, "c*cC*z", "nF") BUILTIN(__builtin_strpbrk, "c*cC*cC*", "nF") BUILTIN(__builtin_strrchr, "c*cC*i", "nF") BUILTIN(__builtin_strspn, "zcC*cC*", "nF") BUILTIN(__builtin_strstr, "c*cC*cC*", "nF") BUILTIN(__builtin_return_address, "v*Ui", "n") BUILTIN(__builtin_frame_address, "v*Ui", "n") BUILTIN(__builtin_flt_rounds, "i", "nc") // GCC Object size checking builtins BUILTIN(__builtin_object_size, "zv*i", "n") BUILTIN(__builtin___memcpy_chk, "v*v*vC*zz", "nF") BUILTIN(__builtin___memmove_chk, "v*v*vC*zz", "nF") BUILTIN(__builtin___mempcpy_chk, "v*v*vC*zz", "nF") BUILTIN(__builtin___memset_chk, "v*v*izz", "nF") BUILTIN(__builtin___stpcpy_chk, "c*c*cC*z", "nF") BUILTIN(__builtin___strcat_chk, "c*c*cC*z", "nF") BUILTIN(__builtin___strcpy_chk, "c*c*cC*z", "nF") BUILTIN(__builtin___strncat_chk, "c*c*cC*zz", "nF") BUILTIN(__builtin___strncpy_chk, "c*c*cC*zz", "nF") BUILTIN(__builtin___snprintf_chk, "ic*zizcC*.", "Fp:4:") BUILTIN(__builtin___sprintf_chk, "ic*izcC*.", "Fp:3:") BUILTIN(__builtin___vsnprintf_chk, "ic*zizcC*a", "FP:4:") BUILTIN(__builtin___vsprintf_chk, "ic*izcC*a", "FP:3:") BUILTIN(__builtin___fprintf_chk, "iP*icC*.", "Fp:2:") BUILTIN(__builtin___printf_chk, "iicC*.", "Fp:1:") BUILTIN(__builtin___vfprintf_chk, "iP*icC*a", "FP:2:") BUILTIN(__builtin___vprintf_chk, "iicC*a", "FP:1:") BUILTIN(__builtin_expect, "iii" , "nc") BUILTIN(__builtin_prefetch, "vCv*.", "nc") BUILTIN(__builtin_trap, "v", "n") BUILTIN(__builtin_shufflevector, "v." , "nc") BUILTIN(__builtin_alloca, "v*z" , "n") // Atomic operators builtin. // FIXME: These should be overloaded for i8, i16, i32, and i64. BUILTIN(__sync_fetch_and_add,"ii*i", "n") BUILTIN(__sync_fetch_and_sub,"ii*i", "n") BUILTIN(__sync_fetch_and_min,"ii*i", "n") BUILTIN(__sync_fetch_and_max,"ii*i", "n") BUILTIN(__sync_fetch_and_umin,"UiUi*Ui", "n") BUILTIN(__sync_fetch_and_umax,"UiUi*Ui", "n") BUILTIN(__sync_fetch_and_and,"ii*i", "n") BUILTIN(__sync_fetch_and_or,"ii*i", "n") BUILTIN(__sync_fetch_and_xor,"ii*i", "n") BUILTIN(__sync_add_and_fetch,"ii*i", "n") BUILTIN(__sync_sub_and_fetch,"ii*i", "n") BUILTIN(__sync_min_and_fetch,"ii*i", "n") BUILTIN(__sync_max_and_fetch,"ii*i", "n") BUILTIN(__sync_umin_and_fetch,"UiUi*Ui", "n") BUILTIN(__sync_umax_and_fetch,"UiUi*Ui", "n") BUILTIN(__sync_and_and_fetch,"ii*i", "n") BUILTIN(__sync_or_and_fetch,"ii*i", "n") BUILTIN(__sync_xor_and_fetch,"ii*i", "n") BUILTIN(__sync_lock_test_and_set,"ii*i", "n") BUILTIN(__sync_bool_compare_and_swap,"ii*ii", "n") BUILTIN(__sync_val_compare_and_swap,"ii*ii", "n") // LLVM instruction builtin BUILTIN(__builtin_llvm_memory_barrier,"vbbbbb", "n") // Builtin library functions LIBBUILTIN(alloca, "v*z", "f", "stdlib.h") LIBBUILTIN(calloc, "v*zz", "f", "stdlib.h") LIBBUILTIN(malloc, "v*z", "f", "stdlib.h") LIBBUILTIN(realloc, "v*v*z", "f", "stdlib.h") LIBBUILTIN(memcpy, "v*v*vC*z", "f", "string.h") LIBBUILTIN(memmove, "v*v*vC*z", "f", "string.h") LIBBUILTIN(memset, "v*v*iz", "f", "string.h") LIBBUILTIN(strcat, "c*c*cC*", "f", "string.h") LIBBUILTIN(strchr, "c*cC*i", "f", "string.h") LIBBUILTIN(strcpy, "c*c*cC*", "f", "string.h") LIBBUILTIN(strcspn, "zcC*cC*", "f", "string.h") LIBBUILTIN(strlen, "zcC*", "f", "string.h") LIBBUILTIN(strncat, "c*c*cC*z", "f", "string.h") LIBBUILTIN(strncpy, "c*c*cC*z", "f", "string.h") LIBBUILTIN(strpbrk, "c*cC*cC*", "f", "string.h") LIBBUILTIN(strrchr, "c*cC*i", "f", "string.h") LIBBUILTIN(strspn, "zcC*cC*", "f", "string.h") LIBBUILTIN(strstr, "c*cC*cC*", "f", "string.h") LIBBUILTIN(printf, "icC*.", "fp:0:", "stdio.h") LIBBUILTIN(fprintf, "iP*cC*.", "fp:1:", "stdio.h") LIBBUILTIN(snprintf, "ic*zcC*.", "fp:2:", "stdio.h") LIBBUILTIN(sprintf, "ic*cC*.", "fp:1:", "stdio.h") LIBBUILTIN(vprintf, "icC*a", "fP:0:", "stdio.h") LIBBUILTIN(vfprintf, "iP*cC*a", "fP:1:", "stdio.h") LIBBUILTIN(vsnprintf, "ic*zcC*a", "fP:2:", "stdio.h") LIBBUILTIN(vsprintf, "ic*cC*a", "fP:1:", "stdio.h") // FIXME: asprintf and vasprintf aren't C99 functions. Should they be // target-specific builtins, perhaps? // Builtin math library functions LIBBUILTIN(pow, "ddd", "fe", "math.h") LIBBUILTIN(powl, "LdLdLd", "fe", "math.h") LIBBUILTIN(powf, "fff", "fe", "math.h") LIBBUILTIN(sqrt, "dd", "fe", "math.h") LIBBUILTIN(sqrtl, "LdLd", "fe", "math.h") LIBBUILTIN(sqrtf, "ff", "fe", "math.h") #undef BUILTIN #undef LIBBUILTIN <file_sep>/test/SemaCXX/blocks.cpp // RUN: clang-cc -fsyntax-only -verify %s -fblocks void tovoid(void*); void tovoid_test(int (^f)(int, int)) { tovoid(f); } <file_sep>/test/Analysis/rdar-6582778-basic-store.c // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -verify %s typedef const void * CFTypeRef; typedef double CFTimeInterval; typedef CFTimeInterval CFAbsoluteTime; typedef const struct __CFAllocator * CFAllocatorRef; typedef const struct __CFDate * CFDateRef; extern CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at); CFAbsoluteTime CFAbsoluteTimeGetCurrent(void); void f(void) { CFAbsoluteTime t = CFAbsoluteTimeGetCurrent(); CFTypeRef vals[] = { CFDateCreate(0, t) }; // no-warning } CFTypeRef global; void g(void) { CFAbsoluteTime t = CFAbsoluteTimeGetCurrent(); global = CFDateCreate(0, t); // no-warning } <file_sep>/test/Sema/types.c // RUN: clang-cc %s -pedantic -verify // rdar://6097662 typedef int (*T)[2]; restrict T x; typedef int *S[2]; restrict S y; // expected-error {{restrict requires a pointer or reference ('S' (aka 'int *[2]') is invalid)}} <file_sep>/test/Analysis/uninit-vals-ps-region.c // RUN: clang-cc -analyze -checker-simple -analyzer-store=region -verify %s struct s { int data; }; struct s global; void g(int); void f4() { int a; if (global.data == 0) a = 3; if (global.data == 0) // When the true branch is feasible 'a = 3'. g(a); // no-warning } <file_sep>/lib/Parse/MinimalAction.cpp //===--- MinimalAction.cpp - Implement the MinimalAction class ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the MinimalAction interface. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "clang/Parse/DeclSpec.h" #include "clang/Parse/Scope.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/RecyclingAllocator.h" #include "llvm/Support/raw_ostream.h" using namespace clang; /// Out-of-line virtual destructor to provide home for ActionBase class. ActionBase::~ActionBase() {} /// Out-of-line virtual destructor to provide home for Action class. Action::~Action() {} // Defined out-of-line here because of dependecy on AttributeList Action::DeclPtrTy Action::ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, const CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, AttributeList *AttrList) { // FIXME: Parser seems to assume that Action::ActOn* takes ownership over // passed AttributeList, however other actions don't free it, is it // temporary state or bug? delete AttrList; return DeclPtrTy(); } void PrettyStackTraceActionsDecl::print(llvm::raw_ostream &OS) const { if (Loc.isValid()) { Loc.print(OS, SM); OS << ": "; } OS << Message; std::string Name = Actions.getDeclName(TheDecl); if (!Name.empty()) OS << " '" << Name << '\''; OS << '\n'; } /// TypeNameInfo - A link exists here for each scope that an identifier is /// defined. namespace { struct TypeNameInfo { TypeNameInfo *Prev; bool isTypeName; TypeNameInfo(bool istypename, TypeNameInfo *prev) { isTypeName = istypename; Prev = prev; } }; struct TypeNameInfoTable { llvm::RecyclingAllocator<llvm::BumpPtrAllocator, TypeNameInfo> Allocator; void AddEntry(bool isTypename, IdentifierInfo *II) { TypeNameInfo *TI = Allocator.Allocate<TypeNameInfo>(); new (TI) TypeNameInfo(isTypename, II->getFETokenInfo<TypeNameInfo>()); II->setFETokenInfo(TI); } void DeleteEntry(TypeNameInfo *Entry) { Entry->~TypeNameInfo(); Allocator.Deallocate(Entry); } }; } static TypeNameInfoTable *getTable(void *TP) { return static_cast<TypeNameInfoTable*>(TP); } MinimalAction::MinimalAction(Preprocessor &pp) : Idents(pp.getIdentifierTable()), PP(pp) { TypeNameInfoTablePtr = new TypeNameInfoTable(); } MinimalAction::~MinimalAction() { delete getTable(TypeNameInfoTablePtr); } void MinimalAction::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { TUScope = S; if (!PP.getLangOptions().ObjC1) return; TypeNameInfoTable &TNIT = *getTable(TypeNameInfoTablePtr); // Recognize the ObjC built-in type identifiers as types. TNIT.AddEntry(true, &Idents.get("id")); TNIT.AddEntry(true, &Idents.get("SEL")); TNIT.AddEntry(true, &Idents.get("Class")); TNIT.AddEntry(true, &Idents.get("Protocol")); } /// isTypeName - This looks at the IdentifierInfo::FETokenInfo field to /// determine whether the name is a type name (objc class name or typedef) or /// not in this scope. /// /// FIXME: Use the passed CXXScopeSpec for accurate C++ type checking. Action::TypeTy * MinimalAction::getTypeName(IdentifierInfo &II, SourceLocation Loc, Scope *S, const CXXScopeSpec *SS) { if (TypeNameInfo *TI = II.getFETokenInfo<TypeNameInfo>()) if (TI->isTypeName) return TI; return 0; } /// isCurrentClassName - Always returns false, because MinimalAction /// does not support C++ classes with constructors. bool MinimalAction::isCurrentClassName(const IdentifierInfo &, Scope *, const CXXScopeSpec *) { return false; } TemplateNameKind MinimalAction::isTemplateName(const IdentifierInfo &II, Scope *S, TemplateTy &TemplateDecl, const CXXScopeSpec *SS) { return TNK_Non_template; } /// ActOnDeclarator - If this is a typedef declarator, we modify the /// IdentifierInfo::FETokenInfo field to keep track of this fact, until S is /// popped. Action::DeclPtrTy MinimalAction::ActOnDeclarator(Scope *S, Declarator &D) { IdentifierInfo *II = D.getIdentifier(); // If there is no identifier associated with this declarator, bail out. if (II == 0) return DeclPtrTy(); TypeNameInfo *weCurrentlyHaveTypeInfo = II->getFETokenInfo<TypeNameInfo>(); bool isTypeName = D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef; // this check avoids creating TypeNameInfo objects for the common case. // It does need to handle the uncommon case of shadowing a typedef name with a // non-typedef name. e.g. { typedef int a; a xx; { int a; } } if (weCurrentlyHaveTypeInfo || isTypeName) { // Allocate and add the 'TypeNameInfo' "decl". getTable(TypeNameInfoTablePtr)->AddEntry(isTypeName, II); // Remember that this needs to be removed when the scope is popped. S->AddDecl(DeclPtrTy::make(II)); } return DeclPtrTy(); } Action::DeclPtrTy MinimalAction::ActOnStartClassInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtocols, SourceLocation EndProtoLoc, AttributeList *AttrList) { // Allocate and add the 'TypeNameInfo' "decl". getTable(TypeNameInfoTablePtr)->AddEntry(true, ClassName); return DeclPtrTy(); } /// ActOnForwardClassDeclaration - /// Scope will always be top level file scope. Action::DeclPtrTy MinimalAction::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, IdentifierInfo **IdentList, unsigned NumElts) { for (unsigned i = 0; i != NumElts; ++i) { // Allocate and add the 'TypeNameInfo' "decl". getTable(TypeNameInfoTablePtr)->AddEntry(true, IdentList[i]); // Remember that this needs to be removed when the scope is popped. TUScope->AddDecl(DeclPtrTy::make(IdentList[i])); } return DeclPtrTy(); } /// ActOnPopScope - When a scope is popped, if any typedefs are now /// out-of-scope, they are removed from the IdentifierInfo::FETokenInfo field. void MinimalAction::ActOnPopScope(SourceLocation Loc, Scope *S) { TypeNameInfoTable &Table = *getTable(TypeNameInfoTablePtr); for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); I != E; ++I) { IdentifierInfo &II = *(*I).getAs<IdentifierInfo>(); TypeNameInfo *TI = II.getFETokenInfo<TypeNameInfo>(); assert(TI && "This decl didn't get pushed??"); if (TI) { TypeNameInfo *Next = TI->Prev; Table.DeleteEntry(TI); II.setFETokenInfo(Next); } } } <file_sep>/test/CodeGen/bool-init.c // RUN: clang-cc -emit-llvm < %s | grep i1 | count 1 // Check that the type of this global isn't i1 _Bool test = &test; <file_sep>/test/Parser/2008-10-31-parse-noop-failure.c // RUN: clang-cc -verify -parse-noop %t void add_attribute(id) int id; {} <file_sep>/lib/CodeGen/CodeGenFunction.cpp //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This coordinates the per-function state used while generating code. // //===----------------------------------------------------------------------===// #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "CGDebugInfo.h" #include "clang/Basic/TargetInfo.h" #include "clang/AST/APValue.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "llvm/Support/CFG.h" #include "llvm/Target/TargetData.h" using namespace clang; using namespace CodeGen; CodeGenFunction::CodeGenFunction(CodeGenModule &cgm) : BlockFunction(cgm, *this, Builder), CGM(cgm), Target(CGM.getContext().Target), DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0), CXXThisDecl(0) { LLVMIntTy = ConvertType(getContext().IntTy); LLVMPointerWidth = Target.getPointerWidth(0); } ASTContext &CodeGenFunction::getContext() const { return CGM.getContext(); } llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { llvm::BasicBlock *&BB = LabelMap[S]; if (BB) return BB; // Create, but don't insert, the new block. return BB = createBasicBlock(S->getName()); } llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) { llvm::Value *Res = LocalDeclMap[VD]; assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); return Res; } llvm::Constant * CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); } const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { return CGM.getTypes().ConvertTypeForMem(T); } const llvm::Type *CodeGenFunction::ConvertType(QualType T) { return CGM.getTypes().ConvertType(T); } bool CodeGenFunction::hasAggregateLLVMType(QualType T) { // FIXME: Use positive checks instead of negative ones to be more // robust in the face of extension. return !T->hasPointerRepresentation() &&!T->isRealType() && !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() && !T->isBlockPointerType(); } void CodeGenFunction::EmitReturnBlock() { // For cleanliness, we try to avoid emitting the return block for // simple cases. llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); if (CurBB) { assert(!CurBB->getTerminator() && "Unexpected terminated block."); // We have a valid insert point, reuse it if there are no explicit // jumps to the return block. if (ReturnBlock->use_empty()) delete ReturnBlock; else EmitBlock(ReturnBlock); return; } // Otherwise, if the return block is the target of a single direct // branch then we can just put the code in that block instead. This // cleans up functions which started with a unified return block. if (ReturnBlock->hasOneUse()) { llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin()); if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) { // Reset insertion point and delete the branch. Builder.SetInsertPoint(BI->getParent()); BI->eraseFromParent(); delete ReturnBlock; return; } } // FIXME: We are at an unreachable point, there is no reason to emit // the block unless it has uses. However, we still need a place to // put the debug region.end for now. EmitBlock(ReturnBlock); } void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { // Finish emission of indirect switches. EmitIndirectSwitches(); assert(BreakContinueStack.empty() && "mismatched push/pop in break/continue stack!"); assert(BlockScopes.empty() && "did not remove all blocks from block scope map!"); assert(CleanupEntries.empty() && "mismatched push/pop in cleanup stack!"); // Emit function epilog (to return). EmitReturnBlock(); // Emit debug descriptor for function end. if (CGDebugInfo *DI = getDebugInfo()) { DI->setLocation(EndLoc); DI->EmitRegionEnd(CurFn, Builder); } EmitFunctionEpilog(*CurFnInfo, ReturnValue); // Remove the AllocaInsertPt instruction, which is just a convenience for us. llvm::Instruction *Ptr = AllocaInsertPt; AllocaInsertPt = 0; Ptr->eraseFromParent(); } void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy, llvm::Function *Fn, const FunctionArgList &Args, SourceLocation StartLoc) { DidCallStackSave = false; CurFuncDecl = D; FnRetTy = RetTy; CurFn = Fn; assert(CurFn->isDeclaration() && "Function already has body?"); llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); // Create a marker to make it easy to insert allocas into the entryblock // later. Don't create this with the builder, because we don't want it // folded. llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty); AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "", EntryBB); if (Builder.isNamePreserving()) AllocaInsertPt->setName("allocapt"); ReturnBlock = createBasicBlock("return"); ReturnValue = 0; if (!RetTy->isVoidType()) ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); Builder.SetInsertPoint(EntryBB); // Emit subprogram debug descriptor. // FIXME: The cast here is a huge hack. if (CGDebugInfo *DI = getDebugInfo()) { DI->setLocation(StartLoc); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder); } else { // Just use LLVM function name. DI->EmitFunctionStart(Fn->getName().c_str(), RetTy, CurFn, Builder); } } // FIXME: Leaked. CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args); EmitFunctionProlog(*CurFnInfo, CurFn, Args); // If any of the arguments have a variably modified type, make sure to // emit the type size. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); i != e; ++i) { QualType Ty = i->second; if (Ty->isVariablyModifiedType()) EmitVLASize(Ty); } } void CodeGenFunction::GenerateCode(const FunctionDecl *FD, llvm::Function *Fn) { // Check if we should generate debug info for this function. if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>()) DebugInfo = CGM.getDebugInfo(); FunctionArgList Args; if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { if (MD->isInstance()) { // Create the implicit 'this' decl. // FIXME: I'm not entirely sure I like using a fake decl just for code // generation. Maybe we can come up with a better way? CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), &getContext().Idents.get("this"), MD->getThisType(getContext())); Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); } } if (FD->getNumParams()) { const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType(); assert(FProto && "Function def must have prototype!"); for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) Args.push_back(std::make_pair(FD->getParamDecl(i), FProto->getArgType(i))); } const CompoundStmt *S = FD->getBody(); StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc()); EmitStmt(S); FinishFunction(S->getRBracLoc()); // Destroy the 'this' declaration. if (CXXThisDecl) CXXThisDecl->Destroy(getContext()); } /// ContainsLabel - Return true if the statement contains a label in it. If /// this statement is not executed normally, it not containing a label means /// that we can just remove the code. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { // Null statement, not a label! if (S == 0) return false; // If this is a label, we have to emit the code, consider something like: // if (0) { ... foo: bar(); } goto foo; if (isa<LabelStmt>(S)) return true; // If this is a case/default statement, and we haven't seen a switch, we have // to emit the code. if (isa<SwitchCase>(S) && !IgnoreCaseStmts) return true; // If this is a switch statement, we want to ignore cases below it. if (isa<SwitchStmt>(S)) IgnoreCaseStmts = true; // Scan subexpressions for verboten labels. for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); I != E; ++I) if (ContainsLabel(*I, IgnoreCaseStmts)) return true; return false; } /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to /// a constant, or if it does but contains a label, return 0. If it constant /// folds to 'true' and does not contain a label, return 1, if it constant folds /// to 'false' and does not contain a label, return -1. int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { // FIXME: Rename and handle conversion of other evaluatable things // to bool. Expr::EvalResult Result; if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || Result.HasSideEffects) return 0; // Not foldable, not integer or not fully evaluatable. if (CodeGenFunction::ContainsLabel(Cond)) return 0; // Contains a label. return Result.Val.getInt().getBoolValue() ? 1 : -1; } /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if /// statement) to the specified blocks. Based on the condition, this might try /// to simplify the codegen of the conditional based on the branch. /// void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock) { if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { // Handle X && Y in a condition. if (CondBOp->getOpcode() == BinaryOperator::LAnd) { // If we have "1 && X", simplify the code. "0 && X" would have constant // folded if the case was simple enough. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { // br(1 && X) -> br(X). return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); } // If we have "X && 1", simplify the code to use an uncond branch. // "X && 0" would have been constant folded to 0. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { // br(X && 1) -> br(X). return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); } // Emit the LHS as a conditional. If the LHS conditional is false, we // want to jump to the FalseBlock. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); EmitBlock(LHSTrue); EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); return; } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { // If we have "0 || X", simplify the code. "1 || X" would have constant // folded if the case was simple enough. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { // br(0 || X) -> br(X). return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); } // If we have "X || 0", simplify the code to use an uncond branch. // "X || 1" would have been constant folded to 1. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { // br(X || 0) -> br(X). return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); } // Emit the LHS as a conditional. If the LHS conditional is true, we // want to jump to the TrueBlock. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); EmitBlock(LHSFalse); EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); return; } } if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { // br(!x, t, f) -> br(x, f, t) if (CondUOp->getOpcode() == UnaryOperator::LNot) return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); } if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { // Handle ?: operator. // Just ignore GNU ?: extension. if (CondOp->getLHS()) { // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); EmitBlock(LHSBlock); EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); EmitBlock(RHSBlock); EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); return; } } // Emit the code with the fully general case. llvm::Value *CondV = EvaluateExprAsBool(Cond); Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); } /// getCGRecordLayout - Return record layout info. const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT, QualType Ty) { const RecordType *RTy = Ty->getAsRecordType(); assert (RTy && "Unexpected type. RecordType expected here."); return CGT.getCGRecordLayout(RTy->getDecl()); } /// ErrorUnsupported - Print out an error that codegen doesn't support the /// specified stmt yet. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, bool OmitOnError) { CGM.ErrorUnsupported(S, Type, OmitOnError); } unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) { // Use LabelIDs.size() as the new ID if one hasn't been assigned. return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second; } void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) { const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); if (DestPtr->getType() != BP) DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); // Get size and alignment info for this aggregate. std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); // FIXME: Handle variable sized types. const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth); Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty), // TypeInfo.first describes size in bits. llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8)); } void CodeGenFunction::EmitIndirectSwitches() { llvm::BasicBlock *Default; if (IndirectSwitches.empty()) return; if (!LabelIDs.empty()) { Default = getBasicBlockForLabel(LabelIDs.begin()->first); } else { // No possible targets for indirect goto, just emit an infinite // loop. Default = createBasicBlock("indirectgoto.loop", CurFn); llvm::BranchInst::Create(Default, Default); } for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(), e = IndirectSwitches.end(); i != e; ++i) { llvm::SwitchInst *I = *i; I->setSuccessor(0, Default); for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) { I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty, LI->second), getBasicBlockForLabel(LI->first)); } } } llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { llvm::Value *&SizeEntry = VLASizeMap[VAT]; assert(SizeEntry && "Did not emit size for type"); return SizeEntry; } llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { assert(Ty->isVariablyModifiedType() && "Must pass variably modified type to EmitVLASizes!"); if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { llvm::Value *&SizeEntry = VLASizeMap[VAT]; if (!SizeEntry) { // Get the element size; llvm::Value *ElemSize; QualType ElemTy = VAT->getElementType(); const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); if (ElemTy->isVariableArrayType()) ElemSize = EmitVLASize(ElemTy); else { ElemSize = llvm::ConstantInt::get(SizeTy, getContext().getTypeSize(ElemTy) / 8); } llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); SizeEntry = Builder.CreateMul(ElemSize, NumElements); } return SizeEntry; } else if (const PointerType *PT = Ty->getAsPointerType()) EmitVLASize(PT->getPointeeType()); else { assert(0 && "unknown VM type!"); } return 0; } llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { if (CGM.getContext().getBuiltinVaListType()->isArrayType()) { return EmitScalarExpr(E); } return EmitLValue(E).getAddress(); } void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) { CleanupEntries.push_back(CleanupEntry(CleanupBlock)); } void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) { assert(CleanupEntries.size() >= OldCleanupStackSize && "Cleanup stack mismatch!"); while (CleanupEntries.size() > OldCleanupStackSize) EmitCleanupBlock(); } CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() { CleanupEntry &CE = CleanupEntries.back(); llvm::BasicBlock *CleanupBlock = CE.CleanupBlock; std::vector<llvm::BasicBlock *> Blocks; std::swap(Blocks, CE.Blocks); std::vector<llvm::BranchInst *> BranchFixups; std::swap(BranchFixups, CE.BranchFixups); CleanupEntries.pop_back(); // Check if any branch fixups pointed to the scope we just popped. If so, // we can remove them. for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0); BlockScopeMap::iterator I = BlockScopes.find(Dest); if (I == BlockScopes.end()) continue; assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!"); if (I->second == CleanupEntries.size()) { // We don't need to do this branch fixup. BranchFixups[i] = BranchFixups.back(); BranchFixups.pop_back(); i--; e--; continue; } } llvm::BasicBlock *SwitchBlock = 0; llvm::BasicBlock *EndBlock = 0; if (!BranchFixups.empty()) { SwitchBlock = createBasicBlock("cleanup.switch"); EndBlock = createBasicBlock("cleanup.end"); llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); Builder.SetInsertPoint(SwitchBlock); llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty, "cleanup.dst"); llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp"); // Create a switch instruction to determine where to jump next. llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, BranchFixups.size()); // Restore the current basic block (if any) if (CurBB) { Builder.SetInsertPoint(CurBB); // If we had a current basic block, we also need to emit an instruction // to initialize the cleanup destination. Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::Int32Ty), DestCodePtr); } else Builder.ClearInsertionPoint(); for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { llvm::BranchInst *BI = BranchFixups[i]; llvm::BasicBlock *Dest = BI->getSuccessor(0); // Fixup the branch instruction to point to the cleanup block. BI->setSuccessor(0, CleanupBlock); if (CleanupEntries.empty()) { llvm::ConstantInt *ID; // Check if we already have a destination for this block. if (Dest == SI->getDefaultDest()) ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0); else { ID = SI->findCaseDest(Dest); if (!ID) { // No code found, get a new unique one by using the number of // switch successors. ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors()); SI->addCase(ID, Dest); } } // Store the jump destination before the branch instruction. new llvm::StoreInst(ID, DestCodePtr, BI); } else { // We need to jump through another cleanup block. Create a pad block // with a branch instruction that jumps to the final destination and // add it as a branch fixup to the current cleanup scope. // Create the pad block. llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn); // Create a unique case ID. llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors()); // Store the jump destination before the branch instruction. new llvm::StoreInst(ID, DestCodePtr, BI); // Add it as the destination. SI->addCase(ID, CleanupPad); // Create the branch to the final destination. llvm::BranchInst *BI = llvm::BranchInst::Create(Dest); CleanupPad->getInstList().push_back(BI); // And add it as a branch fixup. CleanupEntries.back().BranchFixups.push_back(BI); } } } // Remove all blocks from the block scope map. for (size_t i = 0, e = Blocks.size(); i != e; ++i) { assert(BlockScopes.count(Blocks[i]) && "Did not find block in scope map!"); BlockScopes.erase(Blocks[i]); } return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock); } void CodeGenFunction::EmitCleanupBlock() { CleanupBlockInfo Info = PopCleanupBlock(); EmitBlock(Info.CleanupBlock); if (Info.SwitchBlock) EmitBlock(Info.SwitchBlock); if (Info.EndBlock) EmitBlock(Info.EndBlock); } void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) { assert(!CleanupEntries.empty() && "Trying to add branch fixup without cleanup block!"); // FIXME: We could be more clever here and check if there's already a // branch fixup for this destination and recycle it. CleanupEntries.back().BranchFixups.push_back(BI); } void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) { if (!HaveInsertPoint()) return; llvm::BranchInst* BI = Builder.CreateBr(Dest); Builder.ClearInsertionPoint(); // The stack is empty, no need to do any cleanup. if (CleanupEntries.empty()) return; if (!Dest->getParent()) { // We are trying to branch to a block that hasn't been inserted yet. AddBranchFixup(BI); return; } BlockScopeMap::iterator I = BlockScopes.find(Dest); if (I == BlockScopes.end()) { // We are trying to jump to a block that is outside of any cleanup scope. AddBranchFixup(BI); return; } assert(I->second < CleanupEntries.size() && "Trying to branch into cleanup region"); if (I->second == CleanupEntries.size() - 1) { // We have a branch to a block in the same scope. return; } AddBranchFixup(BI); } <file_sep>/test/Preprocessor/cxx_compl.cpp // RUN: clang-cc -DA=1 -E %s | grep 'int a = 37 == 37' && // RUN: clang-cc -DA=0 -E %s | grep 'int a = 927 == 927' && // RUN: clang-cc -E %s | grep 'int a = 927 == 927' #if compl 0 bitand A #define X 37 #else #define X 927 #endif #if ~0 & A #define Y 37 #else #define Y 927 #endif int a = X == Y; <file_sep>/test/CodeGen/typedef-func.c // RUN: clang-cc -emit-llvm < %s // PR2414 struct mad_frame{}; enum mad_flow {}; typedef enum mad_flow filter_func_t(void *, struct mad_frame *); filter_func_t mono_filter; void addfilter2(filter_func_t *func){} void setup_filters() { addfilter2( mono_filter); } <file_sep>/test/Parser/cxx-casting.cpp // RUN: clang-cc -fsyntax-only %s char *const_cast_test(const char *var) { return const_cast<char*>(var); } #if 0 // FIXME: Uncomment when C++ is supported more. struct A { virtual ~A() {} }; struct B : public A { }; struct B *dynamic_cast_test(struct A *a) { return dynamic_cast<struct B*>(a); } #endif char *reinterpret_cast_test() { return reinterpret_cast<char*>(0xdeadbeef); } double static_cast_test(int i) { return static_cast<double>(i); } char postfix_expr_test() { return reinterpret_cast<char*>(0xdeadbeef)[0]; } <file_sep>/test/Preprocessor/poison.c // RUN: clang-cc %s -E 2>&1 | grep error #pragma GCC poison rindex rindex(some_string, 'h'); <file_sep>/test/CodeGen/attr-nodebug.c // RUN: clang-cc -g -emit-llvm -o %t %s && // RUN: not grep 'call void @llvm.dbg.func.start' %t void t1() __attribute__((nodebug)); void t1() { int a = 10; a++; } <file_sep>/test/CodeGen/builtins-powi.c // RUN: clang-cc -emit-llvm -o - %s > %t // RUN: ! grep "__builtin" %t #include <stdio.h> #include <stdlib.h> #include <math.h> void test(long double a, int b) { printf("%Lf**%d: %08x %08x %016Lx\n", a, b, __builtin_powi(a, b), __builtin_powif(a, b), __builtin_powil(a, b) ); } int main() { int i; test(-1,-1LL); test(0,0); test(1,1); for (i=0; i<3; i++) { test(random(), i); } return 0; } <file_sep>/lib/Frontend/InitHeaderSearch.cpp //===--- InitHeaderSearch.cpp - Initialize header search paths ----------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the InitHeaderSearch class. // //===----------------------------------------------------------------------===// #include "clang/Frontend/InitHeaderSearch.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/System/Path.h" #include "llvm/Config/config.h" #include <cstdio> #include <vector> using namespace clang; void InitHeaderSearch::AddPath(const std::string &Path, IncludeDirGroup Group, bool isCXXAware, bool isUserSupplied, bool isFramework, bool IgnoreSysRoot) { assert(!Path.empty() && "can't handle empty path here"); FileManager &FM = Headers.getFileMgr(); // Compute the actual path, taking into consideration -isysroot. llvm::SmallString<256> MappedPath; // Handle isysroot. if (Group == System && !IgnoreSysRoot) { // FIXME: Portability. This should be a sys::Path interface, this doesn't // handle things like C:\ right, nor win32 \\network\device\blah. if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present. MappedPath.append(isysroot.begin(), isysroot.end()); } MappedPath.append(Path.begin(), Path.end()); // Compute the DirectoryLookup type. SrcMgr::CharacteristicKind Type; if (Group == Quoted || Group == Angled) Type = SrcMgr::C_User; else if (isCXXAware) Type = SrcMgr::C_System; else Type = SrcMgr::C_ExternCSystem; // If the directory exists, add it. if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0], &MappedPath[0]+ MappedPath.size())) { IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied, isFramework)); return; } // Check to see if this is an apple-style headermap (which are not allowed to // be frameworks). if (!isFramework) { if (const FileEntry *FE = FM.getFile(&MappedPath[0], &MappedPath[0]+MappedPath.size())) { if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) { // It is a headermap, add it to the search path. IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied)); return; } } } if (Verbose) fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", MappedPath.c_str()); } void InitHeaderSearch::AddEnvVarPaths(const char *Name) { const char* at = getenv(Name); if (!at || *at == 0) // Empty string should not add '.' path. return; const char* delim = strchr(at, llvm::sys::PathSeparator); while (delim != 0) { if (delim-at == 0) AddPath(".", Angled, false, true, false); else AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false, true, false); at = delim + 1; delim = strchr(at, llvm::sys::PathSeparator); } if (*at == 0) AddPath(".", Angled, false, true, false); else AddPath(at, Angled, false, true, false); } void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang) { // FIXME: temporary hack: hard-coded paths. // FIXME: get these from the target? #ifdef LLVM_ON_WIN32 if (Lang.CPlusPlus) { // Mingw32 GCC version 4 AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++", System, true, false, false); AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/mingw32", System, true, false, false); AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/backward", System, true, false, false); } // Mingw32 GCC version 4 AddPath("C:/mingw/include", System, false, false, false); #else if (Lang.CPlusPlus) { AddPath("/usr/include/c++/4.2.1", System, true, false, false); AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false, false); AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false); AddPath("/usr/include/c++/4.0.0", System, true, false, false); AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false, false); AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false); // Ubuntu 7.10 - Gutsy Gibbon AddPath("/usr/include/c++/4.1.3", System, true, false, false); AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false, false); AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false); // Fedora 8 AddPath("/usr/include/c++/4.1.2", System, true, false, false); AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false); // Fedora 9 AddPath("/usr/include/c++/4.3.0", System, true, false, false); AddPath("/usr/include/c++/4.3.0/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.3.0/backward", System, true, false, false); // Fedora 10 AddPath("/usr/include/c++/4.3.2", System, true, false, false); AddPath("/usr/include/c++/4.3.2/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.3.2/backward", System, true, false, false); // Arch Linux 2008-06-24 AddPath("/usr/include/c++/4.3.1", System, true, false, false); AddPath("/usr/include/c++/4.3.1/i686-pc-linux-gnu", System, true, false, false); AddPath("/usr/include/c++/4.3.1/backward", System, true, false, false); AddPath("/usr/include/c++/4.3.1/x86_64-unknown-linux-gnu", System, true, false, false); // Gentoo x86 stable AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4", System, true, false, false); AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/" "i686-pc-linux-gnu", System, true, false, false); AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/backward", System, true, false, false); // DragonFly AddPath("/usr/include/c++/4.1", System, true, false, false); // FreeBSD AddPath("/usr/include/c++/4.2", System, true, false, false); } AddPath("/usr/local/include", System, false, false, false); AddPath("/usr/include", System, false, false, false); AddPath("/System/Library/Frameworks", System, true, false, true); AddPath("/Library/Frameworks", System, true, false, true); #endif } void InitHeaderSearch::AddDefaultEnvVarPaths(const LangOptions &Lang) { AddEnvVarPaths("CPATH"); if (Lang.CPlusPlus && Lang.ObjC1) AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH"); else if (Lang.CPlusPlus) AddEnvVarPaths("CPLUS_INCLUDE_PATH"); else if (Lang.ObjC1) AddEnvVarPaths("OBJC_INCLUDE_PATH"); else AddEnvVarPaths("C_INCLUDE_PATH"); } /// RemoveDuplicates - If there are duplicate directory entries in the specified /// search list, remove the later (dead) ones. static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList, bool Verbose) { llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs; llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs; llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps; for (unsigned i = 0; i != SearchList.size(); ++i) { unsigned DirToRemove = i; const DirectoryLookup &CurEntry = SearchList[i]; if (CurEntry.isNormalDir()) { // If this isn't the first time we've seen this dir, remove it. if (SeenDirs.insert(CurEntry.getDir())) continue; } else if (CurEntry.isFramework()) { // If this isn't the first time we've seen this framework dir, remove it. if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir())) continue; } else { assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?"); // If this isn't the first time we've seen this headermap, remove it. if (SeenHeaderMaps.insert(CurEntry.getHeaderMap())) continue; } // If we have a normal #include dir/framework/headermap that is shadowed // later in the chain by a system include location, we actually want to // ignore the user's request and drop the user dir... keeping the system // dir. This is weird, but required to emulate GCC's search path correctly. // // Since dupes of system dirs are rare, just rescan to find the original // that we're nuking instead of using a DenseMap. if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) { // Find the dir that this is the same of. unsigned FirstDir; for (FirstDir = 0; ; ++FirstDir) { assert(FirstDir != i && "Didn't find dupe?"); const DirectoryLookup &SearchEntry = SearchList[FirstDir]; // If these are different lookup types, then they can't be the dupe. if (SearchEntry.getLookupType() != CurEntry.getLookupType()) continue; bool isSame; if (CurEntry.isNormalDir()) isSame = SearchEntry.getDir() == CurEntry.getDir(); else if (CurEntry.isFramework()) isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir(); else { assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?"); isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap(); } if (isSame) break; } // If the first dir in the search path is a non-system dir, zap it // instead of the system one. if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User) DirToRemove = FirstDir; } if (Verbose) { fprintf(stderr, "ignoring duplicate directory \"%s\"\n", CurEntry.getName()); if (DirToRemove != i) fprintf(stderr, " as it is a non-system directory that duplicates" " a system directory\n"); } // This is reached if the current entry is a duplicate. Remove the // DirToRemove (usually the current dir). SearchList.erase(SearchList.begin()+DirToRemove); --i; } } void InitHeaderSearch::Realize() { // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList. std::vector<DirectoryLookup> SearchList; SearchList = IncludeGroup[Angled]; SearchList.insert(SearchList.end(), IncludeGroup[System].begin(), IncludeGroup[System].end()); SearchList.insert(SearchList.end(), IncludeGroup[After].begin(), IncludeGroup[After].end()); RemoveDuplicates(SearchList, Verbose); RemoveDuplicates(IncludeGroup[Quoted], Verbose); // Prepend QUOTED list on the search list. SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(), IncludeGroup[Quoted].end()); bool DontSearchCurDir = false; // TODO: set to true if -I- is set? Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(), DontSearchCurDir); // If verbose, print the list of directories that will be searched. if (Verbose) { fprintf(stderr, "#include \"...\" search starts here:\n"); unsigned QuotedIdx = IncludeGroup[Quoted].size(); for (unsigned i = 0, e = SearchList.size(); i != e; ++i) { if (i == QuotedIdx) fprintf(stderr, "#include <...> search starts here:\n"); const char *Name = SearchList[i].getName(); const char *Suffix; if (SearchList[i].isNormalDir()) Suffix = ""; else if (SearchList[i].isFramework()) Suffix = " (framework directory)"; else { assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup"); Suffix = " (headermap)"; } fprintf(stderr, " %s%s\n", Name, Suffix); } fprintf(stderr, "End of search list.\n"); } } <file_sep>/tools/clang-cc/PrintParserCallbacks.cpp //===--- PrintParserActions.cpp - Implement -parse-print-callbacks mode ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This code simply runs the preprocessor on the input file and prints out the // result. This is the traditional behavior of the -E option. // //===----------------------------------------------------------------------===// #include "clang-cc.h" #include "clang/Parse/Action.h" #include "clang/Parse/DeclSpec.h" #include "llvm/Support/Streams.h" using namespace clang; namespace { class ParserPrintActions : public MinimalAction { public: ParserPrintActions(Preprocessor &PP) : MinimalAction(PP) {} // Printing Functions which also must call MinimalAction /// ActOnDeclarator - This callback is invoked when a declarator is parsed /// and 'Init' specifies the initializer if any. This is for things like: /// "int X = 4" or "typedef int foo". virtual DeclPtrTy ActOnDeclarator(Scope *S, Declarator &D) { llvm::cout << __FUNCTION__ << " "; if (IdentifierInfo *II = D.getIdentifier()) { llvm::cout << "'" << II->getName() << "'"; } else { llvm::cout << "<anon>"; } llvm::cout << "\n"; // Pass up to EmptyActions so that the symbol table is maintained right. return MinimalAction::ActOnDeclarator(S, D); } /// ActOnPopScope - This callback is called immediately before the specified /// scope is popped and deleted. virtual void ActOnPopScope(SourceLocation Loc, Scope *S) { llvm::cout << __FUNCTION__ << "\n"; return MinimalAction::ActOnPopScope(Loc, S); } /// ActOnTranslationUnitScope - This callback is called once, immediately /// after creating the translation unit scope (in Parser::Initialize). virtual void ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { llvm::cout << __FUNCTION__ << "\n"; MinimalAction::ActOnTranslationUnitScope(Loc, S); } Action::DeclPtrTy ActOnStartClassInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtocols, SourceLocation EndProtoLoc, AttributeList *AttrList) { llvm::cout << __FUNCTION__ << "\n"; return MinimalAction::ActOnStartClassInterface(AtInterfaceLoc, ClassName, ClassLoc, SuperName, SuperLoc, ProtoRefs, NumProtocols, EndProtoLoc, AttrList); } /// ActOnForwardClassDeclaration - /// Scope will always be top level file scope. Action::DeclPtrTy ActOnForwardClassDeclaration(SourceLocation AtClassLoc, IdentifierInfo **IdentList, unsigned NumElts) { llvm::cout << __FUNCTION__ << "\n"; return MinimalAction::ActOnForwardClassDeclaration(AtClassLoc, IdentList, NumElts); } // Pure Printing /// ActOnParamDeclarator - This callback is invoked when a parameter /// declarator is parsed. This callback only occurs for functions /// with prototypes. S is the function prototype scope for the /// parameters (C++ [basic.scope.proto]). virtual DeclPtrTy ActOnParamDeclarator(Scope *S, Declarator &D) { llvm::cout << __FUNCTION__ << " "; if (IdentifierInfo *II = D.getIdentifier()) { llvm::cout << "'" << II->getName() << "'"; } else { llvm::cout << "<anon>"; } llvm::cout << "\n"; return DeclPtrTy(); } /// AddInitializerToDecl - This action is called immediately after /// ParseDeclarator (when an initializer is present). The code is factored /// this way to make sure we are able to handle the following: /// void func() { int xx = xx; } /// This allows ActOnDeclarator to register "xx" prior to parsing the /// initializer. The declaration above should still result in a warning, /// since the reference to "xx" is uninitialized. virtual void AddInitializerToDecl(DeclPtrTy Dcl, ExprArg Init) { llvm::cout << __FUNCTION__ << "\n"; } /// FinalizeDeclaratorGroup - After a sequence of declarators are parsed, /// this gives the actions implementation a chance to process the group as /// a whole. virtual DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, DeclPtrTy *Group, unsigned NumDecls) { llvm::cout << __FUNCTION__ << "\n"; return DeclGroupPtrTy(); } /// ActOnStartOfFunctionDef - This is called at the start of a function /// definition, instead of calling ActOnDeclarator. The Declarator includes /// information about formal arguments that are part of this function. virtual DeclPtrTy ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D){ llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } /// ActOnStartOfFunctionDef - This is called at the start of a function /// definition, after the FunctionDecl has already been created. virtual DeclPtrTy ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } virtual void ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) { llvm::cout << __FUNCTION__ << "\n"; } /// ActOnFunctionDefBody - This is called when a function body has completed /// parsing. Decl is the DeclTy returned by ParseStartOfFunctionDef. virtual DeclPtrTy ActOnFinishFunctionBody(DeclPtrTy Decl, StmtArg Body) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } virtual DeclPtrTy ActOnFileScopeAsmDecl(SourceLocation Loc, ExprArg AsmString) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with /// no declarator (e.g. "struct foo;") is parsed. virtual DeclPtrTy ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } /// ActOnLinkageSpec - Parsed a C++ linkage-specification that /// contained braces. Lang/StrSize contains the language string that /// was parsed at location Loc. Decls/NumDecls provides the /// declarations parsed inside the linkage specification. virtual DeclPtrTy ActOnLinkageSpec(SourceLocation Loc, SourceLocation LBrace, SourceLocation RBrace, const char *Lang, unsigned StrSize, DeclPtrTy *Decls, unsigned NumDecls) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } /// ActOnLinkageSpec - Parsed a C++ linkage-specification without /// braces. Lang/StrSize contains the language string that was /// parsed at location Loc. D is the declaration parsed. virtual DeclPtrTy ActOnLinkageSpec(SourceLocation Loc, const char *Lang, unsigned StrSize, DeclPtrTy D) { return DeclPtrTy(); } //===--------------------------------------------------------------------===// // Type Parsing Callbacks. //===--------------------------------------------------------------------===// virtual TypeResult ActOnTypeName(Scope *S, Declarator &D) { llvm::cout << __FUNCTION__ << "\n"; return TypeResult(); } virtual DeclPtrTy ActOnTag(Scope *S, unsigned TagType, TagKind TK, SourceLocation KWLoc, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, AccessSpecifier AS) { // TagType is an instance of DeclSpec::TST, indicating what kind of tag this // is (struct/union/enum/class). llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } /// Act on @defs() element found when parsing a structure. ClassName is the /// name of the referenced class. virtual void ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, llvm::SmallVectorImpl<DeclPtrTy> &Decls) { llvm::cout << __FUNCTION__ << "\n"; } virtual DeclPtrTy ActOnField(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart, Declarator &D, ExprTy *BitfieldWidth) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } virtual DeclPtrTy ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, ExprTy *BitfieldWidth, tok::ObjCKeywordKind visibility) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } virtual void ActOnFields(Scope* S, SourceLocation RecLoc, DeclPtrTy TagDecl, DeclPtrTy *Fields, unsigned NumFields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList) { llvm::cout << __FUNCTION__ << "\n"; } virtual DeclPtrTy ActOnEnumConstant(Scope *S, DeclPtrTy EnumDecl, DeclPtrTy LastEnumConstant, SourceLocation IdLoc,IdentifierInfo *Id, SourceLocation EqualLoc, ExprTy *Val) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } virtual void ActOnEnumBody(SourceLocation EnumLoc, DeclPtrTy EnumDecl, DeclPtrTy *Elements, unsigned NumElements) { llvm::cout << __FUNCTION__ << "\n"; } //===--------------------------------------------------------------------===// // Statement Parsing Callbacks. //===--------------------------------------------------------------------===// virtual OwningStmtResult ActOnNullStmt(SourceLocation SemiLoc) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, MultiStmtArg Elts, bool isStmtExpr) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnExprStmt(ExprArg Expr) { llvm::cout << __FUNCTION__ << "\n"; return OwningStmtResult(*this, Expr.release()); } /// ActOnCaseStmt - Note that this handles the GNU 'case 1 ... 4' extension, /// which can specify an RHS value. virtual OwningStmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprArg LHSVal, SourceLocation DotDotDotLoc, ExprArg RHSVal, SourceLocation ColonLoc) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, StmtArg SubStmt, Scope *CurScope){ llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation ColonLoc, StmtArg SubStmt) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnIfStmt(SourceLocation IfLoc, ExprArg CondVal, StmtArg ThenVal,SourceLocation ElseLoc, StmtArg ElseVal) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnStartOfSwitchStmt(ExprArg Cond) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch, StmtArg Body) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnWhileStmt(SourceLocation WhileLoc, ExprArg Cond, StmtArg Body) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, SourceLocation WhileLoc, ExprArg Cond){ llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, StmtArg First, ExprArg Second, ExprArg Third, SourceLocation RParenLoc, StmtArg Body) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnObjCForCollectionStmt( SourceLocation ForColLoc, SourceLocation LParenLoc, StmtArg First, ExprArg Second, SourceLocation RParenLoc, StmtArg Body) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, IdentifierInfo *LabelII) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, ExprArg DestExp) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg RetValExp) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, std::string *Names, MultiExprArg Constraints, MultiExprArg Exprs, ExprArg AsmString, MultiExprArg Clobbers, SourceLocation RParenLoc) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } // Objective-c statements virtual OwningStmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, DeclPtrTy Parm, StmtArg Body, StmtArg CatchList) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, StmtArg Try, StmtArg Catch, StmtArg Finally) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw, Scope *CurScope) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr, StmtArg SynchBody) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } // C++ Statements virtual DeclPtrTy ActOnExceptionDeclarator(Scope *S, Declarator &D) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } virtual OwningStmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExceptionDecl, StmtArg HandlerBlock) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } virtual OwningStmtResult ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock, MultiStmtArg Handlers) { llvm::cout << __FUNCTION__ << "\n"; return StmtEmpty(); } //===--------------------------------------------------------------------===// // Expression Parsing Callbacks. //===--------------------------------------------------------------------===// // Primary Expressions. /// ActOnIdentifierExpr - Parse an identifier in expression context. /// 'HasTrailingLParen' indicates whether or not the identifier has a '(' /// token immediately after it. virtual OwningExprResult ActOnIdentifierExpr(Scope *S, SourceLocation Loc, IdentifierInfo &II, bool HasTrailingLParen, const CXXScopeSpec *SS, bool isAddressOfOperand) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXOperatorFunctionIdExpr( Scope *S, SourceLocation OperatorLoc, OverloadedOperatorKind Op, bool HasTrailingLParen, const CXXScopeSpec &SS, bool isAddressOfOperand) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXConversionFunctionExpr( Scope *S, SourceLocation OperatorLoc, TypeTy *Type, bool HasTrailingLParen, const CXXScopeSpec &SS,bool isAddressOfOperand) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCharacterConstant(const Token &) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnNumericConstant(const Token &) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). virtual OwningExprResult ActOnStringLiteral(const Token *Toks, unsigned NumToks) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, ExprArg Val) { llvm::cout << __FUNCTION__ << "\n"; return move(Val); // Default impl returns operand. } // Postfix Expressions. virtual OwningExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, ExprArg Input) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, ExprArg Idx, SourceLocation RLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation MemberLoc, IdentifierInfo &Member, DeclPtrTy ImplDecl) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCallExpr(Scope *S, ExprArg Fn, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation *CommaLocs, SourceLocation RParenLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } // Unary Operators. 'Tok' is the token for the operator. virtual OwningExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, ExprArg Input) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, void *TyOrEx, const SourceRange &ArgRange) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCompoundLiteral(SourceLocation LParen, TypeTy *Ty, SourceLocation RParen, ExprArg Op) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnInitList(SourceLocation LParenLoc, MultiExprArg InitList, SourceLocation RParenLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, SourceLocation RParenLoc,ExprArg Op){ llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, ExprArg LHS, ExprArg RHS) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. virtual OwningExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, ExprArg Cond, ExprArg LHS, ExprArg RHS) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } //===--------------------- GNU Extension Expressions ------------------===// virtual OwningExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, IdentifierInfo *LabelII) {// "&&foo" llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnStmtExpr(SourceLocation LPLoc, StmtArg SubStmt, SourceLocation RPLoc) { // "({..})" llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, TypeTy *Arg1, OffsetOfComponent *CompPtr, unsigned NumComponents, SourceLocation RParenLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } // __builtin_types_compatible_p(type1, type2) virtual OwningExprResult ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, TypeTy *arg1,TypeTy *arg2, SourceLocation RPLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } // __builtin_choose_expr(constExpr, expr1, expr2) virtual OwningExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, ExprArg cond, ExprArg expr1, ExprArg expr2, SourceLocation RPLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } // __builtin_va_arg(expr, type) virtual OwningExprResult ActOnVAArg(SourceLocation BuiltinLoc, ExprArg expr, TypeTy *type, SourceLocation RPLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnGNUNullExpr(SourceLocation TokenLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { llvm::cout << __FUNCTION__ << "\n"; } virtual void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { llvm::cout << __FUNCTION__ << "\n"; } virtual void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { llvm::cout << __FUNCTION__ << "\n"; } virtual OwningExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtArg Body, Scope *CurScope) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual DeclPtrTy ActOnStartNamespaceDef(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } virtual void ActOnFinishNamespaceDef(DeclPtrTy Dcl, SourceLocation RBrace) { llvm::cout << __FUNCTION__ << "\n"; return; } #if 0 // FIXME: AttrList should be deleted by this function, but the definition // would have to be available. virtual DeclPtrTy ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, const CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, AttributeList *AttrList) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } #endif virtual void ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, ExprArg defarg) { llvm::cout << __FUNCTION__ << "\n"; } virtual void ActOnParamUnparsedDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc) { llvm::cout << __FUNCTION__ << "\n"; } virtual void ActOnParamDefaultArgumentError(DeclPtrTy param) { llvm::cout << __FUNCTION__ << "\n"; } virtual void AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { llvm::cout << __FUNCTION__ << "\n"; return; } virtual void ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy Method) { llvm::cout << __FUNCTION__ << "\n"; } virtual void ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy Param) { llvm::cout << __FUNCTION__ << "\n"; } virtual void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy Method) { llvm::cout << __FUNCTION__ << "\n"; } virtual DeclPtrTy ActOnStaticAssertDeclaration(SourceLocation AssertLoc, ExprArg AssertExpr, ExprArg AssertMessageExpr) { llvm::cout << __FUNCTION__ << "\n"; return DeclPtrTy(); } virtual OwningExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, TypeTy *Ty, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, ExprArg Op, SourceLocation RParenLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXThis(SourceLocation ThisLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXThrow(SourceLocation OpLoc, ExprArg Op) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, Declarator &D, SourceLocation EqualLoc, ExprArg AssignExprVal) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, bool ParenTypeId, Declarator &D, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, ExprArg Operand) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } virtual OwningExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, SourceLocation KWLoc, SourceLocation LParen, TypeTy *Ty, SourceLocation RParen) { llvm::cout << __FUNCTION__ << "\n"; return ExprEmpty(); } }; } MinimalAction *clang::CreatePrintParserActionsAction(Preprocessor &PP) { return new ParserPrintActions(PP); } <file_sep>/test/SemaCXX/overload-call-copycon.cpp // RUN: clang-cc -fsyntax-only %s class X { }; int& copycon(X x); float& copycon(...); void test_copycon(X x, X const xc, X volatile xv) { int& i1 = copycon(x); int& i2 = copycon(xc); float& f1 = copycon(xv); } class A { public: A(A&); }; class B : public A { }; short& copycon2(A a); int& copycon2(B b); float& copycon2(...); void test_copycon2(A a, const A ac, B b, B const bc, B volatile bv) { int& i1 = copycon2(b); float& f1 = copycon2(bc); float& f2 = copycon2(bv); short& s1 = copycon2(a); float& f3 = copycon2(ac); } int& copycon3(A a); float& copycon3(...); void test_copycon3(B b, const B bc) { int& i1 = copycon3(b); float& f1 = copycon3(bc); } class C : public B { }; float& copycon4(A a); int& copycon4(B b); void test_copycon4(C c) { int& i = copycon4(c); }; <file_sep>/test/Sema/shift.c // RUN: clang-cc -fsyntax-only %s void test() { char c; c <<= 14; } <file_sep>/lib/Analysis/GRSimpleVals.h // GRSimpleVals.h - Transfer functions for tracking simple values -*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines GRSimpleVals, a sub-class of GRTransferFuncs that // provides transfer functions for performing simple value tracking with // limited support for symbolics. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_GRSIMPLEVALS #define LLVM_CLANG_ANALYSIS_GRSIMPLEVALS #include "clang/Analysis/PathSensitive/GRTransferFuncs.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" namespace clang { class PathDiagnostic; class ASTContext; class GRSimpleVals : public GRTransferFuncs { protected: virtual SVal DetermEvalBinOpNN(GRExprEngine& Eng, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, QualType T); public: GRSimpleVals() {} virtual ~GRSimpleVals() {} // Casts. virtual SVal EvalCast(GRExprEngine& Engine, NonLoc V, QualType CastT); virtual SVal EvalCast(GRExprEngine& Engine, Loc V, QualType CastT); // Unary Operators. virtual SVal EvalMinus(GRExprEngine& Engine, UnaryOperator* U, NonLoc X); virtual SVal EvalComplement(GRExprEngine& Engine, NonLoc X); // Binary Operators. virtual SVal EvalBinOp(GRExprEngine& Engine, BinaryOperator::Opcode Op, Loc L, Loc R); // Pointer arithmetic. virtual SVal EvalBinOp(GRExprEngine& Engine, BinaryOperator::Opcode Op, Loc L, NonLoc R); // Calls. virtual void EvalCall(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, CallExpr* CE, SVal L, ExplodedNode<GRState>* Pred); virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, ObjCMessageExpr* ME, ExplodedNode<GRState>* Pred); static void GeneratePathDiagnostic(PathDiagnostic& PD, ASTContext& Ctx, ExplodedNode<GRState>* N); protected: // Equality operators for Locs. SVal EvalEQ(GRExprEngine& Engine, Loc L, Loc R); SVal EvalNE(GRExprEngine& Engine, Loc L, Loc R); }; } // end clang namespace #endif <file_sep>/test/SemaCXX/function-redecl.cpp // RUN: clang-cc -fsyntax-only -verify %s int foo(int); namespace N { void f1() { void foo(int); // okay } // FIXME: we shouldn't even need this declaration to detect errors // below. void foo(int); // expected-note{{previous declaration is here}} void f2() { int foo(int); // expected-error{{functions that differ only in their return type cannot be overloaded}} { int foo; { // FIXME: should diagnose this because it's incompatible with // N::foo. However, name lookup isn't properly "skipping" the // "int foo" above. float foo(int); } } } } <file_sep>/test/SemaTemplate/right-angle-brackets-0x.cpp // RUN: clang-cc -fsyntax-only -std=c++0x -verify %s template<typename T> struct X; template<int I> struct Y; X<X<int>> *x1; Y<(1 >> 2)> *y1; Y<1 >> 2> *y2; // FIXME: expected-error{{expected unqualified-id}} X<X<X<X<X<int>>>>> *x2; template<> struct X<int> { }; typedef X<int> X_int; struct Z : X_int { }; void f(const X<int> x) { (void)reinterpret_cast<X<int>>(x); // expected-error{{reinterpret_cast from}} (void)reinterpret_cast<X<X<X<int>>>>(x); // expected-error{{reinterpret_cast from}} X<X<int>> *x1; } <file_sep>/test/SemaCXX/__null.cpp // RUN: clang-cc -triple x86_64-unknown-unknown %s -fsyntax-only -verify && // RUN: clang-cc -triple i686-unknown-unknown %s -fsyntax-only -verify void f() { int* i = __null; i = __null; int i2 = __null; // Verify statically that __null is the right size int a[sizeof(typeof(__null)) == sizeof(void*)? 1 : -1]; // Verify that null is evaluated as 0. int b[__null ? -1 : 1]; } <file_sep>/test/Parser/typeof.c // RUN: clang-cc -fsyntax-only -verify %s typedef int TInt; static void test() { int *pi; int typeof (int) aIntInt; // expected-error{{cannot combine with previous 'int' declaration specifier}} short typeof (int) aShortInt; // expected-error{{'short typeof' is invalid}} int int ttt; // expected-error{{cannot combine with previous 'int' declaration specifier}} typeof(TInt) anInt; short TInt eee; // expected-error{{expected ';' at end of declaration}} void ary[7] fff; // expected-error{{array has incomplete element type 'void'}} expected-error{{expected ';' at end of declaration}} typeof(void ary[7]) anIntError; // expected-error{{expected ')'}} expected-note {{to match this '('}} expected-warning {{type specifier missing, defaults to 'int'}} typeof(const int) aci; const typeof (*pi) aConstInt; int xx; int *i; } <file_sep>/test/Parser/compound_literal.c // RUN: clang-cc -fsyntax-only -verify %s int main() { char *s; s = (char []){"whatever"}; } <file_sep>/test/CodeGen/const-init.c // RUN: clang-cc -arch i386 -verify -emit-llvm -o %t %s && #include <stdint.h> // Brace-enclosed string array initializers char a[] = { "asdf" }; // Double-implicit-conversions of array/functions (not legal C, but // clang accepts it for gcc compat). intptr_t b = a; // expected-warning {{incompatible pointer to integer conversion}} int c(); void *d = c; intptr_t e = c; // expected-warning {{incompatible pointer to integer conversion}} int f, *g = __extension__ &f, *h = (1 != 1) ? &f : &f; union s2 { struct { struct { } *f0; } f0; }; int g0 = (int)(&(((union s2 *) 0)->f0.f0) - 0); // RUN: grep '@g1x = global %. { double 1.000000e+00, double 0.000000e+00 }' %t && _Complex double g1x = 1.0f; // RUN: grep '@g1y = global %. { double 0.000000e+00, double 1.000000e+00 }' %t && _Complex double g1y = 1.0fi; // RUN: grep '@g1 = global %. { i8 1, i8 10 }' %t && _Complex char g1 = (char) 1 + (char) 10 * 1i; // RUN: grep '@g2 = global %2 { i32 1, i32 10 }' %t && _Complex int g2 = 1 + 10i; // RUN: grep '@g3 = global %. { float 1.000000e+00, float 1.000000e+01 }' %t && _Complex float g3 = 1.0 + 10.0i; // RUN: grep '@g4 = global %. { double 1.000000e+00, double 1.000000e+01 }' %t && _Complex double g4 = 1.0 + 10.0i; // RUN: grep '@g5 = global %2 zeroinitializer' %t && _Complex int g5 = (2 + 3i) == (5 + 7i); // RUN: grep '@g6 = global %. { double -1.100000e+01, double 2.900000e+01 }' %t && _Complex double g6 = (2.0 + 3.0i) * (5.0 + 7.0i); // RUN: grep '@g7 = global i32 1' %t && int g7 = (2 + 3i) * (5 + 7i) == (-11 + 29i); // RUN: grep '@g8 = global i32 1' %t && int g8 = (2.0 + 3.0i) * (5.0 + 7.0i) == (-11.0 + 29.0i); // RUN: grep '@g9 = global i32 0' %t && int g9 = (2 + 3i) * (5 + 7i) != (-11 + 29i); // RUN: grep '@g10 = global i32 0' %t && int g10 = (2.0 + 3.0i) * (5.0 + 7.0i) != (-11.0 + 29.0i); // Global references // RUN: grep '@g11.l0 = internal global i32 ptrtoint (i32 ()\* @g11 to i32)' %t && long g11() { static long l0 = (long) g11; return l0; } // RUN: grep '@g12 = global i32 ptrtoint (i8\* @g12_tmp to i32)' %t && static char g12_tmp; long g12 = (long) &g12_tmp; // RUN: grep '@g13 = global \[1 x .struct.g13_s0\] \[.struct.g13_s0 <{ i32 ptrtoint (i8\* @g12_tmp to i32) }>\]' %t && struct g13_s0 { long a; }; struct g13_s0 g13[] = { { (long) &g12_tmp } }; // RUN: grep '@g14 = global i8\* inttoptr (i64 100 to i8\*)' %t && void *g14 = (void*) 100; // RUN: grep '@g15 = global i32 -1' %t && int g15 = (int) (char) ((void*) 0 + 255); // RUN: grep '@g16 = global i64 4294967295' %t && long long g16 = (long long) ((void*) 0xFFFFFFFF); // RUN: grep '@g17 = global i32\* @g15' %t && int *g17 = (int *) ((long) &g15); // RUN: grep '@g18.p = internal global \[1 x i32\*\] \[i32\* @g19\]' %t && void g18(void) { extern int g19; static int *p[] = { &g19 }; } // RUN: grep '@g20.l0 = internal global .struct.g20_s1 <{ .struct.g20_s0\* null, .struct.g20_s0\*\* getelementptr (.struct.g20_s1\* @g20.l0, i32 0, i32 0) }>' %t && struct g20_s0; struct g20_s1 { struct g20_s0 *f0, **f1; }; void *g20(void) { static struct g20_s1 l0 = { ((void*) 0), &l0.f0 }; return l0.f1; } // RUN: true <file_sep>/lib/Parse/CMakeLists.txt set(LLVM_NO_RTTI 1) add_clang_library(clangParse AttributeList.cpp DeclSpec.cpp MinimalAction.cpp ParseCXXInlineMethods.cpp ParseDecl.cpp ParseDeclCXX.cpp ParseExpr.cpp ParseExprCXX.cpp ParseInit.cpp ParseObjc.cpp ParsePragma.cpp Parser.cpp ParseStmt.cpp ParseTentative.cpp ParseTemplate.cpp ) add_dependencies(clangParse ClangDiagnosticParse) <file_sep>/tools/ccc/test/ccc/ObjC.c // RUN: xcc -fsyntax-only %s -ObjC && // RUN: ! xcc -fsyntax-only -x c %s -ObjC && // RUN: xcc -fsyntax-only %s -ObjC++ && // RUN: ! xcc -fsyntax-only -x c %s -ObjC++ @interface A @end <file_sep>/tools/ccc/test/ccc/O.c // Just check that clang accepts these. // RUN: xcc -fsyntax-only -O1 -O2 %s && // RUN: xcc -fsyntax-only -O %s <file_sep>/test/SemaTemplate/instantiation-depth.cpp // RUN: clang-cc -fsyntax-only -ftemplate-depth=5 -verify %s template<typename T> struct X : X<T*> { }; // expected-error{{recursive template instantiation exceeded maximum depth of 5}} \ // expected-note{{use -ftemplate-depth-N to increase recursive template instantiation depth}} \ // expected-note 5 {{instantiation of template class}} void test() { (void)sizeof(X<int>); // expected-note {{instantiation of template class}} } <file_sep>/test/CodeGen/func-decl-cleanup.c // RUN: clang-cc %s -emit-llvm -o - // PR2360 typedef void fn_t(); fn_t a,b; void b() { } <file_sep>/test/CodeGen/cxx-default-arg.cpp // RUN: clang-cc -emit-llvm %s -o %t // Note: define CLANG_GENERATE_KNOWN_GOOD and compile to generate code // that makes all of the defaulted arguments explicit. The resulting // byte code should be identical to the compilation without // CLANG_GENERATE_KNOWN_GOOD. #ifdef CLANG_GENERATE_KNOWN_GOOD # define DEFARG(...) __VA_ARGS__ #else # define DEFARG(...) #endif extern int x; struct S { float x; float y; } s; double _Complex c; void f(int i = 0, int j = 1, int k = x, struct S t = s, double _Complex d = c); void g() { f(0, 1, x, s DEFARG(, c)); f(0, 1, x DEFARG(, s, c)); f(0, 1 DEFARG(, x, s, c)); f(0 DEFARG(, 1, x, s, c)); f(DEFARG(0, 1, x, s, c)); } <file_sep>/lib/AST/CFG.cpp //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the CFG and CFGBuilder classes for representing and // building Control-Flow Graphs (CFGs) from ASTs. // //===----------------------------------------------------------------------===// #include "clang/AST/CFG.h" #include "clang/AST/StmtVisitor.h" #include "clang/AST/PrettyPrinter.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/Streams.h" #include "llvm/Support/Compiler.h" #include <llvm/Support/Allocator.h> #include <llvm/Support/Format.h> #include <iomanip> #include <algorithm> #include <sstream> using namespace clang; namespace { // SaveAndRestore - A utility class that uses RIIA to save and restore // the value of a variable. template<typename T> struct VISIBILITY_HIDDEN SaveAndRestore { SaveAndRestore(T& x) : X(x), old_value(x) {} ~SaveAndRestore() { X = old_value; } T get() { return old_value; } T& X; T old_value; }; static SourceLocation GetEndLoc(Decl* D) { if (VarDecl* VD = dyn_cast<VarDecl>(D)) if (Expr* Ex = VD->getInit()) return Ex->getSourceRange().getEnd(); return D->getLocation(); } /// CFGBuilder - This class implements CFG construction from an AST. /// The builder is stateful: an instance of the builder should be used to only /// construct a single CFG. /// /// Example usage: /// /// CFGBuilder builder; /// CFG* cfg = builder.BuildAST(stmt1); /// /// CFG construction is done via a recursive walk of an AST. /// We actually parse the AST in reverse order so that the successor /// of a basic block is constructed prior to its predecessor. This /// allows us to nicely capture implicit fall-throughs without extra /// basic blocks. /// class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> { CFG* cfg; CFGBlock* Block; CFGBlock* Succ; CFGBlock* ContinueTargetBlock; CFGBlock* BreakTargetBlock; CFGBlock* SwitchTerminatedBlock; CFGBlock* DefaultCaseBlock; // LabelMap records the mapping from Label expressions to their blocks. typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy; LabelMapTy LabelMap; // A list of blocks that end with a "goto" that must be backpatched to // their resolved targets upon completion of CFG construction. typedef std::vector<CFGBlock*> BackpatchBlocksTy; BackpatchBlocksTy BackpatchBlocks; // A list of labels whose address has been taken (for indirect gotos). typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy; LabelSetTy AddressTakenLabels; public: explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL), ContinueTargetBlock(NULL), BreakTargetBlock(NULL), SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) { // Create an empty CFG. cfg = new CFG(); } ~CFGBuilder() { delete cfg; } // buildCFG - Used by external clients to construct the CFG. CFG* buildCFG(Stmt* Statement); // Visitors to walk an AST and construct the CFG. Called by // buildCFG. Do not call directly! CFGBlock* VisitBreakStmt(BreakStmt* B); CFGBlock* VisitCaseStmt(CaseStmt* Terminator); CFGBlock* VisitCompoundStmt(CompoundStmt* C); CFGBlock* VisitContinueStmt(ContinueStmt* C); CFGBlock* VisitDefaultStmt(DefaultStmt* D); CFGBlock* VisitDoStmt(DoStmt* D); CFGBlock* VisitForStmt(ForStmt* F); CFGBlock* VisitGotoStmt(GotoStmt* G); CFGBlock* VisitIfStmt(IfStmt* I); CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I); CFGBlock* VisitLabelStmt(LabelStmt* L); CFGBlock* VisitNullStmt(NullStmt* Statement); CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S); CFGBlock* VisitReturnStmt(ReturnStmt* R); CFGBlock* VisitStmt(Stmt* Statement); CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator); CFGBlock* VisitWhileStmt(WhileStmt* W); // FIXME: Add support for ObjC-specific control-flow structures. // NYS == Not Yet Supported CFGBlock* NYS() { badCFG = true; return Block; } CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S); CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { // FIXME: For now we pretend that @catch and the code it contains // does not exit. return Block; } // FIXME: This is not completely supported. We basically @throw like // a 'return'. CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S); CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S){ return NYS(); } // Blocks. CFGBlock* VisitBlockExpr(BlockExpr* E) { return NYS(); } CFGBlock* VisitBlockDeclRefExpr(BlockDeclRefExpr* E) { return NYS(); } private: CFGBlock* createBlock(bool add_successor = true); CFGBlock* addStmt(Stmt* Terminator); CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt); CFGBlock* WalkAST_VisitChildren(Stmt* Terminator); CFGBlock* WalkAST_VisitDeclSubExpr(Decl* D); CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator); void FinishBlock(CFGBlock* B); bool badCFG; }; // FIXME: Add support for dependent-sized array types in C++? // Does it even make sense to build a CFG for an uninstantiated template? static VariableArrayType* FindVA(Type* t) { while (ArrayType* vt = dyn_cast<ArrayType>(t)) { if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt)) if (vat->getSizeExpr()) return vat; t = vt->getElementType().getTypePtr(); } return 0; } /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can /// represent an arbitrary statement. Examples include a single expression /// or a function body (compound statement). The ownership of the returned /// CFG is transferred to the caller. If CFG construction fails, this method /// returns NULL. CFG* CFGBuilder::buildCFG(Stmt* Statement) { assert (cfg); if (!Statement) return NULL; badCFG = false; // Create an empty block that will serve as the exit block for the CFG. // Since this is the first block added to the CFG, it will be implicitly // registered as the exit block. Succ = createBlock(); assert (Succ == &cfg->getExit()); Block = NULL; // the EXIT block is empty. Create all other blocks lazily. // Visit the statements and create the CFG. CFGBlock* B = Visit(Statement); if (!B) B = Succ; if (B) { // Finalize the last constructed block. This usually involves // reversing the order of the statements in the block. if (Block) FinishBlock(B); // Backpatch the gotos whose label -> block mappings we didn't know // when we encountered them. for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), E = BackpatchBlocks.end(); I != E; ++I ) { CFGBlock* B = *I; GotoStmt* G = cast<GotoStmt>(B->getTerminator()); LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); // If there is no target for the goto, then we are looking at an // incomplete AST. Handle this by not registering a successor. if (LI == LabelMap.end()) continue; B->addSuccessor(LI->second); } // Add successors to the Indirect Goto Dispatch block (if we have one). if (CFGBlock* B = cfg->getIndirectGotoBlock()) for (LabelSetTy::iterator I = AddressTakenLabels.begin(), E = AddressTakenLabels.end(); I != E; ++I ) { // Lookup the target block. LabelMapTy::iterator LI = LabelMap.find(*I); // If there is no target block that contains label, then we are looking // at an incomplete AST. Handle this by not registering a successor. if (LI == LabelMap.end()) continue; B->addSuccessor(LI->second); } Succ = B; } // Create an empty entry block that has no predecessors. cfg->setEntry(createBlock()); if (badCFG) { delete cfg; cfg = NULL; return NULL; } // NULL out cfg so that repeated calls to the builder will fail and that // the ownership of the constructed CFG is passed to the caller. CFG* t = cfg; cfg = NULL; return t; } /// createBlock - Used to lazily create blocks that are connected /// to the current (global) succcessor. CFGBlock* CFGBuilder::createBlock(bool add_successor) { CFGBlock* B = cfg->createBlock(); if (add_successor && Succ) B->addSuccessor(Succ); return B; } /// FinishBlock - When the last statement has been added to the block, /// we must reverse the statements because they have been inserted /// in reverse order. void CFGBuilder::FinishBlock(CFGBlock* B) { assert (B); B->reverseStmts(); } /// addStmt - Used to add statements/expressions to the current CFGBlock /// "Block". This method calls WalkAST on the passed statement to see if it /// contains any short-circuit expressions. If so, it recursively creates /// the necessary blocks for such expressions. It returns the "topmost" block /// of the created blocks, or the original value of "Block" when this method /// was called if no additional blocks are created. CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) { if (!Block) Block = createBlock(); return WalkAST(Terminator,true); } /// WalkAST - Used by addStmt to walk the subtree of a statement and /// add extra blocks for ternary operators, &&, and ||. We also /// process "," and DeclStmts (which may contain nested control-flow). CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) { switch (Terminator->getStmtClass()) { case Stmt::ConditionalOperatorClass: { ConditionalOperator* C = cast<ConditionalOperator>(Terminator); // Create the confluence block that will "merge" the results // of the ternary expression. CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock(); ConfluenceBlock->appendStmt(C); FinishBlock(ConfluenceBlock); // Create a block for the LHS expression if there is an LHS expression. // A GCC extension allows LHS to be NULL, causing the condition to // be the value that is returned instead. // e.g: x ?: y is shorthand for: x ? x : y; Succ = ConfluenceBlock; Block = NULL; CFGBlock* LHSBlock = NULL; if (C->getLHS()) { LHSBlock = Visit(C->getLHS()); FinishBlock(LHSBlock); Block = NULL; } // Create the block for the RHS expression. Succ = ConfluenceBlock; CFGBlock* RHSBlock = Visit(C->getRHS()); FinishBlock(RHSBlock); // Create the block that will contain the condition. Block = createBlock(false); if (LHSBlock) Block->addSuccessor(LHSBlock); else { // If we have no LHS expression, add the ConfluenceBlock as a direct // successor for the block containing the condition. Moreover, // we need to reverse the order of the predecessors in the // ConfluenceBlock because the RHSBlock will have been added to // the succcessors already, and we want the first predecessor to the // the block containing the expression for the case when the ternary // expression evaluates to true. Block->addSuccessor(ConfluenceBlock); assert (ConfluenceBlock->pred_size() == 2); std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end()); } Block->addSuccessor(RHSBlock); Block->setTerminator(C); return addStmt(C->getCond()); } case Stmt::ChooseExprClass: { ChooseExpr* C = cast<ChooseExpr>(Terminator); CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock(); ConfluenceBlock->appendStmt(C); FinishBlock(ConfluenceBlock); Succ = ConfluenceBlock; Block = NULL; CFGBlock* LHSBlock = Visit(C->getLHS()); FinishBlock(LHSBlock); Succ = ConfluenceBlock; Block = NULL; CFGBlock* RHSBlock = Visit(C->getRHS()); FinishBlock(RHSBlock); Block = createBlock(false); Block->addSuccessor(LHSBlock); Block->addSuccessor(RHSBlock); Block->setTerminator(C); return addStmt(C->getCond()); } case Stmt::DeclStmtClass: { DeclStmt *DS = cast<DeclStmt>(Terminator); if (DS->isSingleDecl()) { Block->appendStmt(Terminator); return WalkAST_VisitDeclSubExpr(DS->getSingleDecl()); } CFGBlock* B = 0; // FIXME: Add a reverse iterator for DeclStmt to avoid this // extra copy. typedef llvm::SmallVector<Decl*,10> BufTy; BufTy Buf(DS->decl_begin(), DS->decl_end()); for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) { // Get the alignment of the new DeclStmt, padding out to >=8 bytes. unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8 ? 8 : llvm::AlignOf<DeclStmt>::Alignment; // Allocate the DeclStmt using the BumpPtrAllocator. It will // get automatically freed with the CFG. DeclGroupRef DG(*I); Decl* D = *I; void* Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); DeclStmt* DS = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); // Append the fake DeclStmt to block. Block->appendStmt(DS); B = WalkAST_VisitDeclSubExpr(D); } return B; } case Stmt::AddrLabelExprClass: { AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator); AddressTakenLabels.insert(A->getLabel()); if (AlwaysAddStmt) Block->appendStmt(Terminator); return Block; } case Stmt::StmtExprClass: return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator)); case Stmt::SizeOfAlignOfExprClass: { SizeOfAlignOfExpr* E = cast<SizeOfAlignOfExpr>(Terminator); // VLA types have expressions that must be evaluated. if (E->isArgumentType()) { for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr()); VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) addStmt(VA->getSizeExpr()); } // Expressions in sizeof/alignof are not evaluated and thus have no // control flow. else Block->appendStmt(Terminator); return Block; } case Stmt::BinaryOperatorClass: { BinaryOperator* B = cast<BinaryOperator>(Terminator); if (B->isLogicalOp()) { // && or || CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock(); ConfluenceBlock->appendStmt(B); FinishBlock(ConfluenceBlock); // create the block evaluating the LHS CFGBlock* LHSBlock = createBlock(false); LHSBlock->setTerminator(B); // create the block evaluating the RHS Succ = ConfluenceBlock; Block = NULL; CFGBlock* RHSBlock = Visit(B->getRHS()); FinishBlock(RHSBlock); // Now link the LHSBlock with RHSBlock. if (B->getOpcode() == BinaryOperator::LOr) { LHSBlock->addSuccessor(ConfluenceBlock); LHSBlock->addSuccessor(RHSBlock); } else { assert (B->getOpcode() == BinaryOperator::LAnd); LHSBlock->addSuccessor(RHSBlock); LHSBlock->addSuccessor(ConfluenceBlock); } // Generate the blocks for evaluating the LHS. Block = LHSBlock; return addStmt(B->getLHS()); } else if (B->getOpcode() == BinaryOperator::Comma) { // , Block->appendStmt(B); addStmt(B->getRHS()); return addStmt(B->getLHS()); } break; } // Blocks: No support for blocks ... yet case Stmt::BlockExprClass: case Stmt::BlockDeclRefExprClass: return NYS(); case Stmt::ParenExprClass: return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt); default: break; }; if (AlwaysAddStmt) Block->appendStmt(Terminator); return WalkAST_VisitChildren(Terminator); } /// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions /// for initializers in Decls. CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(Decl* D) { VarDecl* VD = dyn_cast<VarDecl>(D); if (!VD) return Block; Expr* Init = VD->getInit(); if (Init) { // Optimization: Don't create separate block-level statements for literals. switch (Init->getStmtClass()) { case Stmt::IntegerLiteralClass: case Stmt::CharacterLiteralClass: case Stmt::StringLiteralClass: break; default: Block = addStmt(Init); } } // If the type of VD is a VLA, then we must process its size expressions. for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) Block = addStmt(VA->getSizeExpr()); return Block; } /// WalkAST_VisitChildren - Utility method to call WalkAST on the /// children of a Stmt. CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) { CFGBlock* B = Block; for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end(); I != E; ++I) if (*I) B = WalkAST(*I); return B; } /// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement /// expressions (a GCC extension). CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) { Block->appendStmt(Terminator); return VisitCompoundStmt(Terminator->getSubStmt()); } /// VisitStmt - Handle statements with no branching control flow. CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) { // We cannot assume that we are in the middle of a basic block, since // the CFG might only be constructed for this single statement. If // we have no current basic block, just create one lazily. if (!Block) Block = createBlock(); // Simply add the statement to the current block. We actually // insert statements in reverse order; this order is reversed later // when processing the containing element in the AST. addStmt(Statement); return Block; } CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) { return Block; } CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) { CFGBlock* LastBlock = NULL; for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); I != E; ++I ) { LastBlock = Visit(*I); } return LastBlock; } CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) { // We may see an if statement in the middle of a basic block, or // it may be the first statement we are processing. In either case, // we create a new basic block. First, we create the blocks for // the then...else statements, and then we create the block containing // the if statement. If we were in the middle of a block, we // stop processing that block and reverse its statements. That block // is then the implicit successor for the "then" and "else" clauses. // The block we were proccessing is now finished. Make it the // successor block. if (Block) { Succ = Block; FinishBlock(Block); } // Process the false branch. NULL out Block so that the recursive // call to Visit will create a new basic block. // Null out Block so that all successor CFGBlock* ElseBlock = Succ; if (Stmt* Else = I->getElse()) { SaveAndRestore<CFGBlock*> sv(Succ); // NULL out Block so that the recursive call to Visit will // create a new basic block. Block = NULL; ElseBlock = Visit(Else); if (!ElseBlock) // Can occur when the Else body has all NullStmts. ElseBlock = sv.get(); else if (Block) FinishBlock(ElseBlock); } // Process the true branch. NULL out Block so that the recursive // call to Visit will create a new basic block. // Null out Block so that all successor CFGBlock* ThenBlock; { Stmt* Then = I->getThen(); assert (Then); SaveAndRestore<CFGBlock*> sv(Succ); Block = NULL; ThenBlock = Visit(Then); if (!ThenBlock) { // We can reach here if the "then" body has all NullStmts. // Create an empty block so we can distinguish between true and false // branches in path-sensitive analyses. ThenBlock = createBlock(false); ThenBlock->addSuccessor(sv.get()); } else if (Block) FinishBlock(ThenBlock); } // Now create a new block containing the if statement. Block = createBlock(false); // Set the terminator of the new block to the If statement. Block->setTerminator(I); // Now add the successors. Block->addSuccessor(ThenBlock); Block->addSuccessor(ElseBlock); // Add the condition as the last statement in the new block. This // may create new blocks as the condition may contain control-flow. Any // newly created blocks will be pointed to be "Block". return addStmt(I->getCond()->IgnoreParens()); } CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) { // If we were in the middle of a block we stop processing that block // and reverse its statements. // // NOTE: If a "return" appears in the middle of a block, this means // that the code afterwards is DEAD (unreachable). We still // keep a basic block for that code; a simple "mark-and-sweep" // from the entry block will be able to report such dead // blocks. if (Block) FinishBlock(Block); // Create the new block. Block = createBlock(false); // The Exit block is the only successor. Block->addSuccessor(&cfg->getExit()); // Add the return statement to the block. This may create new blocks // if R contains control-flow (short-circuit operations). return addStmt(R); } CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) { // Get the block of the labeled statement. Add it to our map. Visit(L->getSubStmt()); CFGBlock* LabelBlock = Block; if (!LabelBlock) // This can happen when the body is empty, i.e. LabelBlock=createBlock(); // scopes that only contains NullStmts. assert (LabelMap.find(L) == LabelMap.end() && "label already in map"); LabelMap[ L ] = LabelBlock; // Labels partition blocks, so this is the end of the basic block // we were processing (L is the block's label). Because this is // label (and we have already processed the substatement) there is no // extra control-flow to worry about. LabelBlock->setLabel(L); FinishBlock(LabelBlock); // We set Block to NULL to allow lazy creation of a new block // (if necessary); Block = NULL; // This block is now the implicit successor of other blocks. Succ = LabelBlock; return LabelBlock; } CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) { // Goto is a control-flow statement. Thus we stop processing the // current block and create a new one. if (Block) FinishBlock(Block); Block = createBlock(false); Block->setTerminator(G); // If we already know the mapping to the label block add the // successor now. LabelMapTy::iterator I = LabelMap.find(G->getLabel()); if (I == LabelMap.end()) // We will need to backpatch this block later. BackpatchBlocks.push_back(Block); else Block->addSuccessor(I->second); return Block; } CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) { // "for" is a control-flow statement. Thus we stop processing the // current block. CFGBlock* LoopSuccessor = NULL; if (Block) { FinishBlock(Block); LoopSuccessor = Block; } else LoopSuccessor = Succ; // Because of short-circuit evaluation, the condition of the loop // can span multiple basic blocks. Thus we need the "Entry" and "Exit" // blocks that evaluate the condition. CFGBlock* ExitConditionBlock = createBlock(false); CFGBlock* EntryConditionBlock = ExitConditionBlock; // Set the terminator for the "exit" condition block. ExitConditionBlock->setTerminator(F); // Now add the actual condition to the condition block. Because the // condition itself may contain control-flow, new blocks may be created. if (Stmt* C = F->getCond()) { Block = ExitConditionBlock; EntryConditionBlock = addStmt(C); if (Block) FinishBlock(EntryConditionBlock); } // The condition block is the implicit successor for the loop body as // well as any code above the loop. Succ = EntryConditionBlock; // Now create the loop body. { assert (F->getBody()); // Save the current values for Block, Succ, and continue and break targets SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ), save_continue(ContinueTargetBlock), save_break(BreakTargetBlock); // Create a new block to contain the (bottom) of the loop body. Block = NULL; if (Stmt* I = F->getInc()) { // Generate increment code in its own basic block. This is the target // of continue statements. Succ = Visit(I); // Finish up the increment block if it hasn't been already. if (Block) { assert (Block == Succ); FinishBlock(Block); Block = 0; } ContinueTargetBlock = Succ; } else { // No increment code. Continues should go the the entry condition block. ContinueTargetBlock = EntryConditionBlock; } // All breaks should go to the code following the loop. BreakTargetBlock = LoopSuccessor; // Now populate the body block, and in the process create new blocks // as we walk the body of the loop. CFGBlock* BodyBlock = Visit(F->getBody()); if (!BodyBlock) BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;" else if (Block) FinishBlock(BodyBlock); // This new body block is a successor to our "exit" condition block. ExitConditionBlock->addSuccessor(BodyBlock); } // Link up the condition block with the code that follows the loop. // (the false branch). ExitConditionBlock->addSuccessor(LoopSuccessor); // If the loop contains initialization, create a new block for those // statements. This block can also contain statements that precede // the loop. if (Stmt* I = F->getInit()) { Block = createBlock(); return addStmt(I); } else { // There is no loop initialization. We are thus basically a while // loop. NULL out Block to force lazy block construction. Block = NULL; Succ = EntryConditionBlock; return EntryConditionBlock; } } CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { // Objective-C fast enumeration 'for' statements: // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC // // for ( Type newVariable in collection_expression ) { statements } // // becomes: // // prologue: // 1. collection_expression // T. jump to loop_entry // loop_entry: // 1. side-effects of element expression // 1. ObjCForCollectionStmt [performs binding to newVariable] // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] // TB: // statements // T. jump to loop_entry // FB: // what comes after // // and // // Type existingItem; // for ( existingItem in expression ) { statements } // // becomes: // // the same with newVariable replaced with existingItem; the binding // works the same except that for one ObjCForCollectionStmt::getElement() // returns a DeclStmt and the other returns a DeclRefExpr. // CFGBlock* LoopSuccessor = 0; if (Block) { FinishBlock(Block); LoopSuccessor = Block; Block = 0; } else LoopSuccessor = Succ; // Build the condition blocks. CFGBlock* ExitConditionBlock = createBlock(false); CFGBlock* EntryConditionBlock = ExitConditionBlock; // Set the terminator for the "exit" condition block. ExitConditionBlock->setTerminator(S); // The last statement in the block should be the ObjCForCollectionStmt, // which performs the actual binding to 'element' and determines if there // are any more items in the collection. ExitConditionBlock->appendStmt(S); Block = ExitConditionBlock; // Walk the 'element' expression to see if there are any side-effects. We // generate new blocks as necesary. We DON'T add the statement by default // to the CFG unless it contains control-flow. EntryConditionBlock = WalkAST(S->getElement(), false); if (Block) { FinishBlock(EntryConditionBlock); Block = 0; } // The condition block is the implicit successor for the loop body as // well as any code above the loop. Succ = EntryConditionBlock; // Now create the true branch. { // Save the current values for Succ, continue and break targets. SaveAndRestore<CFGBlock*> save_Succ(Succ), save_continue(ContinueTargetBlock), save_break(BreakTargetBlock); BreakTargetBlock = LoopSuccessor; ContinueTargetBlock = EntryConditionBlock; CFGBlock* BodyBlock = Visit(S->getBody()); if (!BodyBlock) BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;" else if (Block) FinishBlock(BodyBlock); // This new body block is a successor to our "exit" condition block. ExitConditionBlock->addSuccessor(BodyBlock); } // Link up the condition block with the code that follows the loop. // (the false branch). ExitConditionBlock->addSuccessor(LoopSuccessor); // Now create a prologue block to contain the collection expression. Block = createBlock(); return addStmt(S->getCollection()); } CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) { return NYS(); } CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) { // "while" is a control-flow statement. Thus we stop processing the // current block. CFGBlock* LoopSuccessor = NULL; if (Block) { FinishBlock(Block); LoopSuccessor = Block; } else LoopSuccessor = Succ; // Because of short-circuit evaluation, the condition of the loop // can span multiple basic blocks. Thus we need the "Entry" and "Exit" // blocks that evaluate the condition. CFGBlock* ExitConditionBlock = createBlock(false); CFGBlock* EntryConditionBlock = ExitConditionBlock; // Set the terminator for the "exit" condition block. ExitConditionBlock->setTerminator(W); // Now add the actual condition to the condition block. Because the // condition itself may contain control-flow, new blocks may be created. // Thus we update "Succ" after adding the condition. if (Stmt* C = W->getCond()) { Block = ExitConditionBlock; EntryConditionBlock = addStmt(C); assert (Block == EntryConditionBlock); if (Block) FinishBlock(EntryConditionBlock); } // The condition block is the implicit successor for the loop body as // well as any code above the loop. Succ = EntryConditionBlock; // Process the loop body. { assert (W->getBody()); // Save the current values for Block, Succ, and continue and break targets SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ), save_continue(ContinueTargetBlock), save_break(BreakTargetBlock); // All continues within this loop should go to the condition block ContinueTargetBlock = EntryConditionBlock; // All breaks should go to the code following the loop. BreakTargetBlock = LoopSuccessor; // NULL out Block to force lazy instantiation of blocks for the body. Block = NULL; // Create the body. The returned block is the entry to the loop body. CFGBlock* BodyBlock = Visit(W->getBody()); if (!BodyBlock) BodyBlock = EntryConditionBlock; // can happen for "while(...) ;" else if (Block) FinishBlock(BodyBlock); // Add the loop body entry as a successor to the condition. ExitConditionBlock->addSuccessor(BodyBlock); } // Link up the condition block with the code that follows the loop. // (the false branch). ExitConditionBlock->addSuccessor(LoopSuccessor); // There can be no more statements in the condition block // since we loop back to this block. NULL out Block to force // lazy creation of another block. Block = NULL; // Return the condition block, which is the dominating block for the loop. Succ = EntryConditionBlock; return EntryConditionBlock; } CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { // FIXME: This isn't complete. We basically treat @throw like a return // statement. // If we were in the middle of a block we stop processing that block // and reverse its statements. if (Block) FinishBlock(Block); // Create the new block. Block = createBlock(false); // The Exit block is the only successor. Block->addSuccessor(&cfg->getExit()); // Add the statement to the block. This may create new blocks // if S contains control-flow (short-circuit operations). return addStmt(S); } CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) { // "do...while" is a control-flow statement. Thus we stop processing the // current block. CFGBlock* LoopSuccessor = NULL; if (Block) { FinishBlock(Block); LoopSuccessor = Block; } else LoopSuccessor = Succ; // Because of short-circuit evaluation, the condition of the loop // can span multiple basic blocks. Thus we need the "Entry" and "Exit" // blocks that evaluate the condition. CFGBlock* ExitConditionBlock = createBlock(false); CFGBlock* EntryConditionBlock = ExitConditionBlock; // Set the terminator for the "exit" condition block. ExitConditionBlock->setTerminator(D); // Now add the actual condition to the condition block. Because the // condition itself may contain control-flow, new blocks may be created. if (Stmt* C = D->getCond()) { Block = ExitConditionBlock; EntryConditionBlock = addStmt(C); if (Block) FinishBlock(EntryConditionBlock); } // The condition block is the implicit successor for the loop body. Succ = EntryConditionBlock; // Process the loop body. CFGBlock* BodyBlock = NULL; { assert (D->getBody()); // Save the current values for Block, Succ, and continue and break targets SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ), save_continue(ContinueTargetBlock), save_break(BreakTargetBlock); // All continues within this loop should go to the condition block ContinueTargetBlock = EntryConditionBlock; // All breaks should go to the code following the loop. BreakTargetBlock = LoopSuccessor; // NULL out Block to force lazy instantiation of blocks for the body. Block = NULL; // Create the body. The returned block is the entry to the loop body. BodyBlock = Visit(D->getBody()); if (!BodyBlock) BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" else if (Block) FinishBlock(BodyBlock); // Add the loop body entry as a successor to the condition. ExitConditionBlock->addSuccessor(BodyBlock); } // Link up the condition block with the code that follows the loop. // (the false branch). ExitConditionBlock->addSuccessor(LoopSuccessor); // There can be no more statements in the body block(s) // since we loop back to the body. NULL out Block to force // lazy creation of another block. Block = NULL; // Return the loop body, which is the dominating block for the loop. Succ = BodyBlock; return BodyBlock; } CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) { // "continue" is a control-flow statement. Thus we stop processing the // current block. if (Block) FinishBlock(Block); // Now create a new block that ends with the continue statement. Block = createBlock(false); Block->setTerminator(C); // If there is no target for the continue, then we are looking at an // incomplete AST. This means the CFG cannot be constructed. if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock); else badCFG = true; return Block; } CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) { // "break" is a control-flow statement. Thus we stop processing the // current block. if (Block) FinishBlock(Block); // Now create a new block that ends with the continue statement. Block = createBlock(false); Block->setTerminator(B); // If there is no target for the break, then we are looking at an // incomplete AST. This means that the CFG cannot be constructed. if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock); else badCFG = true; return Block; } CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) { // "switch" is a control-flow statement. Thus we stop processing the // current block. CFGBlock* SwitchSuccessor = NULL; if (Block) { FinishBlock(Block); SwitchSuccessor = Block; } else SwitchSuccessor = Succ; // Save the current "switch" context. SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), save_break(BreakTargetBlock), save_default(DefaultCaseBlock); // Set the "default" case to be the block after the switch statement. // If the switch statement contains a "default:", this value will // be overwritten with the block for that code. DefaultCaseBlock = SwitchSuccessor; // Create a new block that will contain the switch statement. SwitchTerminatedBlock = createBlock(false); // Now process the switch body. The code after the switch is the implicit // successor. Succ = SwitchSuccessor; BreakTargetBlock = SwitchSuccessor; // When visiting the body, the case statements should automatically get // linked up to the switch. We also don't keep a pointer to the body, // since all control-flow from the switch goes to case/default statements. assert (Terminator->getBody() && "switch must contain a non-NULL body"); Block = NULL; CFGBlock *BodyBlock = Visit(Terminator->getBody()); if (Block) FinishBlock(BodyBlock); // If we have no "default:" case, the default transition is to the // code following the switch body. SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock); // Add the terminator and condition in the switch block. SwitchTerminatedBlock->setTerminator(Terminator); assert (Terminator->getCond() && "switch condition must be non-NULL"); Block = SwitchTerminatedBlock; return addStmt(Terminator->getCond()); } CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) { // CaseStmts are essentially labels, so they are the // first statement in a block. if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt()); CFGBlock* CaseBlock = Block; if (!CaseBlock) CaseBlock = createBlock(); // Cases statements partition blocks, so this is the top of // the basic block we were processing (the "case XXX:" is the label). CaseBlock->setLabel(Terminator); FinishBlock(CaseBlock); // Add this block to the list of successors for the block with the // switch statement. assert (SwitchTerminatedBlock); SwitchTerminatedBlock->addSuccessor(CaseBlock); // We set Block to NULL to allow lazy creation of a new block (if necessary) Block = NULL; // This block is now the implicit successor of other blocks. Succ = CaseBlock; return CaseBlock; } CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) { if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt()); DefaultCaseBlock = Block; if (!DefaultCaseBlock) DefaultCaseBlock = createBlock(); // Default statements partition blocks, so this is the top of // the basic block we were processing (the "default:" is the label). DefaultCaseBlock->setLabel(Terminator); FinishBlock(DefaultCaseBlock); // Unlike case statements, we don't add the default block to the // successors for the switch statement immediately. This is done // when we finish processing the switch statement. This allows for // the default case (including a fall-through to the code after the // switch statement) to always be the last successor of a switch-terminated // block. // We set Block to NULL to allow lazy creation of a new block (if necessary) Block = NULL; // This block is now the implicit successor of other blocks. Succ = DefaultCaseBlock; return DefaultCaseBlock; } CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) { // Lazily create the indirect-goto dispatch block if there isn't one // already. CFGBlock* IBlock = cfg->getIndirectGotoBlock(); if (!IBlock) { IBlock = createBlock(false); cfg->setIndirectGotoBlock(IBlock); } // IndirectGoto is a control-flow statement. Thus we stop processing the // current block and create a new one. if (Block) FinishBlock(Block); Block = createBlock(false); Block->setTerminator(I); Block->addSuccessor(IBlock); return addStmt(I->getTarget()); } } // end anonymous namespace /// createBlock - Constructs and adds a new CFGBlock to the CFG. The /// block has no successors or predecessors. If this is the first block /// created in the CFG, it is automatically set to be the Entry and Exit /// of the CFG. CFGBlock* CFG::createBlock() { bool first_block = begin() == end(); // Create the block. Blocks.push_front(CFGBlock(NumBlockIDs++)); // If this is the first block, set it as the Entry and Exit. if (first_block) Entry = Exit = &front(); // Return the block. return &front(); } /// buildCFG - Constructs a CFG from an AST. Ownership of the returned /// CFG is returned to the caller. CFG* CFG::buildCFG(Stmt* Statement) { CFGBuilder Builder; return Builder.buildCFG(Statement); } /// reverseStmts - Reverses the orders of statements within a CFGBlock. void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); } //===----------------------------------------------------------------------===// // CFG: Queries for BlkExprs. //===----------------------------------------------------------------------===// namespace { typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; } static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) { if (!Terminator) return; for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) { if (!*I) continue; if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I)) if (B->isAssignmentOp()) Set.insert(B); FindSubExprAssignments(*I, Set); } } static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { BlkExprMapTy* M = new BlkExprMapTy(); // Look for assignments that are used as subexpressions. These are the // only assignments that we want to *possibly* register as a block-level // expression. Basically, if an assignment occurs both in a subexpression // and at the block-level, it is a block-level expression. llvm::SmallPtrSet<Expr*,50> SubExprAssignments; for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI) FindSubExprAssignments(*BI, SubExprAssignments); for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { // Iterate over the statements again on identify the Expr* and Stmt* at // the block-level that are block-level expressions. for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI) if (Expr* Exp = dyn_cast<Expr>(*BI)) { if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { // Assignment expressions that are not nested within another // expression are really "statements" whose value is never // used by another expression. if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) continue; } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) { // Special handling for statement expressions. The last statement // in the statement expression is also a block-level expr. const CompoundStmt* C = Terminator->getSubStmt(); if (!C->body_empty()) { unsigned x = M->size(); (*M)[C->body_back()] = x; } } unsigned x = M->size(); (*M)[Exp] = x; } // Look at terminators. The condition is a block-level expression. Stmt* S = I->getTerminatorCondition(); if (S && M->find(S) == M->end()) { unsigned x = M->size(); (*M)[S] = x; } } return M; } CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) { assert(S != NULL); if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); BlkExprMapTy::iterator I = M->find(S); if (I == M->end()) return CFG::BlkExprNumTy(); else return CFG::BlkExprNumTy(I->second); } unsigned CFG::getNumBlkExprs() { if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) return M->size(); else { // We assume callers interested in the number of BlkExprs will want // the map constructed if it doesn't already exist. BlkExprMap = (void*) PopulateBlkExprMap(*this); return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); } } //===----------------------------------------------------------------------===// // Cleanup: CFG dstor. //===----------------------------------------------------------------------===// CFG::~CFG() { delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); } //===----------------------------------------------------------------------===// // CFG pretty printing //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper { typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; StmtMapTy StmtMap; signed CurrentBlock; unsigned CurrentStmt; public: StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) { for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { unsigned j = 1; for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ; BI != BEnd; ++BI, ++j ) StmtMap[*BI] = std::make_pair(I->getBlockID(),j); } } virtual ~StmtPrinterHelper() {} void setBlockID(signed i) { CurrentBlock = i; } void setStmtID(unsigned i) { CurrentStmt = i; } virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) { StmtMapTy::iterator I = StmtMap.find(Terminator); if (I == StmtMap.end()) return false; if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock && I->second.second == CurrentStmt) return false; OS << "[B" << I->second.first << "." << I->second.second << "]"; return true; } }; class VISIBILITY_HIDDEN CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,void> { llvm::raw_ostream& OS; StmtPrinterHelper* Helper; public: CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper) : OS(os), Helper(helper) {} void VisitIfStmt(IfStmt* I) { OS << "if "; I->getCond()->printPretty(OS,Helper); } // Default case. void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); } void VisitForStmt(ForStmt* F) { OS << "for (" ; if (F->getInit()) OS << "..."; OS << "; "; if (Stmt* C = F->getCond()) C->printPretty(OS,Helper); OS << "; "; if (F->getInc()) OS << "..."; OS << ")"; } void VisitWhileStmt(WhileStmt* W) { OS << "while " ; if (Stmt* C = W->getCond()) C->printPretty(OS,Helper); } void VisitDoStmt(DoStmt* D) { OS << "do ... while "; if (Stmt* C = D->getCond()) C->printPretty(OS,Helper); } void VisitSwitchStmt(SwitchStmt* Terminator) { OS << "switch "; Terminator->getCond()->printPretty(OS,Helper); } void VisitConditionalOperator(ConditionalOperator* C) { C->getCond()->printPretty(OS,Helper); OS << " ? ... : ..."; } void VisitChooseExpr(ChooseExpr* C) { OS << "__builtin_choose_expr( "; C->getCond()->printPretty(OS,Helper); OS << " )"; } void VisitIndirectGotoStmt(IndirectGotoStmt* I) { OS << "goto *"; I->getTarget()->printPretty(OS,Helper); } void VisitBinaryOperator(BinaryOperator* B) { if (!B->isLogicalOp()) { VisitExpr(B); return; } B->getLHS()->printPretty(OS,Helper); switch (B->getOpcode()) { case BinaryOperator::LOr: OS << " || ..."; return; case BinaryOperator::LAnd: OS << " && ..."; return; default: assert(false && "Invalid logical operator."); } } void VisitExpr(Expr* E) { E->printPretty(OS,Helper); } }; void print_stmt(llvm::raw_ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) { if (Helper) { // special printing for statement-expressions. if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) { CompoundStmt* Sub = SE->getSubStmt(); if (Sub->child_begin() != Sub->child_end()) { OS << "({ ... ; "; Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); OS << " })\n"; return; } } // special printing for comma expressions. if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) { if (B->getOpcode() == BinaryOperator::Comma) { OS << "... , "; Helper->handledStmt(B->getRHS(),OS); OS << '\n'; return; } } } Terminator->printPretty(OS, Helper); // Expressions need a newline. if (isa<Expr>(Terminator)) OS << '\n'; } void print_block(llvm::raw_ostream& OS, const CFG* cfg, const CFGBlock& B, StmtPrinterHelper* Helper, bool print_edges) { if (Helper) Helper->setBlockID(B.getBlockID()); // Print the header. OS << "\n [ B" << B.getBlockID(); if (&B == &cfg->getEntry()) OS << " (ENTRY) ]\n"; else if (&B == &cfg->getExit()) OS << " (EXIT) ]\n"; else if (&B == cfg->getIndirectGotoBlock()) OS << " (INDIRECT GOTO DISPATCH) ]\n"; else OS << " ]\n"; // Print the label of this block. if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) { if (print_edges) OS << " "; if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator)) OS << L->getName(); else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) { OS << "case "; C->getLHS()->printPretty(OS); if (C->getRHS()) { OS << " ... "; C->getRHS()->printPretty(OS); } } else if (isa<DefaultStmt>(Terminator)) OS << "default"; else assert(false && "Invalid label statement in CFGBlock."); OS << ":\n"; } // Iterate through the statements in the block and print them. unsigned j = 1; for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; I != E ; ++I, ++j ) { // Print the statement # in the basic block and the statement itself. if (print_edges) OS << " "; OS << llvm::format("%3d", j) << ": "; if (Helper) Helper->setStmtID(j); print_stmt(OS,Helper,*I); } // Print the terminator of this block. if (B.getTerminator()) { if (print_edges) OS << " "; OS << " T: "; if (Helper) Helper->setBlockID(-1); CFGBlockTerminatorPrint TPrinter(OS,Helper); TPrinter.Visit(const_cast<Stmt*>(B.getTerminator())); OS << '\n'; } if (print_edges) { // Print the predecessors of this block. OS << " Predecessors (" << B.pred_size() << "):"; unsigned i = 0; for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); I != E; ++I, ++i) { if (i == 8 || (i-8) == 0) OS << "\n "; OS << " B" << (*I)->getBlockID(); } OS << '\n'; // Print the successors of this block. OS << " Successors (" << B.succ_size() << "):"; i = 0; for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); I != E; ++I, ++i) { if (i == 8 || (i-8) % 10 == 0) OS << "\n "; OS << " B" << (*I)->getBlockID(); } OS << '\n'; } } } // end anonymous namespace /// dump - A simple pretty printer of a CFG that outputs to stderr. void CFG::dump() const { print(llvm::errs()); } /// print - A simple pretty printer of a CFG that outputs to an ostream. void CFG::print(llvm::raw_ostream& OS) const { StmtPrinterHelper Helper(this); // Print the entry block. print_block(OS, this, getEntry(), &Helper, true); // Iterate through the CFGBlocks and print them one by one. for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { // Skip the entry block, because we already printed it. if (&(*I) == &getEntry() || &(*I) == &getExit()) continue; print_block(OS, this, *I, &Helper, true); } // Print the exit block. print_block(OS, this, getExit(), &Helper, true); OS.flush(); } /// dump - A simply pretty printer of a CFGBlock that outputs to stderr. void CFGBlock::dump(const CFG* cfg) const { print(llvm::errs(), cfg); } /// print - A simple pretty printer of a CFGBlock that outputs to an ostream. /// Generally this will only be called from CFG::print. void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg) const { StmtPrinterHelper Helper(cfg); print_block(OS, cfg, *this, &Helper, true); } /// printTerminator - A simple pretty printer of the terminator of a CFGBlock. void CFGBlock::printTerminator(llvm::raw_ostream& OS) const { CFGBlockTerminatorPrint TPrinter(OS,NULL); TPrinter.Visit(const_cast<Stmt*>(getTerminator())); } Stmt* CFGBlock::getTerminatorCondition() { if (!Terminator) return NULL; Expr* E = NULL; switch (Terminator->getStmtClass()) { default: break; case Stmt::ForStmtClass: E = cast<ForStmt>(Terminator)->getCond(); break; case Stmt::WhileStmtClass: E = cast<WhileStmt>(Terminator)->getCond(); break; case Stmt::DoStmtClass: E = cast<DoStmt>(Terminator)->getCond(); break; case Stmt::IfStmtClass: E = cast<IfStmt>(Terminator)->getCond(); break; case Stmt::ChooseExprClass: E = cast<ChooseExpr>(Terminator)->getCond(); break; case Stmt::IndirectGotoStmtClass: E = cast<IndirectGotoStmt>(Terminator)->getTarget(); break; case Stmt::SwitchStmtClass: E = cast<SwitchStmt>(Terminator)->getCond(); break; case Stmt::ConditionalOperatorClass: E = cast<ConditionalOperator>(Terminator)->getCond(); break; case Stmt::BinaryOperatorClass: // '&&' and '||' E = cast<BinaryOperator>(Terminator)->getLHS(); break; case Stmt::ObjCForCollectionStmtClass: return Terminator; } return E ? E->IgnoreParens() : NULL; } bool CFGBlock::hasBinaryBranchTerminator() const { if (!Terminator) return false; Expr* E = NULL; switch (Terminator->getStmtClass()) { default: return false; case Stmt::ForStmtClass: case Stmt::WhileStmtClass: case Stmt::DoStmtClass: case Stmt::IfStmtClass: case Stmt::ChooseExprClass: case Stmt::ConditionalOperatorClass: case Stmt::BinaryOperatorClass: return true; } return E ? E->IgnoreParens() : NULL; } //===----------------------------------------------------------------------===// // CFG Graphviz Visualization //===----------------------------------------------------------------------===// #ifndef NDEBUG static StmtPrinterHelper* GraphHelper; #endif void CFG::viewCFG() const { #ifndef NDEBUG StmtPrinterHelper H(this); GraphHelper = &H; llvm::ViewGraph(this,"CFG"); GraphHelper = NULL; #endif } namespace llvm { template<> struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) { #ifndef NDEBUG std::string OutSStr; llvm::raw_string_ostream Out(OutSStr); print_block(Out,Graph, *Node, GraphHelper, false); std::string& OutStr = Out.str(); if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); // Process string output to make it nicer... for (unsigned i = 0; i != OutStr.length(); ++i) if (OutStr[i] == '\n') { // Left justify OutStr[i] = '\\'; OutStr.insert(OutStr.begin()+i+1, 'l'); } return OutStr; #else return ""; #endif } }; } // end namespace llvm <file_sep>/test/CodeGen/incomplete-function-type.c // RUN: clang-cc -emit-llvm %s -o - | not grep opaque enum teste1 test1f(void), (*test1)(void) = test1f; struct tests2 test2f(), (*test2)() = test2f; struct tests3; void test3f(struct tests3), (*test3)(struct tests3) = test3f; enum teste1 { TEST1 }; struct tests2 { int x,y,z,a,b,c,d,e,f,g; }; struct tests3 { float x; }; <file_sep>/test/CodeGenCXX/expr.cpp // RUN: clang-cc -emit-llvm -x c++ < %s void f(int x) { if (x != 0) return; } <file_sep>/test/Analysis/region-only-test.c // RUN: clang-cc -analyze -checker-simple -analyzer-store=region -verify %s // Region store must be enabled for tests in this file. // Exercise creating ElementRegion with symbolic super region. void foo(int* p) { int *x; int a; if (p[0] == 1) x = &a; if (p[0] == 1) *x; // no-warning } <file_sep>/test/CodeGen/conditional.c // RUN: clang-cc -emit-llvm %s -o %t float test1(int cond, float a, float b) { return cond ? a : b; } double test2(int cond, float a, double b) { return cond ? a : b; } void f(); void test3(){ 1 ? f() : (void)0; } void test4() { int i; short j; float* k = 1 ? &i : &j; } void test5() { const int* cip; void* vp; cip = 0 ? vp : cip; } void test6(); void test7(int); void* test8() {return 1 ? test6 : test7;} void _efree(void *ptr); void _php_stream_free3() { (1 ? free(0) : _efree(0)); } void _php_stream_free4() { 1 ? _efree(0) : free(0); } <file_sep>/include/clang/Basic/Makefile LEVEL = ../../../../.. BUILT_SOURCES = DiagnosticAnalysisKinds.inc DiagnosticASTKinds.inc \ DiagnosticCommonKinds.inc DiagnosticDriverKinds.inc \ DiagnosticFrontendKinds.inc DiagnosticLexKinds.inc \ DiagnosticParseKinds.inc DiagnosticSemaKinds.inc \ DiagnosticGroups.inc TABLEGEN_INC_FILES_COMMON = 1 include $(LEVEL)/Makefile.common $(ObjDir)/Diagnostic%Kinds.inc.tmp : Diagnostic.td DiagnosticGroups.td Diagnostic%Kinds.td $(TBLGEN) $(Echo) "Building Clang $(patsubst Diagnostic%Kinds.inc.tmp,%,$(@F)) diagnostic tables with tblgen" $(Verb) -$(MKDIR) $(@D) $(Verb) $(TableGen) -gen-clang-diags-defs -clang-component=$(patsubst Diagnostic%Kinds.inc.tmp,%,$(@F)) -o $(call SYSPATH, $@) $< $(ObjDir)/DiagnosticGroups.inc.tmp : Diagnostic.td $(wildcard Diagnostic*.td) $(TBLGEN) $(Echo) "Building Clang diagnostic groups with tblgen" $(Verb) -$(MKDIR) $(@D) $(Verb) $(TableGen) -gen-clang-diag-groups -o $(call SYSPATH, $@) $< <file_sep>/tools/ccc/test/ccc/darwin-ld-shared.c // -shared translates to -dynamiclib on darwin. // RUN: xcc -ccc-host-system darwin -### -filelist a &> %t.1 && // RUN: xcc -ccc-host-system darwin -### -filelist a -shared &> %t.2 && // -dynamiclib turns on -dylib // RUN: not grep -- '-dylib' %t.1 && // RUN: grep -- '-dylib' %t.2 <file_sep>/test/SemaCXX/i-c-e-cxx.cpp // RUN: clang-cc -fsyntax-only -verify %s // C++-specific tests for integral constant expressions. const int c = 10; int ar[c]; <file_sep>/include/clang/Analysis/PathSensitive/GRExprEngineBuilders.h //===-- GRExprEngineBuilders.h - "Builder" classes for GRExprEngine -*- C++ -*-= // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines smart builder "references" which are used to marshal // builders between GRExprEngine objects and their related components. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_GREXPRENGINE_BUILDERS #define LLVM_CLANG_ANALYSIS_GREXPRENGINE_BUILDERS #include "clang/Analysis/PathSensitive/GRExprEngine.h" namespace clang { // SaveAndRestore - A utility class that uses RAII to save and restore // the value of a variable. template<typename T> struct SaveAndRestore { SaveAndRestore(T& x) : X(x), old_value(x) {} ~SaveAndRestore() { X = old_value; } T get() { return old_value; } private: T& X; T old_value; }; // SaveOr - Similar to SaveAndRestore. Operates only on bools; the old // value of a variable is saved, and during the dstor the old value is // or'ed with the new value. struct SaveOr { SaveOr(bool& x) : X(x), old_value(x) { x = false; } ~SaveOr() { X |= old_value; } private: bool& X; const bool old_value; }; class GRStmtNodeBuilderRef { GRExprEngine::NodeSet &Dst; GRExprEngine::StmtNodeBuilder &B; GRExprEngine& Eng; GRExprEngine::NodeTy* Pred; const GRState* state; const Stmt* stmt; const unsigned OldSize; const bool AutoCreateNode; SaveAndRestore<bool> OldSink; SaveAndRestore<const void*> OldTag; SaveOr OldHasGen; private: friend class GRExprEngine; GRStmtNodeBuilderRef(); // do not implement void operator=(const GRStmtNodeBuilderRef&); // do not implement GRStmtNodeBuilderRef(GRExprEngine::NodeSet &dst, GRExprEngine::StmtNodeBuilder &builder, GRExprEngine& eng, GRExprEngine::NodeTy* pred, const GRState *st, const Stmt* s, bool auto_create_node) : Dst(dst), B(builder), Eng(eng), Pred(pred), state(st), stmt(s), OldSize(Dst.size()), AutoCreateNode(auto_create_node), OldSink(B.BuildSinks), OldTag(B.Tag), OldHasGen(B.HasGeneratedNode) {} public: ~GRStmtNodeBuilderRef() { // Handle the case where no nodes where generated. Auto-generate that // contains the updated state if we aren't generating sinks. if (!B.BuildSinks && Dst.size() == OldSize && !B.HasGeneratedNode) { if (AutoCreateNode) B.MakeNode(Dst, const_cast<Stmt*>(stmt), Pred, state); else Dst.Add(Pred); } } GRStateRef getState() { return GRStateRef(state, Eng.getStateManager()); } GRStateManager& getStateManager() { return Eng.getStateManager(); } GRExprEngine::NodeTy* MakeNode(const GRState* state) { return B.MakeNode(Dst, const_cast<Stmt*>(stmt), Pred, state); } }; } // end clang namespace #endif <file_sep>/test/Lexer/rdr-6096838.c /* RUN: clang-cc -fsyntax-only -verify %s && * RUN: clang-cc -std=gnu89 -fsyntax-only -verify %s rdar://6096838 */ long double d = 0x0.0000003ffffffff00000p-16357L; <file_sep>/lib/Analysis/SimpleConstraintManager.cpp //== SimpleConstraintManager.cpp --------------------------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines SimpleConstraintManager, a class that holds code shared // between BasicConstraintManager and RangeConstraintManager. // //===----------------------------------------------------------------------===// #include "SimpleConstraintManager.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" #include "clang/Analysis/PathSensitive/GRState.h" namespace clang { SimpleConstraintManager::~SimpleConstraintManager() {} bool SimpleConstraintManager::canReasonAbout(SVal X) const { if (nonloc::SymExprVal *SymVal = dyn_cast<nonloc::SymExprVal>(&X)) { const SymExpr *SE = SymVal->getSymbolicExpression(); if (isa<SymbolData>(SE)) return true; if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) { switch (SIE->getOpcode()) { // We don't reason yet about bitwise-constraints on symbolic values. case BinaryOperator::And: case BinaryOperator::Or: case BinaryOperator::Xor: return false; // We don't reason yet about arithmetic constraints on symbolic values. case BinaryOperator::Mul: case BinaryOperator::Div: case BinaryOperator::Rem: case BinaryOperator::Add: case BinaryOperator::Sub: case BinaryOperator::Shl: case BinaryOperator::Shr: return false; // All other cases. default: return true; } } return false; } return true; } const GRState* SimpleConstraintManager::Assume(const GRState* St, SVal Cond, bool Assumption, bool& isFeasible) { if (Cond.isUnknown()) { isFeasible = true; return St; } if (isa<NonLoc>(Cond)) return Assume(St, cast<NonLoc>(Cond), Assumption, isFeasible); else return Assume(St, cast<Loc>(Cond), Assumption, isFeasible); } const GRState* SimpleConstraintManager::Assume(const GRState* St, Loc Cond, bool Assumption, bool& isFeasible) { St = AssumeAux(St, Cond, Assumption, isFeasible); if (!isFeasible) return St; // EvalAssume is used to call into the GRTransferFunction object to perform // any checker-specific update of the state based on this assumption being // true or false. return StateMgr.getTransferFuncs().EvalAssume(StateMgr, St, Cond, Assumption, isFeasible); } const GRState* SimpleConstraintManager::AssumeAux(const GRState* St, Loc Cond, bool Assumption, bool& isFeasible) { BasicValueFactory& BasicVals = StateMgr.getBasicVals(); switch (Cond.getSubKind()) { default: assert (false && "'Assume' not implemented for this Loc."); return St; case loc::MemRegionKind: { // FIXME: Should this go into the storemanager? const MemRegion* R = cast<loc::MemRegionVal>(Cond).getRegion(); const SubRegion* SubR = dyn_cast<SubRegion>(R); while (SubR) { // FIXME: now we only find the first symbolic region. if (const SymbolicRegion* SymR = dyn_cast<SymbolicRegion>(SubR)) { if (Assumption) return AssumeSymNE(St, SymR->getSymbol(), BasicVals.getZeroWithPtrWidth(), isFeasible); else return AssumeSymEQ(St, SymR->getSymbol(), BasicVals.getZeroWithPtrWidth(), isFeasible); } SubR = dyn_cast<SubRegion>(SubR->getSuperRegion()); } // FALL-THROUGH. } case loc::FuncValKind: case loc::GotoLabelKind: isFeasible = Assumption; return St; case loc::ConcreteIntKind: { bool b = cast<loc::ConcreteInt>(Cond).getValue() != 0; isFeasible = b ? Assumption : !Assumption; return St; } } // end switch } const GRState* SimpleConstraintManager::Assume(const GRState* St, NonLoc Cond, bool Assumption, bool& isFeasible) { St = AssumeAux(St, Cond, Assumption, isFeasible); if (!isFeasible) return St; // EvalAssume is used to call into the GRTransferFunction object to perform // any checker-specific update of the state based on this assumption being // true or false. return StateMgr.getTransferFuncs().EvalAssume(StateMgr, St, Cond, Assumption, isFeasible); } const GRState* SimpleConstraintManager::AssumeAux(const GRState* St,NonLoc Cond, bool Assumption, bool& isFeasible) { // We cannot reason about SymIntExpr and SymSymExpr. if (!canReasonAbout(Cond)) { isFeasible = true; return St; } BasicValueFactory& BasicVals = StateMgr.getBasicVals(); SymbolManager& SymMgr = StateMgr.getSymbolManager(); switch (Cond.getSubKind()) { default: assert(false && "'Assume' not implemented for this NonLoc"); case nonloc::SymbolValKind: { nonloc::SymbolVal& SV = cast<nonloc::SymbolVal>(Cond); SymbolRef sym = SV.getSymbol(); QualType T = SymMgr.getType(sym); if (Assumption) return AssumeSymNE(St, sym, BasicVals.getValue(0, T), isFeasible); else return AssumeSymEQ(St, sym, BasicVals.getValue(0, T), isFeasible); } case nonloc::SymExprValKind: { nonloc::SymExprVal V = cast<nonloc::SymExprVal>(Cond); if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(V.getSymbolicExpression())) return AssumeSymInt(St, Assumption, SE, isFeasible); isFeasible = true; return St; } case nonloc::ConcreteIntKind: { bool b = cast<nonloc::ConcreteInt>(Cond).getValue() != 0; isFeasible = b ? Assumption : !Assumption; return St; } case nonloc::LocAsIntegerKind: return AssumeAux(St, cast<nonloc::LocAsInteger>(Cond).getLoc(), Assumption, isFeasible); } // end switch } const GRState* SimpleConstraintManager::AssumeSymInt(const GRState* St, bool Assumption, const SymIntExpr *SE, bool& isFeasible) { // Here we assume that LHS is a symbol. This is consistent with the // rest of the constraint manager logic. SymbolRef Sym = cast<SymbolData>(SE->getLHS()); const llvm::APSInt &Int = SE->getRHS(); switch (SE->getOpcode()) { default: // No logic yet for other operators. isFeasible = true; return St; case BinaryOperator::EQ: return Assumption ? AssumeSymEQ(St, Sym, Int, isFeasible) : AssumeSymNE(St, Sym, Int, isFeasible); case BinaryOperator::NE: return Assumption ? AssumeSymNE(St, Sym, Int, isFeasible) : AssumeSymEQ(St, Sym, Int, isFeasible); case BinaryOperator::GT: return Assumption ? AssumeSymGT(St, Sym, Int, isFeasible) : AssumeSymLE(St, Sym, Int, isFeasible); case BinaryOperator::GE: return Assumption ? AssumeSymGE(St, Sym, Int, isFeasible) : AssumeSymLT(St, Sym, Int, isFeasible); case BinaryOperator::LT: return Assumption ? AssumeSymLT(St, Sym, Int, isFeasible) : AssumeSymGE(St, Sym, Int, isFeasible); case BinaryOperator::LE: return Assumption ? AssumeSymLE(St, Sym, Int, isFeasible) : AssumeSymGT(St, Sym, Int, isFeasible); } // end switch } const GRState* SimpleConstraintManager::AssumeInBound(const GRState* St, SVal Idx, SVal UpperBound, bool Assumption, bool& isFeasible) { // Only support ConcreteInt for now. if (!(isa<nonloc::ConcreteInt>(Idx) && isa<nonloc::ConcreteInt>(UpperBound))){ isFeasible = true; return St; } const llvm::APSInt& Zero = getBasicVals().getZeroWithPtrWidth(false); llvm::APSInt IdxV = cast<nonloc::ConcreteInt>(Idx).getValue(); // IdxV might be too narrow. if (IdxV.getBitWidth() < Zero.getBitWidth()) IdxV.extend(Zero.getBitWidth()); // UBV might be too narrow, too. llvm::APSInt UBV = cast<nonloc::ConcreteInt>(UpperBound).getValue(); if (UBV.getBitWidth() < Zero.getBitWidth()) UBV.extend(Zero.getBitWidth()); bool InBound = (Zero <= IdxV) && (IdxV < UBV); isFeasible = Assumption ? InBound : !InBound; return St; } } // end of namespace clang <file_sep>/lib/Analysis/CMakeLists.txt set(LLVM_NO_RTTI 1) add_clang_library(clangAnalysis BasicConstraintManager.cpp BasicObjCFoundationChecks.cpp BasicStore.cpp BasicValueFactory.cpp BugReporter.cpp CFRefCount.cpp CheckDeadStores.cpp CheckNSError.cpp CheckObjCDealloc.cpp CheckObjCInstMethSignature.cpp CheckObjCUnusedIVars.cpp Environment.cpp ExplodedGraph.cpp GRBlockCounter.cpp GRCoreEngine.cpp GRExprEngine.cpp GRExprEngineInternalChecks.cpp GRSimpleVals.cpp GRState.cpp GRTransferFuncs.cpp LiveVariables.cpp MemRegion.cpp PathDiagnostic.cpp RangeConstraintManager.cpp RegionStore.cpp SimpleConstraintManager.cpp SVals.cpp SymbolManager.cpp UninitializedValues.cpp ) add_dependencies(clangAnalysis ClangDiagnosticAnalysis) <file_sep>/tools/ccc/ccc #!/usr/bin/env python import os import sys from ccclib import Arguments from ccclib import Driver def main(): progDir = os.path.dirname(sys.argv[0]) progName = os.path.basename(sys.argv[0]) d = Driver.Driver(progName, progDir) try: d.run(sys.argv[1:]) except Arguments.InvalidArgumentsError,e: print >>sys.stderr, "%s: %s" % (progName, e.args[0]) sys.exit(1) except Arguments.MissingArgumentError,e: print >>sys.stderr, "%s: argument to '%s' missing" % (progName, e.args[0].name) sys.exit(1) except NotImplementedError,e: print >>sys.stderr, "%s: not implemented: %s" % (progName, e.args[0]) if __name__=='__main__': main() <file_sep>/test/SemaTemplate/instantiate-static-var.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T, T Divisor> class X { public: static const T value = 10 / Divisor; // expected-error{{in-class initializer is not an integral constant expression}} }; int array1[X<int, 2>::value == 5? 1 : -1]; X<int, 0> xi0; // expected-note{{in instantiation of template class 'class X<int, 0>' requested here}} template<typename T> class Y { static const T value = 0; // expected-error{{'value' can only be initialized if it is a static const integral data member}} }; Y<float> fy; // expected-note{{in instantiation of template class 'class Y<float>' requested here}} <file_sep>/lib/AST/TypeSerialization.cpp //===--- TypeSerialization.cpp - Serialization of Decls ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines methods that implement bitcode serialization for Types. // //===----------------------------------------------------------------------===// #include "clang/AST/Type.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ASTContext.h" #include "llvm/Bitcode/Serialize.h" #include "llvm/Bitcode/Deserialize.h" using namespace clang; using llvm::Serializer; using llvm::Deserializer; using llvm::SerializedPtrID; void QualType::Emit(Serializer& S) const { S.EmitPtr(getTypePtr()); S.EmitInt(getCVRQualifiers()); } QualType QualType::ReadVal(Deserializer& D) { uintptr_t Val; D.ReadUIntPtr(Val, false); return QualType(reinterpret_cast<Type*>(Val), D.ReadInt()); } void QualType::ReadBackpatch(Deserializer& D) { uintptr_t Val; D.ReadUIntPtr(Val, false); Value.setPointer(reinterpret_cast<Type*>(Val)); Value.setInt(D.ReadInt()); } //===----------------------------------------------------------------------===// // Type Serialization: Dispatch code to handle specific types. //===----------------------------------------------------------------------===// void Type::Emit(Serializer& S) const { S.EmitInt(getTypeClass()); S.EmitPtr(this); if (!isa<BuiltinType>(this)) EmitImpl(S); } void Type::Create(ASTContext& Context, unsigned i, Deserializer& D) { Type::TypeClass K = static_cast<Type::TypeClass>(D.ReadInt()); SerializedPtrID PtrID = D.ReadPtrID(); switch (K) { default: assert (false && "Deserialization for type not supported."); break; case Type::Builtin: assert (i < Context.getTypes().size()); assert (isa<BuiltinType>(Context.getTypes()[i])); D.RegisterPtr(PtrID,Context.getTypes()[i]); break; case Type::ExtQual: D.RegisterPtr(PtrID,ExtQualType::CreateImpl(Context,D)); break; case Type::Complex: D.RegisterPtr(PtrID,ComplexType::CreateImpl(Context,D)); break; case Type::ConstantArray: D.RegisterPtr(PtrID,ConstantArrayType::CreateImpl(Context,D)); break; case Type::FunctionNoProto: D.RegisterPtr(PtrID,FunctionNoProtoType::CreateImpl(Context,D)); break; case Type::FunctionProto: D.RegisterPtr(PtrID,FunctionProtoType::CreateImpl(Context,D)); break; case Type::IncompleteArray: D.RegisterPtr(PtrID,IncompleteArrayType::CreateImpl(Context,D)); break; case Type::MemberPointer: D.RegisterPtr(PtrID, MemberPointerType::CreateImpl(Context, D)); break; case Type::Pointer: D.RegisterPtr(PtrID, PointerType::CreateImpl(Context, D)); break; case Type::BlockPointer: D.RegisterPtr(PtrID, BlockPointerType::CreateImpl(Context, D)); break; case Type::LValueReference: D.RegisterPtr(PtrID, LValueReferenceType::CreateImpl(Context, D)); break; case Type::RValueReference: D.RegisterPtr(PtrID, RValueReferenceType::CreateImpl(Context, D)); break; case Type::Record: case Type::Enum: // FIXME: Implement this! assert(false && "Can't deserialize tag types!"); break; case Type::Typedef: D.RegisterPtr(PtrID, TypedefType::CreateImpl(Context, D)); break; case Type::TypeOfExpr: D.RegisterPtr(PtrID, TypeOfExprType::CreateImpl(Context, D)); break; case Type::TypeOf: D.RegisterPtr(PtrID, TypeOfType::CreateImpl(Context, D)); break; case Type::TemplateTypeParm: D.RegisterPtr(PtrID, TemplateTypeParmType::CreateImpl(Context, D)); break; case Type::VariableArray: D.RegisterPtr(PtrID, VariableArrayType::CreateImpl(Context, D)); break; } } //===----------------------------------------------------------------------===// // ExtQualType //===----------------------------------------------------------------------===// void ExtQualType::EmitImpl(Serializer& S) const { S.EmitPtr(getBaseType()); S.EmitInt(getAddressSpace()); } Type* ExtQualType::CreateImpl(ASTContext& Context, Deserializer& D) { QualType BaseTy = QualType::ReadVal(D); unsigned AddressSpace = D.ReadInt(); return Context.getAddrSpaceQualType(BaseTy, AddressSpace).getTypePtr(); } //===----------------------------------------------------------------------===// // BlockPointerType //===----------------------------------------------------------------------===// void BlockPointerType::EmitImpl(Serializer& S) const { S.Emit(getPointeeType()); } Type* BlockPointerType::CreateImpl(ASTContext& Context, Deserializer& D) { return Context.getBlockPointerType(QualType::ReadVal(D)).getTypePtr(); } //===----------------------------------------------------------------------===// // ComplexType //===----------------------------------------------------------------------===// void ComplexType::EmitImpl(Serializer& S) const { S.Emit(getElementType()); } Type* ComplexType::CreateImpl(ASTContext& Context, Deserializer& D) { return Context.getComplexType(QualType::ReadVal(D)).getTypePtr(); } //===----------------------------------------------------------------------===// // ConstantArray //===----------------------------------------------------------------------===// void ConstantArrayType::EmitImpl(Serializer& S) const { S.Emit(getElementType()); S.EmitInt(getSizeModifier()); S.EmitInt(getIndexTypeQualifier()); S.Emit(Size); } Type* ConstantArrayType::CreateImpl(ASTContext& Context, Deserializer& D) { QualType ElTy = QualType::ReadVal(D); ArraySizeModifier am = static_cast<ArraySizeModifier>(D.ReadInt()); unsigned ITQ = D.ReadInt(); llvm::APInt Size; D.Read(Size); return Context.getConstantArrayType(ElTy,Size,am,ITQ).getTypePtr(); } //===----------------------------------------------------------------------===// // FunctionNoProtoType //===----------------------------------------------------------------------===// void FunctionNoProtoType::EmitImpl(Serializer& S) const { S.Emit(getResultType()); } Type* FunctionNoProtoType::CreateImpl(ASTContext& Context, Deserializer& D) { return Context.getFunctionNoProtoType(QualType::ReadVal(D)).getTypePtr(); } //===----------------------------------------------------------------------===// // FunctionProtoType //===----------------------------------------------------------------------===// void FunctionProtoType::EmitImpl(Serializer& S) const { S.Emit(getResultType()); S.EmitBool(isVariadic()); S.EmitInt(getTypeQuals()); S.EmitInt(getNumArgs()); for (arg_type_iterator I=arg_type_begin(), E=arg_type_end(); I!=E; ++I) S.Emit(*I); } Type* FunctionProtoType::CreateImpl(ASTContext& Context, Deserializer& D) { QualType ResultType = QualType::ReadVal(D); bool isVariadic = D.ReadBool(); unsigned TypeQuals = D.ReadInt(); unsigned NumArgs = D.ReadInt(); llvm::SmallVector<QualType,15> Args; for (unsigned j = 0; j < NumArgs; ++j) Args.push_back(QualType::ReadVal(D)); return Context.getFunctionType(ResultType,&*Args.begin(), NumArgs,isVariadic,TypeQuals).getTypePtr(); } //===----------------------------------------------------------------------===// // PointerType //===----------------------------------------------------------------------===// void PointerType::EmitImpl(Serializer& S) const { S.Emit(getPointeeType()); } Type* PointerType::CreateImpl(ASTContext& Context, Deserializer& D) { return Context.getPointerType(QualType::ReadVal(D)).getTypePtr(); } //===----------------------------------------------------------------------===// // ReferenceType //===----------------------------------------------------------------------===// void ReferenceType::EmitImpl(Serializer& S) const { S.Emit(getPointeeType()); } Type* LValueReferenceType::CreateImpl(ASTContext& Context, Deserializer& D) { return Context.getLValueReferenceType(QualType::ReadVal(D)).getTypePtr(); } Type* RValueReferenceType::CreateImpl(ASTContext& Context, Deserializer& D) { return Context.getRValueReferenceType(QualType::ReadVal(D)).getTypePtr(); } //===----------------------------------------------------------------------===// // MemberPointerType //===----------------------------------------------------------------------===// void MemberPointerType::EmitImpl(Serializer& S) const { S.Emit(getPointeeType()); S.Emit(QualType(Class, 0)); } Type* MemberPointerType::CreateImpl(ASTContext& Context, Deserializer& D) { QualType Pointee = QualType::ReadVal(D); QualType Class = QualType::ReadVal(D); return Context.getMemberPointerType(Pointee, Class.getTypePtr()).getTypePtr(); } //===----------------------------------------------------------------------===// // TagType //===----------------------------------------------------------------------===// void TagType::EmitImpl(Serializer& S) const { S.EmitOwnedPtr(getDecl()); } Type* TagType::CreateImpl(ASTContext& Context, Deserializer& D) { std::vector<Type*>& Types = const_cast<std::vector<Type*>&>(Context.getTypes()); // FIXME: This is wrong: we need the subclasses to do the // (de-)serialization. TagType* T = new TagType(Record, NULL,QualType()); Types.push_back(T); // Deserialize the decl. T->decl.setPointer(cast<TagDecl>(D.ReadOwnedPtr<Decl>(Context))); T->decl.setInt(0); return T; } //===----------------------------------------------------------------------===// // TypedefType //===----------------------------------------------------------------------===// void TypedefType::EmitImpl(Serializer& S) const { S.Emit(getCanonicalTypeInternal()); S.EmitPtr(Decl); } Type* TypedefType::CreateImpl(ASTContext& Context, Deserializer& D) { std::vector<Type*>& Types = const_cast<std::vector<Type*>&>(Context.getTypes()); TypedefType* T = new TypedefType(Type::Typedef, NULL, QualType::ReadVal(D)); Types.push_back(T); D.ReadPtr(T->Decl); // May be backpatched. return T; } //===----------------------------------------------------------------------===// // TypeOfExprType //===----------------------------------------------------------------------===// void TypeOfExprType::EmitImpl(llvm::Serializer& S) const { S.EmitOwnedPtr(TOExpr); } Type* TypeOfExprType::CreateImpl(ASTContext& Context, Deserializer& D) { Expr* E = D.ReadOwnedPtr<Expr>(Context); std::vector<Type*>& Types = const_cast<std::vector<Type*>&>(Context.getTypes()); TypeOfExprType* T = new TypeOfExprType(E, Context.getCanonicalType(E->getType())); Types.push_back(T); return T; } //===----------------------------------------------------------------------===// // TypeOfType //===----------------------------------------------------------------------===// void TypeOfType::EmitImpl(llvm::Serializer& S) const { S.Emit(TOType); } Type* TypeOfType::CreateImpl(ASTContext& Context, Deserializer& D) { QualType TOType = QualType::ReadVal(D); std::vector<Type*>& Types = const_cast<std::vector<Type*>&>(Context.getTypes()); TypeOfType* T = new TypeOfType(TOType, Context.getCanonicalType(TOType)); Types.push_back(T); return T; } //===----------------------------------------------------------------------===// // TemplateTypeParmType //===----------------------------------------------------------------------===// void TemplateTypeParmType::EmitImpl(Serializer& S) const { S.EmitInt(Depth); S.EmitInt(Index); S.EmitPtr(Name); } Type* TemplateTypeParmType::CreateImpl(ASTContext& Context, Deserializer& D) { unsigned Depth = D.ReadInt(); unsigned Index = D.ReadInt(); IdentifierInfo *Name = D.ReadPtr<IdentifierInfo>(); return Context.getTemplateTypeParmType(Depth, Index, Name).getTypePtr(); } //===----------------------------------------------------------------------===// // TemplateSpecializationType //===----------------------------------------------------------------------===// void TemplateSpecializationType::EmitImpl(Serializer& S) const { // FIXME: Serialization support } Type* TemplateSpecializationType:: CreateImpl(ASTContext& Context, Deserializer& D) { // FIXME: Deserialization support return 0; } //===----------------------------------------------------------------------===// // QualifiedNameType //===----------------------------------------------------------------------===// void QualifiedNameType::EmitImpl(llvm::Serializer& S) const { // FIXME: Serialize the actual components } Type* QualifiedNameType::CreateImpl(ASTContext& Context, llvm::Deserializer& D) { // FIXME: Implement de-serialization return 0; } //===----------------------------------------------------------------------===// // TypenameType //===----------------------------------------------------------------------===// void TypenameType::EmitImpl(llvm::Serializer& S) const { // FIXME: Serialize the actual components } Type* TypenameType::CreateImpl(ASTContext& Context, llvm::Deserializer& D) { // FIXME: Implement de-serialization return 0; } //===----------------------------------------------------------------------===// // VariableArrayType //===----------------------------------------------------------------------===// void VariableArrayType::EmitImpl(Serializer& S) const { S.Emit(getElementType()); S.EmitInt(getSizeModifier()); S.EmitInt(getIndexTypeQualifier()); S.EmitOwnedPtr(SizeExpr); } Type* VariableArrayType::CreateImpl(ASTContext& Context, Deserializer& D) { QualType ElTy = QualType::ReadVal(D); ArraySizeModifier am = static_cast<ArraySizeModifier>(D.ReadInt()); unsigned ITQ = D.ReadInt(); Expr* SizeExpr = D.ReadOwnedPtr<Expr>(Context); return Context.getVariableArrayType(ElTy,SizeExpr,am,ITQ).getTypePtr(); } //===----------------------------------------------------------------------===// // DependentSizedArrayType //===----------------------------------------------------------------------===// void DependentSizedArrayType::EmitImpl(Serializer& S) const { S.Emit(getElementType()); S.EmitInt(getSizeModifier()); S.EmitInt(getIndexTypeQualifier()); S.EmitOwnedPtr(SizeExpr); } Type* DependentSizedArrayType::CreateImpl(ASTContext& Context, Deserializer& D) { QualType ElTy = QualType::ReadVal(D); ArraySizeModifier am = static_cast<ArraySizeModifier>(D.ReadInt()); unsigned ITQ = D.ReadInt(); Expr* SizeExpr = D.ReadOwnedPtr<Expr>(Context); return Context.getDependentSizedArrayType(ElTy,SizeExpr,am,ITQ).getTypePtr(); } //===----------------------------------------------------------------------===// // IncompleteArrayType //===----------------------------------------------------------------------===// void IncompleteArrayType::EmitImpl(Serializer& S) const { S.Emit(getElementType()); S.EmitInt(getSizeModifier()); S.EmitInt(getIndexTypeQualifier()); } Type* IncompleteArrayType::CreateImpl(ASTContext& Context, Deserializer& D) { QualType ElTy = QualType::ReadVal(D); ArraySizeModifier am = static_cast<ArraySizeModifier>(D.ReadInt()); unsigned ITQ = D.ReadInt(); return Context.getIncompleteArrayType(ElTy,am,ITQ).getTypePtr(); } <file_sep>/test/Parser/cxx-decl.cpp // RUN: clang-cc -verify -fsyntax-only %s int x(*g); // expected-error {{use of undeclared identifier 'g'}} <file_sep>/test/Frontend/mmacosx-version-min-test.c // RUN: not clang-cc -fsyntax-only -mmacosx-version-min=10.4 -triple=x86_64-apple-darwin %s <file_sep>/lib/Sema/CMakeLists.txt set(LLVM_NO_RTTI 1) add_clang_library(clangSema IdentifierResolver.cpp ParseAST.cpp Sema.cpp SemaAccess.cpp SemaAttr.cpp SemaChecking.cpp SemaCXXScopeSpec.cpp SemaDeclAttr.cpp SemaDecl.cpp SemaDeclCXX.cpp SemaDeclObjC.cpp SemaExpr.cpp SemaExprCXX.cpp SemaExprObjC.cpp SemaInherit.cpp SemaInit.cpp SemaLookup.cpp SemaNamedCast.cpp SemaOverload.cpp SemaStmt.cpp SemaTemplate.cpp SemaTemplateInstantiate.cpp SemaTemplateInstantiateDecl.cpp SemaTemplateInstantiateExpr.cpp SemaType.cpp ) add_dependencies(clangSema ClangDiagnosticSema) <file_sep>/include/clang/Frontend/PCHBitCodes.h //===- PCHBitCodes.h - Enum values for the PCH bitcode format ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines Bitcode enum values for Clang precompiled header files. // // The enum values defined in this file should be considered permanent. If // new features are added, they should have values added at the end of the // respective lists. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_PCHBITCODES_H #define LLVM_CLANG_FRONTEND_PCHBITCODES_H #include "llvm/Bitcode/BitCodes.h" #include "llvm/Support/DataTypes.h" namespace clang { namespace pch { /// \brief An ID number that refers to a declaration in a PCH file. /// /// The ID numbers of types are consecutive (in order of /// discovery) and start at 2. 0 is reserved for NULL, and 1 is /// reserved for the translation unit declaration. typedef uint32_t DeclID; /// \brief An ID number that refers to a type in a PCH file. /// /// The ID of a type is partitioned into two parts: the lower /// three bits are used to store the const/volatile/restrict /// qualifiers (as with QualType) and the upper bits provide a /// type index. The type index values are partitioned into two /// sets. The values below NUM_PREDEF_TYPE_IDs are predefined type /// IDs (based on the PREDEF_TYPE_*_ID constants), with 0 as a /// placeholder for "no type". Values from NUM_PREDEF_TYPE_IDs are /// other types that have serialized representations. typedef uint32_t TypeID; /// \brief An ID number that refers to an identifier in a PCH /// file. typedef uint32_t IdentID; /// \brief Describes the various kinds of blocks that occur within /// a PCH file. enum BlockIDs { /// \brief The PCH block, which acts as a container around the /// full PCH block. PCH_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID, /// \brief The block containing information about the source /// manager. SOURCE_MANAGER_BLOCK_ID, /// \brief The block containing information about the /// preprocessor. PREPROCESSOR_BLOCK_ID, /// \brief The block containing the definitions of all of the /// types used within the PCH file. TYPES_BLOCK_ID, /// \brief The block containing the definitions of all of the /// declarations stored in the PCH file. DECLS_BLOCK_ID }; /// \brief Record types that occur within the PCH block itself. enum PCHRecordTypes { /// \brief Offset of each type within the types block. /// /// The TYPE_OFFSET constant describes the record that occurs /// within the block identified by TYPE_OFFSETS_BLOCK_ID within /// the PCH file. The record itself is an array of offsets that /// point into the types block (identified by TYPES_BLOCK_ID in /// the PCH file). The index into the array is based on the ID /// of a type. For a given type ID @c T, the lower three bits of /// @c T are its qualifiers (const, volatile, restrict), as in /// the QualType class. The upper bits, after being shifted and /// subtracting NUM_PREDEF_TYPE_IDS, are used to index into the /// TYPE_OFFSET block to determine the offset of that type's /// corresponding record within the TYPES_BLOCK_ID block. TYPE_OFFSET = 1, /// \brief Record code for the offsets of each decl. /// /// The DECL_OFFSET constant describes the record that occurs /// within the block identifier by DECL_OFFSETS_BLOCK_ID within /// the PCH file. The record itself is an array of offsets that /// point into the declarations block (identified by /// DECLS_BLOCK_ID). The declaration ID is an index into this /// record, after subtracting one to account for the use of /// declaration ID 0 for a NULL declaration pointer. Index 0 is /// reserved for the translation unit declaration. DECL_OFFSET = 2, /// \brief Record code for the language options table. /// /// The record with this code contains the contents of the /// LangOptions structure. We serialize the entire contents of /// the structure, and let the reader decide which options are /// actually important to check. LANGUAGE_OPTIONS = 3, /// \brief Record code for the target triple used to build the /// PCH file. TARGET_TRIPLE = 4, /// \brief Record code for the table of offsets of each /// identifier ID. /// /// The offset table contains offsets into the blob stored in /// the IDENTIFIER_TABLE record. Each offset points to the /// NULL-terminated string that corresponds to that identifier. IDENTIFIER_OFFSET = 5, /// \brief Record code for the identifier table. /// /// The identifier table is a simple blob that contains /// NULL-terminated strings for all of the identifiers /// referenced by the PCH file. The IDENTIFIER_OFFSET table /// contains the mapping from identifier IDs to the characters /// in this blob. Note that the starting offsets of all of the /// identifiers are odd, so that, when the identifier offset /// table is loaded in, we can use the low bit to distinguish /// between offsets (for unresolved identifier IDs) and /// IdentifierInfo pointers (for already-resolved identifier /// IDs). IDENTIFIER_TABLE = 6, /// \brief Record code for the array of external definitions. /// /// The PCH file contains a list of all of the external /// definitions present within the parsed headers, stored as an /// array of declaration IDs. These external definitions will be /// reported to the AST consumer after the PCH file has been /// read, since their presence can affect the semantics of the /// program (e.g., for code generation). EXTERNAL_DEFINITIONS = 7 }; /// \brief Record types used within a source manager block. enum SourceManagerRecordTypes { /// \brief Describes a source location entry (SLocEntry) for a /// file. SM_SLOC_FILE_ENTRY = 1, /// \brief Describes a source location entry (SLocEntry) for a /// buffer. SM_SLOC_BUFFER_ENTRY = 2, /// \brief Describes a blob that contains the data for a buffer /// entry. This kind of record always directly follows a /// SM_SLOC_BUFFER_ENTRY record. SM_SLOC_BUFFER_BLOB = 3, /// \brief Describes a source location entry (SLocEntry) for a /// macro instantiation. SM_SLOC_INSTANTIATION_ENTRY = 4, /// \brief Describes the SourceManager's line table, with /// information about #line directives. SM_LINE_TABLE = 5 }; /// \brief Record types used within a preprocessor block. enum PreprocessorRecordTypes { // The macros in the PP section are a PP_MACRO_* instance followed by a // list of PP_TOKEN instances for each token in the definition. /// \brief An object-like macro definition. /// [PP_MACRO_OBJECT_LIKE, IdentInfoID, SLoc, IsUsed] PP_MACRO_OBJECT_LIKE = 1, /// \brief A function-like macro definition. /// [PP_MACRO_FUNCTION_LIKE, <ObjectLikeStuff>, IsC99Varargs, IsGNUVarars, /// NumArgs, ArgIdentInfoID* ] PP_MACRO_FUNCTION_LIKE = 2, /// \brief Describes one token. /// [PP_TOKEN, SLoc, Length, IdentInfoID, Kind, Flags] PP_TOKEN = 3, /// \brief The value of the next __COUNTER__ to dispense. /// [PP_COUNTER_VALUE, Val] PP_COUNTER_VALUE = 4 }; /// \defgroup PCHAST Precompiled header AST constants /// /// The constants in this group describe various components of the /// abstract syntax tree within a precompiled header. /// /// @{ /// \brief Predefined type IDs. /// /// These type IDs correspond to predefined types in the AST /// context, such as built-in types (int) and special place-holder /// types (the <overload> and <dependent> type markers). Such /// types are never actually serialized, since they will be built /// by the AST context when it is created. enum PredefinedTypeIDs { /// \brief The NULL type. PREDEF_TYPE_NULL_ID = 0, /// \brief The void type. PREDEF_TYPE_VOID_ID = 1, /// \brief The 'bool' or '_Bool' type. PREDEF_TYPE_BOOL_ID = 2, /// \brief The 'char' type, when it is unsigned. PREDEF_TYPE_CHAR_U_ID = 3, /// \brief The 'unsigned char' type. PREDEF_TYPE_UCHAR_ID = 4, /// \brief The 'unsigned short' type. PREDEF_TYPE_USHORT_ID = 5, /// \brief The 'unsigned int' type. PREDEF_TYPE_UINT_ID = 6, /// \brief The 'unsigned long' type. PREDEF_TYPE_ULONG_ID = 7, /// \brief The 'unsigned long long' type. PREDEF_TYPE_ULONGLONG_ID = 8, /// \brief The 'char' type, when it is signed. PREDEF_TYPE_CHAR_S_ID = 9, /// \brief The 'signed char' type. PREDEF_TYPE_SCHAR_ID = 10, /// \brief The C++ 'wchar_t' type. PREDEF_TYPE_WCHAR_ID = 11, /// \brief The (signed) 'short' type. PREDEF_TYPE_SHORT_ID = 12, /// \brief The (signed) 'int' type. PREDEF_TYPE_INT_ID = 13, /// \brief The (signed) 'long' type. PREDEF_TYPE_LONG_ID = 14, /// \brief The (signed) 'long long' type. PREDEF_TYPE_LONGLONG_ID = 15, /// \brief The 'float' type. PREDEF_TYPE_FLOAT_ID = 16, /// \brief The 'double' type. PREDEF_TYPE_DOUBLE_ID = 17, /// \brief The 'long double' type. PREDEF_TYPE_LONGDOUBLE_ID = 18, /// \brief The placeholder type for overloaded function sets. PREDEF_TYPE_OVERLOAD_ID = 19, /// \brief The placeholder type for dependent types. PREDEF_TYPE_DEPENDENT_ID = 20 }; /// \brief The number of predefined type IDs that are reserved for /// the PREDEF_TYPE_* constants. /// /// Type IDs for non-predefined types will start at /// NUM_PREDEF_TYPE_IDs. const unsigned NUM_PREDEF_TYPE_IDS = 100; /// \brief Record codes for each kind of type. /// /// These constants describe the records that can occur within a /// block identified by TYPES_BLOCK_ID in the PCH file. Each /// constant describes a record for a specific type class in the /// AST. enum TypeCode { /// \brief An ExtQualType record. TYPE_EXT_QUAL = 1, /// \brief A FixedWidthIntType record. TYPE_FIXED_WIDTH_INT = 2, /// \brief A ComplexType record. TYPE_COMPLEX = 3, /// \brief A PointerType record. TYPE_POINTER = 4, /// \brief A BlockPointerType record. TYPE_BLOCK_POINTER = 5, /// \brief An LValueReferenceType record. TYPE_LVALUE_REFERENCE = 6, /// \brief An RValueReferenceType record. TYPE_RVALUE_REFERENCE = 7, /// \brief A MemberPointerType record. TYPE_MEMBER_POINTER = 8, /// \brief A ConstantArrayType record. TYPE_CONSTANT_ARRAY = 9, /// \brief An IncompleteArrayType record. TYPE_INCOMPLETE_ARRAY = 10, /// \brief A VariableArrayType record. TYPE_VARIABLE_ARRAY = 11, /// \brief A VectorType record. TYPE_VECTOR = 12, /// \brief An ExtVectorType record. TYPE_EXT_VECTOR = 13, /// \brief A FunctionNoProtoType record. TYPE_FUNCTION_NO_PROTO = 14, /// \brief A FunctionProtoType record. TYPE_FUNCTION_PROTO = 15, /// \brief A TypedefType record. TYPE_TYPEDEF = 16, /// \brief A TypeOfExprType record. TYPE_TYPEOF_EXPR = 17, /// \brief A TypeOfType record. TYPE_TYPEOF = 18, /// \brief A RecordType record. TYPE_RECORD = 19, /// \brief An EnumType record. TYPE_ENUM = 20, /// \brief An ObjCInterfaceType record. TYPE_OBJC_INTERFACE = 21, /// \brief An ObjCQualifiedInterfaceType record. TYPE_OBJC_QUALIFIED_INTERFACE = 22, /// \brief An ObjCQualifiedIdType record. TYPE_OBJC_QUALIFIED_ID = 23, /// \brief An ObjCQualifiedClassType record. TYPE_OBJC_QUALIFIED_CLASS = 24 }; /// \brief Record codes for each kind of declaration. /// /// These constants describe the records that can occur within a /// declarations block (identified by DECLS_BLOCK_ID). Each /// constant describes a record for a specific declaration class /// in the AST. enum DeclCode { /// \brief Attributes attached to a declaration. DECL_ATTR = 1, /// \brief A TranslationUnitDecl record. DECL_TRANSLATION_UNIT, /// \brief A TypedefDecl record. DECL_TYPEDEF, /// \brief An EnumDecl record. DECL_ENUM, /// \brief A RecordDecl record. DECL_RECORD, /// \brief An EnumConstantDecl record. DECL_ENUM_CONSTANT, /// \brief A FunctionDecl record. DECL_FUNCTION, /// \brief A FieldDecl record. DECL_FIELD, /// \brief A VarDecl record. DECL_VAR, /// \brief A ParmVarDecl record. DECL_PARM_VAR, /// \brief An OriginalParmVarDecl record. DECL_ORIGINAL_PARM_VAR, /// \brief A FileScopeAsmDecl record. DECL_FILE_SCOPE_ASM, /// \brief A BlockDecl record. DECL_BLOCK, /// \brief A record that stores the set of declarations that are /// lexically stored within a given DeclContext. /// /// The record itself is an array of declaration IDs, in the /// order in which those declarations were added to the /// declaration context. This data is used when iterating over /// the contents of a DeclContext, e.g., via /// DeclContext::decls_begin()/DeclContext::decls_end(). DECL_CONTEXT_LEXICAL, /// \brief A record that stores the set of declarations that are /// visible from a given DeclContext. /// /// The record itself stores a set of mappings, each of which /// associates a declaration name with one or more declaration /// IDs. This data is used when performing qualified name lookup /// into a DeclContext via DeclContext::lookup. DECL_CONTEXT_VISIBLE }; /// \brief Record codes for each kind of statement or expression. /// /// These constants describe the records that describe statements /// or expressions. These records can occur within either the type /// or declaration blocks, so they begin with record values of /// 100. Each constant describes a record for a specific /// statement or expression class in the AST. enum StmtCode { /// \brief A marker record that indicates that we are at the end /// of an expression. EXPR_STOP, /// \brief A NULL expression. EXPR_NULL, /// \brief A PredefinedExpr record. EXPR_PREDEFINED, /// \brief A DeclRefExpr record. EXPR_DECL_REF, /// \brief An IntegerLiteral record. EXPR_INTEGER_LITERAL, /// \brief A FloatingLiteral record. EXPR_FLOATING_LITERAL, /// \brief An ImaginaryLiteral record. EXPR_IMAGINARY_LITERAL, /// \brief A StringLiteral record. EXPR_STRING_LITERAL, /// \brief A CharacterLiteral record. EXPR_CHARACTER_LITERAL, /// \brief A ParenExpr record. EXPR_PAREN, /// \brief A UnaryOperator record. EXPR_UNARY_OPERATOR, /// \brief A SizefAlignOfExpr record. EXPR_SIZEOF_ALIGN_OF, /// \brief An ArraySubscriptExpr record. EXPR_ARRAY_SUBSCRIPT, /// \brief A CallExpr record. EXPR_CALL, /// \brief A MemberExpr record. EXPR_MEMBER, /// \brief A BinaryOperator record. EXPR_BINARY_OPERATOR, /// \brief A CompoundAssignOperator record. EXPR_COMPOUND_ASSIGN_OPERATOR, /// \brief A ConditionOperator record. EXPR_CONDITIONAL_OPERATOR, /// \brief An ImplicitCastExpr record. EXPR_IMPLICIT_CAST, /// \brief A CStyleCastExpr record. EXPR_CSTYLE_CAST, /// \brief A CompoundLiteralExpr record. EXPR_COMPOUND_LITERAL, /// \brief An ExtVectorElementExpr record. EXPR_EXT_VECTOR_ELEMENT, /// \brief An InitListExpr record. EXPR_INIT_LIST, /// \brief A DesignatedInitExpr record. EXPR_DESIGNATED_INIT, /// \brief An ImplicitValueInitExpr record. EXPR_IMPLICIT_VALUE_INIT, /// \brief A VAArgExpr record. EXPR_VA_ARG, // FIXME: AddrLabelExpr // FIXME: StmtExpr /// \brief A TypesCompatibleExpr record. EXPR_TYPES_COMPATIBLE, /// \brief A ChooseExpr record. EXPR_CHOOSE, /// \brief A GNUNullExpr record. EXPR_GNU_NULL, /// \brief A ShuffleVectorExpr record. EXPR_SHUFFLE_VECTOR, /// FIXME: BlockExpr EXPR_BLOCK_DECL_REF }; /// \brief The kinds of designators that can occur in a /// DesignatedInitExpr. enum DesignatorTypes { /// \brief Field designator where only the field name is known. DESIG_FIELD_NAME = 0, /// \brief Field designator where the field has been resolved to /// a declaration. DESIG_FIELD_DECL = 1, /// \brief Array designator. DESIG_ARRAY = 2, /// \brief GNU array range designator. DESIG_ARRAY_RANGE = 3 }; /// @} } } // end namespace clang #endif <file_sep>/tools/ccc/test/ccc/integrated-cpp.c // RUN: xcc -fsyntax-only -### %s 2>&1 | count 2 && // RUN: xcc -fsyntax-only -### %s -no-integrated-cpp 2>&1 | count 3 && // RUN: xcc -fsyntax-only -### %s -save-temps 2>&1 | count 3 <file_sep>/test/Preprocessor/_Pragma-poison.c // RUN: clang-cc -Eonly %s 2>&1 | grep error | wc -l | grep 1 && // RUN: clang-cc -Eonly %s 2>&1 | grep 7:4 | wc -l | grep 1 #define BAR _Pragma ("GCC poison XYZW") XYZW /*NO ERROR*/ XYZW // NO ERROR BAR XYZW // ERROR <file_sep>/test/Analysis/CGColorSpace.c // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -analyzer-constraints=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -analyzer-constraints=range -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -analyzer-constraints=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -analyzer-constraints=range -verify %s typedef struct CGColorSpace *CGColorSpaceRef; extern CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void); extern CGColorSpaceRef CGColorSpaceRetain(CGColorSpaceRef space); extern void CGColorSpaceRelease(CGColorSpaceRef space); void f() { CGColorSpaceRef X = CGColorSpaceCreateDeviceRGB(); // expected-warning{{leak}} CGColorSpaceRetain(X); } void fb() { CGColorSpaceRef X = CGColorSpaceCreateDeviceRGB(); CGColorSpaceRetain(X); CGColorSpaceRelease(X); CGColorSpaceRelease(X); // no-warning } <file_sep>/lib/Sema/SemaOverload.h //===--- Overload.h - C++ Overloading ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the data structures and types used in C++ // overload resolution. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_OVERLOAD_H #define LLVM_CLANG_SEMA_OVERLOAD_H #include "llvm/ADT/SmallVector.h" namespace clang { class CXXConstructorDecl; class FunctionDecl; /// ImplicitConversionKind - The kind of implicit conversion used to /// convert an argument to a parameter's type. The enumerator values /// match with Table 9 of (C++ 13.3.3.1.1) and are listed such that /// better conversion kinds have smaller values. enum ImplicitConversionKind { ICK_Identity = 0, ///< Identity conversion (no conversion) ICK_Lvalue_To_Rvalue, ///< Lvalue-to-rvalue conversion (C++ 4.1) ICK_Array_To_Pointer, ///< Array-to-pointer conversion (C++ 4.2) ICK_Function_To_Pointer, ///< Function-to-pointer (C++ 4.3) ICK_Qualification, ///< Qualification conversions (C++ 4.4) ICK_Integral_Promotion, ///< Integral promotions (C++ 4.5) ICK_Floating_Promotion, ///< Floating point promotions (C++ 4.6) ICK_Complex_Promotion, ///< Complex promotions (Clang extension) ICK_Integral_Conversion, ///< Integral conversions (C++ 4.7) ICK_Floating_Conversion, ///< Floating point conversions (C++ 4.8) ICK_Complex_Conversion, ///< Complex conversions (C99 6.3.1.6) ICK_Floating_Integral, ///< Floating-integral conversions (C++ 4.9) ICK_Complex_Real, ///< Complex-real conversions (C99 6.3.1.7) ICK_Pointer_Conversion, ///< Pointer conversions (C++ 4.10) ICK_Pointer_Member, ///< Pointer-to-member conversions (C++ 4.11) ICK_Boolean_Conversion, ///< Boolean conversions (C++ 4.12) ICK_Compatible_Conversion, ///< Conversions between compatible types in C99 ICK_Derived_To_Base, ///< Derived-to-base (C++ [over.best.ics]) ICK_Num_Conversion_Kinds ///< The number of conversion kinds }; /// ImplicitConversionCategory - The category of an implicit /// conversion kind. The enumerator values match with Table 9 of /// (C++ 13.3.3.1.1) and are listed such that better conversion /// categories have smaller values. enum ImplicitConversionCategory { ICC_Identity = 0, ///< Identity ICC_Lvalue_Transformation, ///< Lvalue transformation ICC_Qualification_Adjustment, ///< Qualification adjustment ICC_Promotion, ///< Promotion ICC_Conversion ///< Conversion }; ImplicitConversionCategory GetConversionCategory(ImplicitConversionKind Kind); /// ImplicitConversionRank - The rank of an implicit conversion /// kind. The enumerator values match with Table 9 of (C++ /// 13.3.3.1.1) and are listed such that better conversion ranks /// have smaller values. enum ImplicitConversionRank { ICR_Exact_Match = 0, ///< Exact Match ICR_Promotion, ///< Promotion ICR_Conversion ///< Conversion }; ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind); /// StandardConversionSequence - represents a standard conversion /// sequence (C++ 13.3.3.1.1). A standard conversion sequence /// contains between zero and three conversions. If a particular /// conversion is not needed, it will be set to the identity conversion /// (ICK_Identity). Note that the three conversions are /// specified as separate members (rather than in an array) so that /// we can keep the size of a standard conversion sequence to a /// single word. struct StandardConversionSequence { /// First -- The first conversion can be an lvalue-to-rvalue /// conversion, array-to-pointer conversion, or /// function-to-pointer conversion. ImplicitConversionKind First : 8; /// Second - The second conversion can be an integral promotion, /// floating point promotion, integral conversion, floating point /// conversion, floating-integral conversion, pointer conversion, /// pointer-to-member conversion, or boolean conversion. ImplicitConversionKind Second : 8; /// Third - The third conversion can be a qualification conversion. ImplicitConversionKind Third : 8; /// Deprecated - Whether this the deprecated conversion of a /// string literal to a pointer to non-const character data /// (C++ 4.2p2). bool Deprecated : 1; /// IncompatibleObjC - Whether this is an Objective-C conversion /// that we should warn about (if we actually use it). bool IncompatibleObjC : 1; /// ReferenceBinding - True when this is a reference binding /// (C++ [over.ics.ref]). bool ReferenceBinding : 1; /// DirectBinding - True when this is a reference binding that is a /// direct binding (C++ [dcl.init.ref]). bool DirectBinding : 1; /// RRefBinding - True when this is a reference binding of an rvalue /// reference to an rvalue (C++0x [over.ics.rank]p3b4). bool RRefBinding : 1; /// FromType - The type that this conversion is converting /// from. This is an opaque pointer that can be translated into a /// QualType. void *FromTypePtr; /// ToType - The type that this conversion is converting to. This /// is an opaque pointer that can be translated into a QualType. void *ToTypePtr; /// CopyConstructor - The copy constructor that is used to perform /// this conversion, when the conversion is actually just the /// initialization of an object via copy constructor. Such /// conversions are either identity conversions or derived-to-base /// conversions. CXXConstructorDecl *CopyConstructor; void setAsIdentityConversion(); ImplicitConversionRank getRank() const; bool isPointerConversionToBool() const; bool isPointerConversionToVoidPointer(ASTContext& Context) const; void DebugPrint() const; }; /// UserDefinedConversionSequence - Represents a user-defined /// conversion sequence (C++ 13.3.3.1.2). struct UserDefinedConversionSequence { /// Before - Represents the standard conversion that occurs before /// the actual user-defined conversion. (C++ 13.3.3.1.2p1): /// /// If the user-defined conversion is specified by a constructor /// (12.3.1), the initial standard conversion sequence converts /// the source type to the type required by the argument of the /// constructor. If the user-defined conversion is specified by /// a conversion function (12.3.2), the initial standard /// conversion sequence converts the source type to the implicit /// object parameter of the conversion function. StandardConversionSequence Before; /// After - Represents the standard conversion that occurs after /// the actual user-defined conversion. StandardConversionSequence After; /// ConversionFunction - The function that will perform the /// user-defined conversion. FunctionDecl* ConversionFunction; void DebugPrint() const; }; /// ImplicitConversionSequence - Represents an implicit conversion /// sequence, which may be a standard conversion sequence // (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2), /// or an ellipsis conversion sequence (C++ 13.3.3.1.3). struct ImplicitConversionSequence { /// Kind - The kind of implicit conversion sequence. BadConversion /// specifies that there is no conversion from the source type to /// the target type. The enumerator values are ordered such that /// better implicit conversions have smaller values. enum Kind { StandardConversion = 0, UserDefinedConversion, EllipsisConversion, BadConversion }; /// ConversionKind - The kind of implicit conversion sequence. Kind ConversionKind; union { /// When ConversionKind == StandardConversion, provides the /// details of the standard conversion sequence. StandardConversionSequence Standard; /// When ConversionKind == UserDefinedConversion, provides the /// details of the user-defined conversion sequence. UserDefinedConversionSequence UserDefined; }; // The result of a comparison between implicit conversion // sequences. Use Sema::CompareImplicitConversionSequences to // actually perform the comparison. enum CompareKind { Better = -1, Indistinguishable = 0, Worse = 1 }; void DebugPrint() const; }; /// OverloadCandidate - A single candidate in an overload set (C++ 13.3). struct OverloadCandidate { /// Function - The actual function that this candidate /// represents. When NULL, this is a built-in candidate /// (C++ [over.oper]) or a surrogate for a conversion to a /// function pointer or reference (C++ [over.call.object]). FunctionDecl *Function; // BuiltinTypes - Provides the return and parameter types of a // built-in overload candidate. Only valid when Function is NULL. struct { QualType ResultTy; QualType ParamTypes[3]; } BuiltinTypes; /// Surrogate - The conversion function for which this candidate /// is a surrogate, but only if IsSurrogate is true. CXXConversionDecl *Surrogate; /// Conversions - The conversion sequences used to convert the /// function arguments to the function parameters. llvm::SmallVector<ImplicitConversionSequence, 4> Conversions; /// Viable - True to indicate that this overload candidate is viable. bool Viable; /// IsSurrogate - True to indicate that this candidate is a /// surrogate for a conversion to a function pointer or reference /// (C++ [over.call.object]). bool IsSurrogate; /// IgnoreObjectArgument - True to indicate that the first /// argument's conversion, which for this function represents the /// implicit object argument, should be ignored. This will be true /// when the candidate is a static member function (where the /// implicit object argument is just a placeholder) or a /// non-static member function when the call doesn't have an /// object argument. bool IgnoreObjectArgument; /// FinalConversion - For a conversion function (where Function is /// a CXXConversionDecl), the standard conversion that occurs /// after the call to the overload candidate to convert the result /// of calling the conversion function to the required type. StandardConversionSequence FinalConversion; }; /// OverloadCandidateSet - A set of overload candidates, used in C++ /// overload resolution (C++ 13.3). typedef llvm::SmallVector<OverloadCandidate, 16> OverloadCandidateSet; } // end namespace clang #endif // LLVM_CLANG_SEMA_OVERLOAD_H <file_sep>/include/clang/Basic/CMakeLists.txt macro(clang_diag_gen component) tablegen(Diagnostic${component}Kinds.inc -gen-clang-diags-defs -clang-component=${component}) add_custom_target(ClangDiagnostic${component} DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/Diagnostic${component}Kinds.inc) endmacro(clang_diag_gen) set(LLVM_TARGET_DEFINITIONS Diagnostic.td) clang_diag_gen(Analysis) clang_diag_gen(AST) clang_diag_gen(Common) clang_diag_gen(Driver) clang_diag_gen(Frontend) clang_diag_gen(Lex) clang_diag_gen(Parse) clang_diag_gen(Sema)<file_sep>/lib/AST/Type.cpp //===--- Type.cpp - Type representation and manipulation ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements type-related functionality. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/Type.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/raw_ostream.h" using namespace clang; bool QualType::isConstant(ASTContext &Ctx) const { if (isConstQualified()) return true; if (getTypePtr()->isArrayType()) return Ctx.getAsArrayType(*this)->getElementType().isConstant(Ctx); return false; } void Type::Destroy(ASTContext& C) { this->~Type(); C.Deallocate(this); } void VariableArrayType::Destroy(ASTContext& C) { SizeExpr->Destroy(C); this->~VariableArrayType(); C.Deallocate(this); } void DependentSizedArrayType::Destroy(ASTContext& C) { SizeExpr->Destroy(C); this->~DependentSizedArrayType(); C.Deallocate(this); } /// getArrayElementTypeNoTypeQual - If this is an array type, return the /// element type of the array, potentially with type qualifiers missing. /// This method should never be used when type qualifiers are meaningful. const Type *Type::getArrayElementTypeNoTypeQual() const { // If this is directly an array type, return it. if (const ArrayType *ATy = dyn_cast<ArrayType>(this)) return ATy->getElementType().getTypePtr(); // If the canonical form of this type isn't the right kind, reject it. if (!isa<ArrayType>(CanonicalType)) { // Look through type qualifiers if (ArrayType *AT = dyn_cast<ArrayType>(CanonicalType.getUnqualifiedType())) return AT->getElementType().getTypePtr(); return 0; } // If this is a typedef for an array type, strip the typedef off without // losing all typedef information. return cast<ArrayType>(getDesugaredType())->getElementType().getTypePtr(); } /// getDesugaredType - Return the specified type with any "sugar" removed from /// the type. This takes off typedefs, typeof's etc. If the outer level of /// the type is already concrete, it returns it unmodified. This is similar /// to getting the canonical type, but it doesn't remove *all* typedefs. For /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is /// concrete. /// /// \param ForDisplay When true, the desugaring is provided for /// display purposes only. In this case, we apply more heuristics to /// decide whether it is worth providing a desugared form of the type /// or not. QualType QualType::getDesugaredType(bool ForDisplay) const { return getTypePtr()->getDesugaredType(ForDisplay) .getWithAdditionalQualifiers(getCVRQualifiers()); } /// getDesugaredType - Return the specified type with any "sugar" removed from /// type type. This takes off typedefs, typeof's etc. If the outer level of /// the type is already concrete, it returns it unmodified. This is similar /// to getting the canonical type, but it doesn't remove *all* typedefs. For /// example, it return "T*" as "T*", (not as "int*"), because the pointer is /// concrete. /// /// \param ForDisplay When true, the desugaring is provided for /// display purposes only. In this case, we apply more heuristics to /// decide whether it is worth providing a desugared form of the type /// or not. QualType Type::getDesugaredType(bool ForDisplay) const { if (const TypedefType *TDT = dyn_cast<TypedefType>(this)) return TDT->LookThroughTypedefs().getDesugaredType(); if (const TypeOfExprType *TOE = dyn_cast<TypeOfExprType>(this)) return TOE->getUnderlyingExpr()->getType().getDesugaredType(); if (const TypeOfType *TOT = dyn_cast<TypeOfType>(this)) return TOT->getUnderlyingType().getDesugaredType(); if (const TemplateSpecializationType *Spec = dyn_cast<TemplateSpecializationType>(this)) { if (ForDisplay) return QualType(this, 0); QualType Canon = Spec->getCanonicalTypeInternal(); if (Canon->getAsTemplateSpecializationType()) return QualType(this, 0); return Canon->getDesugaredType(); } if (const QualifiedNameType *QualName = dyn_cast<QualifiedNameType>(this)) { if (ForDisplay) { // If desugaring the type that the qualified name is referring to // produces something interesting, that's our desugared type. QualType NamedType = QualName->getNamedType().getDesugaredType(); if (NamedType != QualName->getNamedType()) return NamedType; } else return QualName->getNamedType().getDesugaredType(); } return QualType(this, 0); } /// isVoidType - Helper method to determine if this is the 'void' type. bool Type::isVoidType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() == BuiltinType::Void; if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType)) return AS->getBaseType()->isVoidType(); return false; } bool Type::isObjectType() const { if (isa<FunctionType>(CanonicalType) || isa<ReferenceType>(CanonicalType) || isa<IncompleteArrayType>(CanonicalType) || isVoidType()) return false; if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType)) return AS->getBaseType()->isObjectType(); return true; } bool Type::isDerivedType() const { switch (CanonicalType->getTypeClass()) { case ExtQual: return cast<ExtQualType>(CanonicalType)->getBaseType()->isDerivedType(); case Pointer: case VariableArray: case ConstantArray: case IncompleteArray: case FunctionProto: case FunctionNoProto: case LValueReference: case RValueReference: case Record: return true; default: return false; } } bool Type::isClassType() const { if (const RecordType *RT = getAsRecordType()) return RT->getDecl()->isClass(); return false; } bool Type::isStructureType() const { if (const RecordType *RT = getAsRecordType()) return RT->getDecl()->isStruct(); return false; } bool Type::isUnionType() const { if (const RecordType *RT = getAsRecordType()) return RT->getDecl()->isUnion(); return false; } bool Type::isComplexType() const { if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) return CT->getElementType()->isFloatingType(); if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType)) return AS->getBaseType()->isComplexType(); return false; } bool Type::isComplexIntegerType() const { // Check for GCC complex integer extension. if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) return CT->getElementType()->isIntegerType(); if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType)) return AS->getBaseType()->isComplexIntegerType(); return false; } const ComplexType *Type::getAsComplexIntegerType() const { // Are we directly a complex type? if (const ComplexType *CTy = dyn_cast<ComplexType>(this)) { if (CTy->getElementType()->isIntegerType()) return CTy; return 0; } // If the canonical form of this type isn't what we want, reject it. if (!isa<ComplexType>(CanonicalType)) { // Look through type qualifiers (e.g. ExtQualType's). if (isa<ComplexType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsComplexIntegerType(); return 0; } // If this is a typedef for a complex type, strip the typedef off without // losing all typedef information. return cast<ComplexType>(getDesugaredType()); } const BuiltinType *Type::getAsBuiltinType() const { // If this is directly a builtin type, return it. if (const BuiltinType *BTy = dyn_cast<BuiltinType>(this)) return BTy; // If the canonical form of this type isn't a builtin type, reject it. if (!isa<BuiltinType>(CanonicalType)) { // Look through type qualifiers (e.g. ExtQualType's). if (isa<BuiltinType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsBuiltinType(); return 0; } // If this is a typedef for a builtin type, strip the typedef off without // losing all typedef information. return cast<BuiltinType>(getDesugaredType()); } const FunctionType *Type::getAsFunctionType() const { // If this is directly a function type, return it. if (const FunctionType *FTy = dyn_cast<FunctionType>(this)) return FTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<FunctionType>(CanonicalType)) { // Look through type qualifiers if (isa<FunctionType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsFunctionType(); return 0; } // If this is a typedef for a function type, strip the typedef off without // losing all typedef information. return cast<FunctionType>(getDesugaredType()); } const FunctionNoProtoType *Type::getAsFunctionNoProtoType() const { return dyn_cast_or_null<FunctionNoProtoType>(getAsFunctionType()); } const FunctionProtoType *Type::getAsFunctionProtoType() const { return dyn_cast_or_null<FunctionProtoType>(getAsFunctionType()); } const PointerType *Type::getAsPointerType() const { // If this is directly a pointer type, return it. if (const PointerType *PTy = dyn_cast<PointerType>(this)) return PTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<PointerType>(CanonicalType)) { // Look through type qualifiers if (isa<PointerType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsPointerType(); return 0; } // If this is a typedef for a pointer type, strip the typedef off without // losing all typedef information. return cast<PointerType>(getDesugaredType()); } const BlockPointerType *Type::getAsBlockPointerType() const { // If this is directly a block pointer type, return it. if (const BlockPointerType *PTy = dyn_cast<BlockPointerType>(this)) return PTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<BlockPointerType>(CanonicalType)) { // Look through type qualifiers if (isa<BlockPointerType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsBlockPointerType(); return 0; } // If this is a typedef for a block pointer type, strip the typedef off // without losing all typedef information. return cast<BlockPointerType>(getDesugaredType()); } const ReferenceType *Type::getAsReferenceType() const { // If this is directly a reference type, return it. if (const ReferenceType *RTy = dyn_cast<ReferenceType>(this)) return RTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<ReferenceType>(CanonicalType)) { // Look through type qualifiers if (isa<ReferenceType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsReferenceType(); return 0; } // If this is a typedef for a reference type, strip the typedef off without // losing all typedef information. return cast<ReferenceType>(getDesugaredType()); } const LValueReferenceType *Type::getAsLValueReferenceType() const { // If this is directly an lvalue reference type, return it. if (const LValueReferenceType *RTy = dyn_cast<LValueReferenceType>(this)) return RTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<LValueReferenceType>(CanonicalType)) { // Look through type qualifiers if (isa<LValueReferenceType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsLValueReferenceType(); return 0; } // If this is a typedef for an lvalue reference type, strip the typedef off // without losing all typedef information. return cast<LValueReferenceType>(getDesugaredType()); } const RValueReferenceType *Type::getAsRValueReferenceType() const { // If this is directly an rvalue reference type, return it. if (const RValueReferenceType *RTy = dyn_cast<RValueReferenceType>(this)) return RTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<RValueReferenceType>(CanonicalType)) { // Look through type qualifiers if (isa<RValueReferenceType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsRValueReferenceType(); return 0; } // If this is a typedef for an rvalue reference type, strip the typedef off // without losing all typedef information. return cast<RValueReferenceType>(getDesugaredType()); } const MemberPointerType *Type::getAsMemberPointerType() const { // If this is directly a member pointer type, return it. if (const MemberPointerType *MTy = dyn_cast<MemberPointerType>(this)) return MTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<MemberPointerType>(CanonicalType)) { // Look through type qualifiers if (isa<MemberPointerType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsMemberPointerType(); return 0; } // If this is a typedef for a member pointer type, strip the typedef off // without losing all typedef information. return cast<MemberPointerType>(getDesugaredType()); } /// isVariablyModifiedType (C99 6.7.5p3) - Return true for variable length /// array types and types that contain variable array types in their /// declarator bool Type::isVariablyModifiedType() const { // A VLA is a variably modified type. if (isVariableArrayType()) return true; // An array can contain a variably modified type if (const Type *T = getArrayElementTypeNoTypeQual()) return T->isVariablyModifiedType(); // A pointer can point to a variably modified type. // Also, C++ references and member pointers can point to a variably modified // type, where VLAs appear as an extension to C++, and should be treated // correctly. if (const PointerType *PT = getAsPointerType()) return PT->getPointeeType()->isVariablyModifiedType(); if (const ReferenceType *RT = getAsReferenceType()) return RT->getPointeeType()->isVariablyModifiedType(); if (const MemberPointerType *PT = getAsMemberPointerType()) return PT->getPointeeType()->isVariablyModifiedType(); // A function can return a variably modified type // This one isn't completely obvious, but it follows from the // definition in C99 6.7.5p3. Because of this rule, it's // illegal to declare a function returning a variably modified type. if (const FunctionType *FT = getAsFunctionType()) return FT->getResultType()->isVariablyModifiedType(); return false; } const RecordType *Type::getAsRecordType() const { // If this is directly a record type, return it. if (const RecordType *RTy = dyn_cast<RecordType>(this)) return RTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<RecordType>(CanonicalType)) { // Look through type qualifiers if (isa<RecordType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsRecordType(); return 0; } // If this is a typedef for a record type, strip the typedef off without // losing all typedef information. return cast<RecordType>(getDesugaredType()); } const TagType *Type::getAsTagType() const { // If this is directly a tag type, return it. if (const TagType *TagTy = dyn_cast<TagType>(this)) return TagTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<TagType>(CanonicalType)) { // Look through type qualifiers if (isa<TagType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsTagType(); return 0; } // If this is a typedef for a tag type, strip the typedef off without // losing all typedef information. return cast<TagType>(getDesugaredType()); } const RecordType *Type::getAsStructureType() const { // If this is directly a structure type, return it. if (const RecordType *RT = dyn_cast<RecordType>(this)) { if (RT->getDecl()->isStruct()) return RT; } // If the canonical form of this type isn't the right kind, reject it. if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) { if (!RT->getDecl()->isStruct()) return 0; // If this is a typedef for a structure type, strip the typedef off without // losing all typedef information. return cast<RecordType>(getDesugaredType()); } // Look through type qualifiers if (isa<RecordType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsStructureType(); return 0; } const RecordType *Type::getAsUnionType() const { // If this is directly a union type, return it. if (const RecordType *RT = dyn_cast<RecordType>(this)) { if (RT->getDecl()->isUnion()) return RT; } // If the canonical form of this type isn't the right kind, reject it. if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) { if (!RT->getDecl()->isUnion()) return 0; // If this is a typedef for a union type, strip the typedef off without // losing all typedef information. return cast<RecordType>(getDesugaredType()); } // Look through type qualifiers if (isa<RecordType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsUnionType(); return 0; } const EnumType *Type::getAsEnumType() const { // Check the canonicalized unqualified type directly; the more complex // version is unnecessary because there isn't any typedef information // to preserve. return dyn_cast<EnumType>(CanonicalType.getUnqualifiedType()); } const ComplexType *Type::getAsComplexType() const { // Are we directly a complex type? if (const ComplexType *CTy = dyn_cast<ComplexType>(this)) return CTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<ComplexType>(CanonicalType)) { // Look through type qualifiers if (isa<ComplexType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsComplexType(); return 0; } // If this is a typedef for a complex type, strip the typedef off without // losing all typedef information. return cast<ComplexType>(getDesugaredType()); } const VectorType *Type::getAsVectorType() const { // Are we directly a vector type? if (const VectorType *VTy = dyn_cast<VectorType>(this)) return VTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<VectorType>(CanonicalType)) { // Look through type qualifiers if (isa<VectorType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsVectorType(); return 0; } // If this is a typedef for a vector type, strip the typedef off without // losing all typedef information. return cast<VectorType>(getDesugaredType()); } const ExtVectorType *Type::getAsExtVectorType() const { // Are we directly an OpenCU vector type? if (const ExtVectorType *VTy = dyn_cast<ExtVectorType>(this)) return VTy; // If the canonical form of this type isn't the right kind, reject it. if (!isa<ExtVectorType>(CanonicalType)) { // Look through type qualifiers if (isa<ExtVectorType>(CanonicalType.getUnqualifiedType())) return CanonicalType.getUnqualifiedType()->getAsExtVectorType(); return 0; } // If this is a typedef for an extended vector type, strip the typedef off // without losing all typedef information. return cast<ExtVectorType>(getDesugaredType()); } const ObjCInterfaceType *Type::getAsObjCInterfaceType() const { // There is no sugar for ObjCInterfaceType's, just return the canonical // type pointer if it is the right class. There is no typedef information to // return and these cannot be Address-space qualified. return dyn_cast<ObjCInterfaceType>(CanonicalType.getUnqualifiedType()); } const ObjCQualifiedInterfaceType * Type::getAsObjCQualifiedInterfaceType() const { // There is no sugar for ObjCQualifiedInterfaceType's, just return the // canonical type pointer if it is the right class. return dyn_cast<ObjCQualifiedInterfaceType>(CanonicalType.getUnqualifiedType()); } const ObjCQualifiedIdType *Type::getAsObjCQualifiedIdType() const { // There is no sugar for ObjCQualifiedIdType's, just return the canonical // type pointer if it is the right class. return dyn_cast<ObjCQualifiedIdType>(CanonicalType.getUnqualifiedType()); } const TemplateTypeParmType *Type::getAsTemplateTypeParmType() const { // There is no sugar for template type parameters, so just return // the canonical type pointer if it is the right class. // FIXME: can these be address-space qualified? return dyn_cast<TemplateTypeParmType>(CanonicalType); } const TemplateSpecializationType * Type::getAsTemplateSpecializationType() const { // There is no sugar for class template specialization types, so // just return the canonical type pointer if it is the right class. return dyn_cast<TemplateSpecializationType>(CanonicalType); } bool Type::isIntegerType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() >= BuiltinType::Bool && BT->getKind() <= BuiltinType::LongLong; if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) // Incomplete enum types are not treated as integer types. // FIXME: In C++, enum types are never integer types. if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition()) return true; if (isa<FixedWidthIntType>(CanonicalType)) return true; if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) return VT->getElementType()->isIntegerType(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isIntegerType(); return false; } bool Type::isIntegralType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() >= BuiltinType::Bool && BT->getKind() <= BuiltinType::LongLong; if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition()) return true; // Complete enum types are integral. // FIXME: In C++, enum types are never integral. if (isa<FixedWidthIntType>(CanonicalType)) return true; if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isIntegralType(); return false; } bool Type::isEnumeralType() const { if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) return TT->getDecl()->isEnum(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isEnumeralType(); return false; } bool Type::isBooleanType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() == BuiltinType::Bool; if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isBooleanType(); return false; } bool Type::isCharType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() == BuiltinType::Char_U || BT->getKind() == BuiltinType::UChar || BT->getKind() == BuiltinType::Char_S || BT->getKind() == BuiltinType::SChar; if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isCharType(); return false; } bool Type::isWideCharType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() == BuiltinType::WChar; if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isWideCharType(); return false; } /// isSignedIntegerType - Return true if this is an integer type that is /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], /// an enum decl which has a signed representation, or a vector of signed /// integer element type. bool Type::isSignedIntegerType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { return BT->getKind() >= BuiltinType::Char_S && BT->getKind() <= BuiltinType::LongLong; } if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) return ET->getDecl()->getIntegerType()->isSignedIntegerType(); if (const FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(CanonicalType)) return FWIT->isSigned(); if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) return VT->getElementType()->isSignedIntegerType(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isSignedIntegerType(); return false; } /// isUnsignedIntegerType - Return true if this is an integer type that is /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum /// decl which has an unsigned representation, or a vector of unsigned integer /// element type. bool Type::isUnsignedIntegerType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { return BT->getKind() >= BuiltinType::Bool && BT->getKind() <= BuiltinType::ULongLong; } if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); if (const FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(CanonicalType)) return !FWIT->isSigned(); if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) return VT->getElementType()->isUnsignedIntegerType(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isUnsignedIntegerType(); return false; } bool Type::isFloatingType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() >= BuiltinType::Float && BT->getKind() <= BuiltinType::LongDouble; if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) return CT->getElementType()->isFloatingType(); if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) return VT->getElementType()->isFloatingType(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isFloatingType(); return false; } bool Type::isRealFloatingType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() >= BuiltinType::Float && BT->getKind() <= BuiltinType::LongDouble; if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) return VT->getElementType()->isRealFloatingType(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isRealFloatingType(); return false; } bool Type::isRealType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() >= BuiltinType::Bool && BT->getKind() <= BuiltinType::LongDouble; if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) return TT->getDecl()->isEnum() && TT->getDecl()->isDefinition(); if (isa<FixedWidthIntType>(CanonicalType)) return true; if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) return VT->getElementType()->isRealType(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isRealType(); return false; } bool Type::isArithmeticType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() >= BuiltinType::Bool && BT->getKind() <= BuiltinType::LongDouble; if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2). // If a body isn't seen by the time we get here, return false. return ET->getDecl()->isDefinition(); if (isa<FixedWidthIntType>(CanonicalType)) return true; if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isArithmeticType(); return isa<ComplexType>(CanonicalType) || isa<VectorType>(CanonicalType); } bool Type::isScalarType() const { if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) return BT->getKind() != BuiltinType::Void; if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) { // Enums are scalar types, but only if they are defined. Incomplete enums // are not treated as scalar types. if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition()) return true; return false; } if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isScalarType(); if (isa<FixedWidthIntType>(CanonicalType)) return true; return isa<PointerType>(CanonicalType) || isa<BlockPointerType>(CanonicalType) || isa<MemberPointerType>(CanonicalType) || isa<ComplexType>(CanonicalType) || isa<ObjCQualifiedIdType>(CanonicalType) || isa<ObjCQualifiedClassType>(CanonicalType); } /// \brief Determines whether the type is a C++ aggregate type or C /// aggregate or union type. /// /// An aggregate type is an array or a class type (struct, union, or /// class) that has no user-declared constructors, no private or /// protected non-static data members, no base classes, and no virtual /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also /// includes union types. bool Type::isAggregateType() const { if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) { if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl())) return ClassDecl->isAggregate(); return true; } if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isAggregateType(); return isa<ArrayType>(CanonicalType); } /// isConstantSizeType - Return true if this is not a variable sized type, /// according to the rules of C99 6.7.5p3. It is not legal to call this on /// incomplete types or dependent types. bool Type::isConstantSizeType() const { if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType)) return EXTQT->getBaseType()->isConstantSizeType(); assert(!isIncompleteType() && "This doesn't make sense for incomplete types"); assert(!isDependentType() && "This doesn't make sense for dependent types"); // The VAT must have a size, as it is known to be complete. return !isa<VariableArrayType>(CanonicalType); } /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1) /// - a type that can describe objects, but which lacks information needed to /// determine its size. bool Type::isIncompleteType() const { switch (CanonicalType->getTypeClass()) { default: return false; case ExtQual: return cast<ExtQualType>(CanonicalType)->getBaseType()->isIncompleteType(); case Builtin: // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never // be completed. return isVoidType(); case Record: case Enum: // A tagged type (struct/union/enum/class) is incomplete if the decl is a // forward declaration, but not a full definition (C99 6.2.5p22). return !cast<TagType>(CanonicalType)->getDecl()->isDefinition(); case IncompleteArray: // An array of unknown size is an incomplete type (C99 6.2.5p22). return true; } } /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10) bool Type::isPODType() const { // The compiler shouldn't query this for incomplete types, but the user might. // We return false for that case. if (isIncompleteType()) return false; switch (CanonicalType->getTypeClass()) { // Everything not explicitly mentioned is not POD. default: return false; case ExtQual: return cast<ExtQualType>(CanonicalType)->getBaseType()->isPODType(); case VariableArray: case ConstantArray: // IncompleteArray is caught by isIncompleteType() above. return cast<ArrayType>(CanonicalType)->getElementType()->isPODType(); case Builtin: case Complex: case Pointer: case MemberPointer: case Vector: case ExtVector: case ObjCQualifiedId: return true; case Enum: return true; case Record: if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl())) return ClassDecl->isPOD(); // C struct/union is POD. return true; } } bool Type::isPromotableIntegerType() const { if (const BuiltinType *BT = getAsBuiltinType()) switch (BT->getKind()) { case BuiltinType::Bool: case BuiltinType::Char_S: case BuiltinType::Char_U: case BuiltinType::SChar: case BuiltinType::UChar: case BuiltinType::Short: case BuiltinType::UShort: return true; default: return false; } return false; } const char *BuiltinType::getName() const { switch (getKind()) { default: assert(0 && "Unknown builtin type!"); case Void: return "void"; case Bool: return "_Bool"; case Char_S: return "char"; case Char_U: return "char"; case SChar: return "signed char"; case Short: return "short"; case Int: return "int"; case Long: return "long"; case LongLong: return "long long"; case UChar: return "unsigned char"; case UShort: return "unsigned short"; case UInt: return "unsigned int"; case ULong: return "unsigned long"; case ULongLong: return "unsigned long long"; case Float: return "float"; case Double: return "double"; case LongDouble: return "long double"; case WChar: return "wchar_t"; case Overload: return "<overloaded function type>"; case Dependent: return "<dependent type>"; } } void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, arg_type_iterator ArgTys, unsigned NumArgs, bool isVariadic, unsigned TypeQuals) { ID.AddPointer(Result.getAsOpaquePtr()); for (unsigned i = 0; i != NumArgs; ++i) ID.AddPointer(ArgTys[i].getAsOpaquePtr()); ID.AddInteger(isVariadic); ID.AddInteger(TypeQuals); } void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getResultType(), arg_type_begin(), NumArgs, isVariadic(), getTypeQuals()); } void ObjCQualifiedInterfaceType::Profile(llvm::FoldingSetNodeID &ID, const ObjCInterfaceDecl *Decl, ObjCProtocolDecl **protocols, unsigned NumProtocols) { ID.AddPointer(Decl); for (unsigned i = 0; i != NumProtocols; i++) ID.AddPointer(protocols[i]); } void ObjCQualifiedInterfaceType::Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getDecl(), &Protocols[0], getNumProtocols()); } void ObjCQualifiedIdType::Profile(llvm::FoldingSetNodeID &ID, ObjCProtocolDecl **protocols, unsigned NumProtocols) { for (unsigned i = 0; i != NumProtocols; i++) ID.AddPointer(protocols[i]); } void ObjCQualifiedIdType::Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, &Protocols[0], getNumProtocols()); } /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to /// potentially looking through *all* consequtive typedefs. This returns the /// sum of the type qualifiers, so if you have: /// typedef const int A; /// typedef volatile A B; /// looking through the typedefs for B will give you "const volatile A". /// QualType TypedefType::LookThroughTypedefs() const { // Usually, there is only a single level of typedefs, be fast in that case. QualType FirstType = getDecl()->getUnderlyingType(); if (!isa<TypedefType>(FirstType)) return FirstType; // Otherwise, do the fully general loop. unsigned TypeQuals = 0; const TypedefType *TDT = this; while (1) { QualType CurType = TDT->getDecl()->getUnderlyingType(); /// FIXME: /// FIXME: This is incorrect for ExtQuals! /// FIXME: TypeQuals |= CurType.getCVRQualifiers(); TDT = dyn_cast<TypedefType>(CurType); if (TDT == 0) return QualType(CurType.getTypePtr(), TypeQuals); } } TypeOfExprType::TypeOfExprType(Expr *E, QualType can) : Type(TypeOfExpr, can, E->isTypeDependent()), TOExpr(E) { assert(!isa<TypedefType>(can) && "Invalid canonical type"); } bool RecordType::classof(const TagType *TT) { return isa<RecordDecl>(TT->getDecl()); } bool EnumType::classof(const TagType *TT) { return isa<EnumDecl>(TT->getDecl()); } bool TemplateSpecializationType:: anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) { for (unsigned Idx = 0; Idx < NumArgs; ++Idx) { switch (Args[Idx].getKind()) { case TemplateArgument::Type: if (Args[Idx].getAsType()->isDependentType()) return true; break; case TemplateArgument::Declaration: case TemplateArgument::Integral: // Never dependent break; case TemplateArgument::Expression: if (Args[Idx].getAsExpr()->isTypeDependent() || Args[Idx].getAsExpr()->isValueDependent()) return true; break; } } return false; } TemplateSpecializationType:: TemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon) : Type(TemplateSpecialization, Canon.isNull()? QualType(this, 0) : Canon, T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)), Template(T), NumArgs(NumArgs) { assert((!Canon.isNull() || T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) && "No canonical type for non-dependent class template specialization"); TemplateArgument *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1); for (unsigned Arg = 0; Arg < NumArgs; ++Arg) new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]); } void TemplateSpecializationType::Destroy(ASTContext& C) { for (unsigned Arg = 0; Arg < NumArgs; ++Arg) { // FIXME: Not all expressions get cloned, so we can't yet perform // this destruction. // if (Expr *E = getArg(Arg).getAsExpr()) // E->Destroy(C); } } TemplateSpecializationType::iterator TemplateSpecializationType::end() const { return begin() + getNumArgs(); } const TemplateArgument & TemplateSpecializationType::getArg(unsigned Idx) const { assert(Idx < getNumArgs() && "Template argument out of range"); return getArgs()[Idx]; } void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, TemplateName T, const TemplateArgument *Args, unsigned NumArgs) { T.Profile(ID); for (unsigned Idx = 0; Idx < NumArgs; ++Idx) Args[Idx].Profile(ID); } //===----------------------------------------------------------------------===// // Type Printing //===----------------------------------------------------------------------===// void QualType::dump(const char *msg) const { std::string R = "identifier"; getAsStringInternal(R); if (msg) fprintf(stderr, "%s: %s\n", msg, R.c_str()); else fprintf(stderr, "%s\n", R.c_str()); } void QualType::dump() const { dump(""); } void Type::dump() const { std::string S = "identifier"; getAsStringInternal(S); fprintf(stderr, "%s\n", S.c_str()); } static void AppendTypeQualList(std::string &S, unsigned TypeQuals) { // Note: funkiness to ensure we get a space only between quals. bool NonePrinted = true; if (TypeQuals & QualType::Const) S += "const", NonePrinted = false; if (TypeQuals & QualType::Volatile) S += (NonePrinted+" volatile"), NonePrinted = false; if (TypeQuals & QualType::Restrict) S += (NonePrinted+" restrict"), NonePrinted = false; } void QualType::getAsStringInternal(std::string &S) const { if (isNull()) { S += "NULL TYPE"; return; } // Print qualifiers as appropriate. if (unsigned Tq = getCVRQualifiers()) { std::string TQS; AppendTypeQualList(TQS, Tq); if (!S.empty()) S = TQS + ' ' + S; else S = TQS; } getTypePtr()->getAsStringInternal(S); } void BuiltinType::getAsStringInternal(std::string &S) const { if (S.empty()) { S = getName(); } else { // Prefix the basic type, e.g. 'int X'. S = ' ' + S; S = getName() + S; } } void FixedWidthIntType::getAsStringInternal(std::string &S) const { // FIXME: Once we get bitwidth attribute, write as // "int __attribute__((bitwidth(x)))". std::string prefix = "__clang_fixedwidth"; prefix += llvm::utostr_32(Width); prefix += (char)(Signed ? 'S' : 'U'); if (S.empty()) { S = prefix; } else { // Prefix the basic type, e.g. 'int X'. S = prefix + S; } } void ComplexType::getAsStringInternal(std::string &S) const { ElementType->getAsStringInternal(S); S = "_Complex " + S; } void ExtQualType::getAsStringInternal(std::string &S) const { bool NeedsSpace = false; if (AddressSpace) { S = "__attribute__((address_space("+llvm::utostr_32(AddressSpace)+")))" + S; NeedsSpace = true; } if (GCAttrType != QualType::GCNone) { if (NeedsSpace) S += ' '; S += "__attribute__((objc_gc("; if (GCAttrType == QualType::Weak) S += "weak"; else S += "strong"; S += ")))"; } BaseType->getAsStringInternal(S); } void PointerType::getAsStringInternal(std::string &S) const { S = '*' + S; // Handle things like 'int (*A)[4];' correctly. // FIXME: this should include vectors, but vectors use attributes I guess. if (isa<ArrayType>(getPointeeType())) S = '(' + S + ')'; getPointeeType().getAsStringInternal(S); } void BlockPointerType::getAsStringInternal(std::string &S) const { S = '^' + S; PointeeType.getAsStringInternal(S); } void LValueReferenceType::getAsStringInternal(std::string &S) const { S = '&' + S; // Handle things like 'int (&A)[4];' correctly. // FIXME: this should include vectors, but vectors use attributes I guess. if (isa<ArrayType>(getPointeeType())) S = '(' + S + ')'; getPointeeType().getAsStringInternal(S); } void RValueReferenceType::getAsStringInternal(std::string &S) const { S = "&&" + S; // Handle things like 'int (&&A)[4];' correctly. // FIXME: this should include vectors, but vectors use attributes I guess. if (isa<ArrayType>(getPointeeType())) S = '(' + S + ')'; getPointeeType().getAsStringInternal(S); } void MemberPointerType::getAsStringInternal(std::string &S) const { std::string C; Class->getAsStringInternal(C); C += "::*"; S = C + S; // Handle things like 'int (Cls::*A)[4];' correctly. // FIXME: this should include vectors, but vectors use attributes I guess. if (isa<ArrayType>(getPointeeType())) S = '(' + S + ')'; getPointeeType().getAsStringInternal(S); } void ConstantArrayType::getAsStringInternal(std::string &S) const { S += '['; S += llvm::utostr(getSize().getZExtValue()); S += ']'; getElementType().getAsStringInternal(S); } void IncompleteArrayType::getAsStringInternal(std::string &S) const { S += "[]"; getElementType().getAsStringInternal(S); } void VariableArrayType::getAsStringInternal(std::string &S) const { S += '['; if (getIndexTypeQualifier()) { AppendTypeQualList(S, getIndexTypeQualifier()); S += ' '; } if (getSizeModifier() == Static) S += "static"; else if (getSizeModifier() == Star) S += '*'; if (getSizeExpr()) { std::string SStr; llvm::raw_string_ostream s(SStr); getSizeExpr()->printPretty(s); S += s.str(); } S += ']'; getElementType().getAsStringInternal(S); } void DependentSizedArrayType::getAsStringInternal(std::string &S) const { S += '['; if (getIndexTypeQualifier()) { AppendTypeQualList(S, getIndexTypeQualifier()); S += ' '; } if (getSizeModifier() == Static) S += "static"; else if (getSizeModifier() == Star) S += '*'; if (getSizeExpr()) { std::string SStr; llvm::raw_string_ostream s(SStr); getSizeExpr()->printPretty(s); S += s.str(); } S += ']'; getElementType().getAsStringInternal(S); } void VectorType::getAsStringInternal(std::string &S) const { // FIXME: We prefer to print the size directly here, but have no way // to get the size of the type. S += " __attribute__((__vector_size__("; S += llvm::utostr_32(NumElements); // convert back to bytes. S += " * sizeof(" + ElementType.getAsString() + "))))"; ElementType.getAsStringInternal(S); } void ExtVectorType::getAsStringInternal(std::string &S) const { S += " __attribute__((ext_vector_type("; S += llvm::utostr_32(NumElements); S += ")))"; ElementType.getAsStringInternal(S); } void TypeOfExprType::getAsStringInternal(std::string &InnerString) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'typeof(e) X'. InnerString = ' ' + InnerString; std::string Str; llvm::raw_string_ostream s(Str); getUnderlyingExpr()->printPretty(s); InnerString = "typeof(" + s.str() + ")" + InnerString; } void TypeOfType::getAsStringInternal(std::string &InnerString) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'typeof(t) X'. InnerString = ' ' + InnerString; std::string Tmp; getUnderlyingType().getAsStringInternal(Tmp); InnerString = "typeof(" + Tmp + ")" + InnerString; } void FunctionNoProtoType::getAsStringInternal(std::string &S) const { // If needed for precedence reasons, wrap the inner part in grouping parens. if (!S.empty()) S = "(" + S + ")"; S += "()"; getResultType().getAsStringInternal(S); } void FunctionProtoType::getAsStringInternal(std::string &S) const { // If needed for precedence reasons, wrap the inner part in grouping parens. if (!S.empty()) S = "(" + S + ")"; S += "("; std::string Tmp; for (unsigned i = 0, e = getNumArgs(); i != e; ++i) { if (i) S += ", "; getArgType(i).getAsStringInternal(Tmp); S += Tmp; Tmp.clear(); } if (isVariadic()) { if (getNumArgs()) S += ", "; S += "..."; } else if (getNumArgs() == 0) { // Do not emit int() if we have a proto, emit 'int(void)'. S += "void"; } S += ")"; getResultType().getAsStringInternal(S); } void TypedefType::getAsStringInternal(std::string &InnerString) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'. InnerString = ' ' + InnerString; InnerString = getDecl()->getIdentifier()->getName() + InnerString; } void TemplateTypeParmType::getAsStringInternal(std::string &InnerString) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'parmname X'. InnerString = ' ' + InnerString; if (!Name) InnerString = "type-parameter-" + llvm::utostr_32(Depth) + '-' + llvm::utostr_32(Index) + InnerString; else InnerString = Name->getName() + InnerString; } std::string TemplateSpecializationType::PrintTemplateArgumentList( const TemplateArgument *Args, unsigned NumArgs) { std::string SpecString; SpecString += '<'; for (unsigned Arg = 0; Arg < NumArgs; ++Arg) { if (Arg) SpecString += ", "; // Print the argument into a string. std::string ArgString; switch (Args[Arg].getKind()) { case TemplateArgument::Type: Args[Arg].getAsType().getAsStringInternal(ArgString); break; case TemplateArgument::Declaration: ArgString = cast<NamedDecl>(Args[Arg].getAsDecl())->getNameAsString(); break; case TemplateArgument::Integral: ArgString = Args[Arg].getAsIntegral()->toString(10, true); break; case TemplateArgument::Expression: { llvm::raw_string_ostream s(ArgString); Args[Arg].getAsExpr()->printPretty(s); break; } } // If this is the first argument and its string representation // begins with the global scope specifier ('::foo'), add a space // to avoid printing the diagraph '<:'. if (!Arg && !ArgString.empty() && ArgString[0] == ':') SpecString += ' '; SpecString += ArgString; } // If the last character of our string is '>', add another space to // keep the two '>''s separate tokens. We don't *have* to do this in // C++0x, but it's still good hygiene. if (SpecString[SpecString.size() - 1] == '>') SpecString += ' '; SpecString += '>'; return SpecString; } void TemplateSpecializationType:: getAsStringInternal(std::string &InnerString) const { std::string SpecString; { llvm::raw_string_ostream OS(SpecString); Template.print(OS); } SpecString += PrintTemplateArgumentList(getArgs(), getNumArgs()); if (InnerString.empty()) InnerString.swap(SpecString); else InnerString = SpecString + ' ' + InnerString; } void QualifiedNameType::getAsStringInternal(std::string &InnerString) const { std::string MyString; { llvm::raw_string_ostream OS(MyString); NNS->print(OS); } std::string TypeStr; if (const TagType *TagT = dyn_cast<TagType>(NamedType.getTypePtr())) { // Suppress printing of 'enum', 'struct', 'union', or 'class'. TagT->getAsStringInternal(TypeStr, true); } else NamedType.getAsStringInternal(TypeStr); MyString += TypeStr; if (InnerString.empty()) InnerString.swap(MyString); else InnerString = MyString + ' ' + InnerString; } void TypenameType::getAsStringInternal(std::string &InnerString) const { std::string MyString; { llvm::raw_string_ostream OS(MyString); OS << "typename "; NNS->print(OS); if (const IdentifierInfo *Ident = getIdentifier()) OS << Ident->getName(); else if (const TemplateSpecializationType *Spec = getTemplateId()) { Spec->getTemplateName().print(OS, true); OS << TemplateSpecializationType::PrintTemplateArgumentList( Spec->getArgs(), Spec->getNumArgs()); } } if (InnerString.empty()) InnerString.swap(MyString); else InnerString = MyString + ' ' + InnerString; } void ObjCInterfaceType::getAsStringInternal(std::string &InnerString) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'. InnerString = ' ' + InnerString; InnerString = getDecl()->getIdentifier()->getName() + InnerString; } void ObjCQualifiedInterfaceType::getAsStringInternal( std::string &InnerString) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'. InnerString = ' ' + InnerString; std::string ObjCQIString = getDecl()->getNameAsString(); ObjCQIString += '<'; bool isFirst = true; for (qual_iterator I = qual_begin(), E = qual_end(); I != E; ++I) { if (isFirst) isFirst = false; else ObjCQIString += ','; ObjCQIString += (*I)->getNameAsString(); } ObjCQIString += '>'; InnerString = ObjCQIString + InnerString; } void ObjCQualifiedIdType::getAsStringInternal(std::string &InnerString) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'. InnerString = ' ' + InnerString; std::string ObjCQIString = "id"; ObjCQIString += '<'; int num = getNumProtocols(); for (int i = 0; i < num; i++) { ObjCQIString += getProtocols(i)->getNameAsString(); if (i < num-1) ObjCQIString += ','; } ObjCQIString += '>'; InnerString = ObjCQIString + InnerString; } void TagType::getAsStringInternal(std::string &InnerString) const { getAsStringInternal(InnerString, false); } void TagType::getAsStringInternal(std::string &InnerString, bool SuppressTagKind) const { if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'. InnerString = ' ' + InnerString; const char *Kind = SuppressTagKind? 0 : getDecl()->getKindName(); const char *ID; if (const IdentifierInfo *II = getDecl()->getIdentifier()) ID = II->getName(); else if (TypedefDecl *Typedef = getDecl()->getTypedefForAnonDecl()) { Kind = 0; assert(Typedef->getIdentifier() && "Typedef without identifier?"); ID = Typedef->getIdentifier()->getName(); } else ID = "<anonymous>"; // If this is a class template specialization, print the template // arguments. if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(getDecl())) { std::string TemplateArgs = TemplateSpecializationType::PrintTemplateArgumentList( Spec->getTemplateArgs(), Spec->getNumTemplateArgs()); InnerString = TemplateArgs + InnerString; } if (Kind) { // Compute the full nested-name-specifier for this type. In C, // this will always be empty. std::string ContextStr; for (DeclContext *DC = getDecl()->getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { std::string MyPart; if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) { if (NS->getIdentifier()) MyPart = NS->getNameAsString(); } else if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { std::string TemplateArgs = TemplateSpecializationType::PrintTemplateArgumentList( Spec->getTemplateArgs(), Spec->getNumTemplateArgs()); MyPart = Spec->getIdentifier()->getName() + TemplateArgs; } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) { if (TypedefDecl *Typedef = Tag->getTypedefForAnonDecl()) MyPart = Typedef->getIdentifier()->getName(); else if (Tag->getIdentifier()) MyPart = Tag->getIdentifier()->getName(); } if (!MyPart.empty()) ContextStr = MyPart + "::" + ContextStr; } InnerString = std::string(Kind) + " " + ContextStr + ID + InnerString; } else InnerString = ID + InnerString; } <file_sep>/test/CodeGen/merge-statics.c // RUN: clang-cc < %s -emit-llvm | grep internal | count 1 // The two decls for 'a' should merge into one llvm GlobalVariable. struct s { int x; }; static struct s a; struct s *ap1 = &a; static struct s a = { 10 }; <file_sep>/tools/ccc/test/ccc/phases.c // One C file. // RUN: touch %t.c && // RUN: xcc -ccc-host-system unknown -ccc-print-phases %t.c > %t && // RUN: grep '0: input, "%t.c", c' %t && // RUN: grep '1: preprocessor, {0}, cpp-output' %t && // RUN: grep '2: compiler, {1}, assembler' %t && // RUN: grep '3: assembler, {2}, object' %t && // RUN: grep '4: linker, {3}, image' %t && // PCH. // RUN: touch %t.h && // RUN: xcc -ccc-host-system unknown -ccc-print-phases -x c-header %t.h > %t && // RUN: grep '0: input, "%t.h", c-header' %t && // RUN: grep '1: preprocessor, {0}, c-header-cpp-output' %t && // RUN: grep '2: precompiler, {1}, precompiled-header' %t && // Assembler w/ and w/o preprocessor. // RUN: touch %t.s && // RUN: xcc -ccc-host-system unknown -ccc-print-phases -x assembler %t.s > %t && // RUN: grep '0: input, "%t.s", assembler' %t && // RUN: grep '1: assembler, {0}, object' %t && // RUN: grep '2: linker, {1}, image' %t && // RUN: xcc -ccc-host-system unknown -ccc-print-phases -x assembler-with-cpp %t.s > %t && // RUN: grep '0: input, "%t.s", assembler-with-cpp' %t && // RUN: grep '1: preprocessor, {0}, assembler' %t && // RUN: grep '2: assembler, {1}, object' %t && // RUN: grep '3: linker, {2}, image' %t && // Check the various ways of early termination. // RUN: xcc -ccc-host-system unknown -ccc-print-phases -E %s > %t && // RUN: not grep ': compiler, ' %t && // RUN: xcc -ccc-host-system unknown -ccc-print-phases -fsyntax-only %s > %t && // RUN: grep ': syntax-only, {1}, nothing' %t && // RUN: not grep ': assembler, ' %t && // RUN: xcc -ccc-host-system unknown -ccc-print-phases -S %s > %t && // RUN: not grep ': assembler, ' %t && // RUN: xcc -ccc-host-system unknown -ccc-print-phases -c %s > %t && // RUN: not grep ': linker, ' %t && // Multiple output files. // RUN: touch %t.1.c && // RUN: touch %t.2.c && // RUN: xcc -ccc-host-system unknown -ccc-print-phases -c %t.1.c %t.2.c > %t && // RUN: grep ': assembler,' %t | count 2 && // FIXME: Only for darwin. // Treat -filelist as a linker input. // RUN: xcc -ccc-host-system unknown -ccc-print-phases -filelist /dev/null > %t && // RUN: grep '1: linker, {0}, image' %t && // RUN: true <file_sep>/include/clang/Analysis/PathSensitive/GRState.h //== GRState*h - Path-Sens. "State" for tracking valuues -----*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines SymbolRef, ExprBindKey, and GRState* // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_VALUESTATE_H #define LLVM_CLANG_ANALYSIS_VALUESTATE_H // FIXME: Reduce the number of includes. #include "clang/Analysis/PathSensitive/Environment.h" #include "clang/Analysis/PathSensitive/Store.h" #include "clang/Analysis/PathSensitive/ConstraintManager.h" #include "clang/Analysis/PathSensitive/ValueManager.h" #include "clang/Analysis/PathSensitive/GRCoreEngine.h" #include "clang/AST/Expr.h" #include "clang/AST/Decl.h" #include "clang/AST/ASTContext.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "llvm/Support/Casting.h" #include "llvm/Support/DataTypes.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Streams.h" #include <functional> namespace clang { class GRStateManager; class GRTransferFuncs; typedef ConstraintManager* (*ConstraintManagerCreator)(GRStateManager&); typedef StoreManager* (*StoreManagerCreator)(GRStateManager&); //===----------------------------------------------------------------------===// // GRStateTrait - Traits used by the Generic Data Map of a GRState. //===----------------------------------------------------------------------===// template <typename T> struct GRStatePartialTrait; template <typename T> struct GRStateTrait { typedef typename T::data_type data_type; static inline void* GDMIndex() { return &T::TagInt; } static inline void* MakeVoidPtr(data_type D) { return (void*) D; } static inline data_type MakeData(void* const* P) { return P ? (data_type) *P : (data_type) 0; } }; //===----------------------------------------------------------------------===// // GRState- An ImmutableMap type Stmt*/Decl*/Symbols to SVals. //===----------------------------------------------------------------------===// /// GRState - This class encapsulates the actual data values for /// for a "state" in our symbolic value tracking. It is intended to be /// used as a functional object; that is once it is created and made /// "persistent" in a FoldingSet its values will never change. class GRState : public llvm::FoldingSetNode { public: // Typedefs. typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy; typedef llvm::ImmutableMap<void*, void*> GenericDataMap; typedef GRStateManager ManagerTy; private: void operator=(const GRState& R) const; friend class GRStateManager; Environment Env; Store St; // FIXME: Make these private. public: GenericDataMap GDM; public: /// This ctor is used when creating the first GRState object. GRState(const Environment& env, Store st, GenericDataMap gdm) : Env(env), St(st), GDM(gdm) {} /// Copy ctor - We must explicitly define this or else the "Next" ptr /// in FoldingSetNode will also get copied. GRState(const GRState& RHS) : llvm::FoldingSetNode(), Env(RHS.Env), St(RHS.St), GDM(RHS.GDM) {} /// getEnvironment - Return the environment associated with this state. /// The environment is the mapping from expressions to values. const Environment& getEnvironment() const { return Env; } /// getStore - Return the store associated with this state. The store /// is a mapping from locations to values. Store getStore() const { return St; } /// getGDM - Return the generic data map associated with this state. GenericDataMap getGDM() const { return GDM; } /// Profile - Profile the contents of a GRState object for use /// in a FoldingSet. static void Profile(llvm::FoldingSetNodeID& ID, const GRState* V) { V->Env.Profile(ID); ID.AddPointer(V->St); V->GDM.Profile(ID); } /// Profile - Used to profile the contents of this object for inclusion /// in a FoldingSet. void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, this); } SVal LookupExpr(Expr* E) const { return Env.LookupExpr(E); } // Iterators. typedef Environment::seb_iterator seb_iterator; seb_iterator seb_begin() const { return Env.seb_begin(); } seb_iterator seb_end() const { return Env.beb_end(); } typedef Environment::beb_iterator beb_iterator; beb_iterator beb_begin() const { return Env.beb_begin(); } beb_iterator beb_end() const { return Env.beb_end(); } // Trait based GDM dispatch. void* const* FindGDM(void* K) const; template <typename T> typename GRStateTrait<T>::data_type get() const { return GRStateTrait<T>::MakeData(FindGDM(GRStateTrait<T>::GDMIndex())); } template<typename T> typename GRStateTrait<T>::lookup_type get(typename GRStateTrait<T>::key_type key) const { void* const* d = FindGDM(GRStateTrait<T>::GDMIndex()); return GRStateTrait<T>::Lookup(GRStateTrait<T>::MakeData(d), key); } template<typename T> bool contains(typename GRStateTrait<T>::key_type key) const { void* const* d = FindGDM(GRStateTrait<T>::GDMIndex()); return GRStateTrait<T>::Contains(GRStateTrait<T>::MakeData(d), key); } // State pretty-printing. class Printer { public: virtual ~Printer() {} virtual void Print(std::ostream& Out, const GRState* state, const char* nl, const char* sep) = 0; }; void print(std::ostream& Out, StoreManager& StoreMgr, ConstraintManager& ConstraintMgr, Printer **Beg = 0, Printer **End = 0, const char* nl = "\n", const char *sep = "") const; // Tags used for the Generic Data Map. struct NullDerefTag { static int TagInt; typedef const SVal* data_type; }; }; template<> struct GRTrait<GRState*> { static inline void* toPtr(GRState* St) { return (void*) St; } static inline GRState* toState(void* P) { return (GRState*) P; } static inline void Profile(llvm::FoldingSetNodeID& profile, GRState* St) { // At this point states have already been uniqued. Just // add the pointer. profile.AddPointer(St); } }; class GRStateSet { typedef llvm::SmallPtrSet<const GRState*,5> ImplTy; ImplTy Impl; public: GRStateSet() {} inline void Add(const GRState* St) { Impl.insert(St); } typedef ImplTy::const_iterator iterator; inline unsigned size() const { return Impl.size(); } inline bool empty() const { return Impl.empty(); } inline iterator begin() const { return Impl.begin(); } inline iterator end() const { return Impl.end(); } class AutoPopulate { GRStateSet& S; unsigned StartSize; const GRState* St; public: AutoPopulate(GRStateSet& s, const GRState* st) : S(s), StartSize(S.size()), St(st) {} ~AutoPopulate() { if (StartSize == S.size()) S.Add(St); } }; }; //===----------------------------------------------------------------------===// // GRStateManager - Factory object for GRStates. //===----------------------------------------------------------------------===// class GRStateRef; class GRStateManager { friend class GRExprEngine; friend class GRStateRef; private: EnvironmentManager EnvMgr; llvm::OwningPtr<StoreManager> StoreMgr; llvm::OwningPtr<ConstraintManager> ConstraintMgr; GRState::IntSetTy::Factory ISetFactory; GRState::GenericDataMap::Factory GDMFactory; typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy; GDMContextsTy GDMContexts; /// Printers - A set of printer objects used for pretty-printing a GRState. /// GRStateManager owns these objects. std::vector<GRState::Printer*> Printers; /// StateSet - FoldingSet containing all the states created for analyzing /// a particular function. This is used to unique states. llvm::FoldingSet<GRState> StateSet; /// ValueMgr - Object that manages the data for all created SVals. ValueManager ValueMgr; /// Alloc - A BumpPtrAllocator to allocate states. llvm::BumpPtrAllocator& Alloc; /// CurrentStmt - The block-level statement currently being visited. This /// is set by GRExprEngine. Stmt* CurrentStmt; /// cfg - The CFG for the analyzed function/method. CFG& cfg; /// codedecl - The Decl representing the function/method being analyzed. const Decl& codedecl; /// TF - Object that represents a bundle of transfer functions /// for manipulating and creating SVals. GRTransferFuncs* TF; /// Liveness - live-variables information of the ValueDecl* and block-level /// Expr* in the CFG. Used to get initial store and prune out dead state. LiveVariables& Liveness; private: Environment RemoveBlkExpr(const Environment& Env, Expr* E) { return EnvMgr.RemoveBlkExpr(Env, E); } // FIXME: Remove when we do lazy initializaton of variable bindings. // const GRState* BindVar(const GRState* St, VarDecl* D, SVal V) { // return SetSVal(St, getLoc(D), V); // } public: GRStateManager(ASTContext& Ctx, StoreManagerCreator CreateStoreManager, ConstraintManagerCreator CreateConstraintManager, llvm::BumpPtrAllocator& alloc, CFG& c, const Decl& cd, LiveVariables& L) : EnvMgr(alloc), ISetFactory(alloc), GDMFactory(alloc), ValueMgr(alloc, Ctx), Alloc(alloc), cfg(c), codedecl(cd), Liveness(L) { StoreMgr.reset((*CreateStoreManager)(*this)); ConstraintMgr.reset((*CreateConstraintManager)(*this)); } ~GRStateManager(); const GRState* getInitialState(); ASTContext &getContext() { return ValueMgr.getContext(); } const ASTContext &getContext() const { return ValueMgr.getContext(); } const Decl &getCodeDecl() { return codedecl; } GRTransferFuncs& getTransferFuncs() { return *TF; } BasicValueFactory &getBasicVals() { return ValueMgr.getBasicValueFactory(); } const BasicValueFactory& getBasicVals() const { return ValueMgr.getBasicValueFactory(); } SymbolManager &getSymbolManager() { return ValueMgr.getSymbolManager(); } const SymbolManager &getSymbolManager() const { return ValueMgr.getSymbolManager(); } ValueManager &getValueManager() { return ValueMgr; } const ValueManager &getValueManager() const { return ValueMgr; } LiveVariables& getLiveVariables() { return Liveness; } llvm::BumpPtrAllocator& getAllocator() { return Alloc; } MemRegionManager& getRegionManager() { return ValueMgr.getRegionManager(); } const MemRegionManager& getRegionManager() const { return ValueMgr.getRegionManager(); } StoreManager& getStoreManager() { return *StoreMgr; } ConstraintManager& getConstraintManager() { return *ConstraintMgr; } const GRState* BindDecl(const GRState* St, const VarDecl* VD, SVal IVal) { // Store manager should return a persistent state. return StoreMgr->BindDecl(St, VD, IVal); } const GRState* BindDeclWithNoInit(const GRState* St, const VarDecl* VD) { // Store manager should return a persistent state. return StoreMgr->BindDeclWithNoInit(St, VD); } /// BindCompoundLiteral - Return the state that has the bindings currently /// in 'state' plus the bindings for the CompoundLiteral. 'R' is the region /// for the compound literal and 'BegInit' and 'EndInit' represent an /// array of initializer values. const GRState* BindCompoundLiteral(const GRState* St, const CompoundLiteralExpr* CL, SVal V) { return StoreMgr->BindCompoundLiteral(St, CL, V); } const GRState* RemoveDeadBindings(const GRState* St, Stmt* Loc, SymbolReaper& SymReaper); const GRState* RemoveSubExprBindings(const GRState* St) { GRState NewSt = *St; NewSt.Env = EnvMgr.RemoveSubExprBindings(NewSt.Env); return getPersistentState(NewSt); } // Utility methods for getting regions. VarRegion* getRegion(const VarDecl* D) { return getRegionManager().getVarRegion(D); } const MemRegion* getSelfRegion(const GRState* state) { return StoreMgr->getSelfRegion(state->getStore()); } // Get the lvalue for a variable reference. SVal GetLValue(const GRState* St, const VarDecl* D) { return StoreMgr->getLValueVar(St, D); } // Get the lvalue for a StringLiteral. SVal GetLValue(const GRState* St, const StringLiteral* E) { return StoreMgr->getLValueString(St, E); } SVal GetLValue(const GRState* St, const CompoundLiteralExpr* CL) { return StoreMgr->getLValueCompoundLiteral(St, CL); } // Get the lvalue for an ivar reference. SVal GetLValue(const GRState* St, const ObjCIvarDecl* D, SVal Base) { return StoreMgr->getLValueIvar(St, D, Base); } // Get the lvalue for a field reference. SVal GetLValue(const GRState* St, SVal Base, const FieldDecl* D) { return StoreMgr->getLValueField(St, Base, D); } // Get the lvalue for an array index. SVal GetLValue(const GRState* St, SVal Base, SVal Idx) { return StoreMgr->getLValueElement(St, Base, Idx); } // Methods that query & manipulate the Environment. SVal GetSVal(const GRState* St, Stmt* Ex) { return St->getEnvironment().GetSVal(Ex, getBasicVals()); } SVal GetSValAsScalarOrLoc(const GRState* state, const Stmt *S) { if (const Expr *Ex = dyn_cast<Expr>(S)) { QualType T = Ex->getType(); if (Loc::IsLocType(T) || T->isIntegerType()) return GetSVal(state, S); } return UnknownVal(); } SVal GetSVal(const GRState* St, const Stmt* Ex) { return St->getEnvironment().GetSVal(const_cast<Stmt*>(Ex), getBasicVals()); } SVal GetBlkExprSVal(const GRState* St, Stmt* Ex) { return St->getEnvironment().GetBlkExprSVal(Ex, getBasicVals()); } const GRState* BindExpr(const GRState* St, Stmt* Ex, SVal V, bool isBlkExpr, bool Invalidate) { const Environment& OldEnv = St->getEnvironment(); Environment NewEnv = EnvMgr.BindExpr(OldEnv, Ex, V, isBlkExpr, Invalidate); if (NewEnv == OldEnv) return St; GRState NewSt = *St; NewSt.Env = NewEnv; return getPersistentState(NewSt); } const GRState* BindExpr(const GRState* St, Stmt* Ex, SVal V, bool Invalidate = true) { bool isBlkExpr = false; if (Ex == CurrentStmt) { // FIXME: Should this just be an assertion? When would we want to set // the value of a block-level expression if it wasn't CurrentStmt? isBlkExpr = cfg.isBlkExpr(Ex); if (!isBlkExpr) return St; } return BindExpr(St, Ex, V, isBlkExpr, Invalidate); } SVal ArrayToPointer(Loc Array) { return StoreMgr->ArrayToPointer(Array); } // Methods that manipulate the GDM. const GRState* addGDM(const GRState* St, void* Key, void* Data); // Methods that query or create regions. bool hasStackStorage(const MemRegion* R) { return getRegionManager().hasStackStorage(R); } // Methods that query & manipulate the Store. void iterBindings(const GRState* state, StoreManager::BindingsHandler& F) { StoreMgr->iterBindings(state->getStore(), F); } SVal GetSVal(const GRState* state, Loc LV, QualType T = QualType()) { return StoreMgr->Retrieve(state, LV, T); } SVal GetSVal(const GRState* state, const MemRegion* R) { return StoreMgr->Retrieve(state, loc::MemRegionVal(R)); } SVal GetSValAsScalarOrLoc(const GRState* state, const MemRegion *R) { // We only want to do fetches from regions that we can actually bind // values. For example, SymbolicRegions of type 'id<...>' cannot // have direct bindings (but their can be bindings on their subregions). if (!R->isBoundable(getContext())) return UnknownVal(); if (const TypedRegion *TR = dyn_cast<TypedRegion>(R)) { QualType T = TR->getRValueType(getContext()); if (Loc::IsLocType(T) || T->isIntegerType()) return GetSVal(state, R); } return UnknownVal(); } const GRState* BindLoc(const GRState* St, Loc LV, SVal V) { return StoreMgr->Bind(St, LV, V); } void Unbind(GRState& St, Loc LV) { St.St = StoreMgr->Remove(St.St, LV); } const GRState* Unbind(const GRState* St, Loc LV); const GRState* getPersistentState(GRState& Impl); // MakeStateWithStore - get a persistent state with the new store. const GRState* MakeStateWithStore(const GRState* St, Store store); bool isEqual(const GRState* state, Expr* Ex, const llvm::APSInt& V); bool isEqual(const GRState* state, Expr* Ex, uint64_t); //==---------------------------------------------------------------------==// // Generic Data Map methods. //==---------------------------------------------------------------------==// // // GRStateManager and GRState support a "generic data map" that allows // different clients of GRState objects to embed arbitrary data within a // GRState object. The generic data map is essentially an immutable map // from a "tag" (that acts as the "key" for a client) and opaque values. // Tags/keys and values are simply void* values. The typical way that clients // generate unique tags are by taking the address of a static variable. // Clients are responsible for ensuring that data values referred to by a // the data pointer are immutable (and thus are essentially purely functional // data). // // The templated methods below use the GRStateTrait<T> class // to resolve keys into the GDM and to return data values to clients. // // Trait based GDM dispatch. template <typename T> const GRState* set(const GRState* st, typename GRStateTrait<T>::data_type D) { return addGDM(st, GRStateTrait<T>::GDMIndex(), GRStateTrait<T>::MakeVoidPtr(D)); } template<typename T> const GRState* set(const GRState* st, typename GRStateTrait<T>::key_type K, typename GRStateTrait<T>::value_type V, typename GRStateTrait<T>::context_type C) { return addGDM(st, GRStateTrait<T>::GDMIndex(), GRStateTrait<T>::MakeVoidPtr(GRStateTrait<T>::Set(st->get<T>(), K, V, C))); } template <typename T> const GRState* add(const GRState* st, typename GRStateTrait<T>::key_type K, typename GRStateTrait<T>::context_type C) { return addGDM(st, GRStateTrait<T>::GDMIndex(), GRStateTrait<T>::MakeVoidPtr(GRStateTrait<T>::Add(st->get<T>(), K, C))); } template <typename T> const GRState* remove(const GRState* st, typename GRStateTrait<T>::key_type K, typename GRStateTrait<T>::context_type C) { return addGDM(st, GRStateTrait<T>::GDMIndex(), GRStateTrait<T>::MakeVoidPtr(GRStateTrait<T>::Remove(st->get<T>(), K, C))); } void* FindGDMContext(void* index, void* (*CreateContext)(llvm::BumpPtrAllocator&), void (*DeleteContext)(void*)); template <typename T> typename GRStateTrait<T>::context_type get_context() { void* p = FindGDMContext(GRStateTrait<T>::GDMIndex(), GRStateTrait<T>::CreateContext, GRStateTrait<T>::DeleteContext); return GRStateTrait<T>::MakeContext(p); } //==---------------------------------------------------------------------==// // Constraints on values. //==---------------------------------------------------------------------==// // // Each GRState records constraints on symbolic values. These constraints // are managed using the ConstraintManager associated with a GRStateManager. // As constraints gradually accrue on symbolic values, added constraints // may conflict and indicate that a state is infeasible (as no real values // could satisfy all the constraints). This is the principal mechanism // for modeling path-sensitivity in GRExprEngine/GRState. // // Various "Assume" methods form the interface for adding constraints to // symbolic values. A call to "Assume" indicates an assumption being placed // on one or symbolic values. Assume methods take the following inputs: // // (1) A GRState object representing the current state. // // (2) The assumed constraint (which is specific to a given "Assume" method). // // (3) A binary value "Assumption" that indicates whether the constraint is // assumed to be true or false. // // The output of "Assume" are two values: // // (a) "isFeasible" is set to true or false to indicate whether or not // the assumption is feasible. // // (b) A new GRState object with the added constraints. // // FIXME: (a) should probably disappear since it is redundant with (b). // (i.e., (b) could just be set to NULL). // const GRState* Assume(const GRState* St, SVal Cond, bool Assumption, bool& isFeasible) { return ConstraintMgr->Assume(St, Cond, Assumption, isFeasible); } const GRState* AssumeInBound(const GRState* St, SVal Idx, SVal UpperBound, bool Assumption, bool& isFeasible) { return ConstraintMgr->AssumeInBound(St, Idx, UpperBound, Assumption, isFeasible); } const llvm::APSInt* getSymVal(const GRState* St, SymbolRef sym) { return ConstraintMgr->getSymVal(St, sym); } void EndPath(const GRState* St) { ConstraintMgr->EndPath(St); } bool scanReachableSymbols(SVal val, const GRState* state, SymbolVisitor& visitor); }; //===----------------------------------------------------------------------===// // GRStateRef - A "fat" reference to GRState that also bundles GRStateManager. //===----------------------------------------------------------------------===// class GRStateRef { const GRState* St; GRStateManager* Mgr; public: GRStateRef(const GRState* st, GRStateManager& mgr) : St(st), Mgr(&mgr) {} const GRState* getState() const { return St; } operator const GRState*() const { return St; } GRStateManager& getManager() const { return *Mgr; } SVal GetSVal(Expr* Ex) { return Mgr->GetSVal(St, Ex); } SVal GetBlkExprSVal(Expr* Ex) { return Mgr->GetBlkExprSVal(St, Ex); } SVal GetSValAsScalarOrLoc(const Expr *Ex) { return Mgr->GetSValAsScalarOrLoc(St, Ex); } SVal GetSVal(Loc LV, QualType T = QualType()) { return Mgr->GetSVal(St, LV, T); } SVal GetSVal(const MemRegion* R) { return Mgr->GetSVal(St, R); } SVal GetSValAsScalarOrLoc(const MemRegion *R) { return Mgr->GetSValAsScalarOrLoc(St, R); } GRStateRef BindExpr(Stmt* Ex, SVal V, bool isBlkExpr, bool Invalidate) { return GRStateRef(Mgr->BindExpr(St, Ex, V, isBlkExpr, Invalidate), *Mgr); } GRStateRef BindExpr(Stmt* Ex, SVal V, bool Invalidate = true) { return GRStateRef(Mgr->BindExpr(St, Ex, V, Invalidate), *Mgr); } GRStateRef BindDecl(const VarDecl* VD, SVal InitVal) { return GRStateRef(Mgr->BindDecl(St, VD, InitVal), *Mgr); } GRStateRef BindLoc(Loc LV, SVal V) { return GRStateRef(Mgr->BindLoc(St, LV, V), *Mgr); } GRStateRef BindLoc(SVal LV, SVal V) { if (!isa<Loc>(LV)) return *this; return BindLoc(cast<Loc>(LV), V); } GRStateRef Unbind(Loc LV) { return GRStateRef(Mgr->Unbind(St, LV), *Mgr); } // Trait based GDM dispatch. template<typename T> typename GRStateTrait<T>::data_type get() const { return St->get<T>(); } template<typename T> typename GRStateTrait<T>::lookup_type get(typename GRStateTrait<T>::key_type key) const { return St->get<T>(key); } template<typename T> GRStateRef set(typename GRStateTrait<T>::data_type D) { return GRStateRef(Mgr->set<T>(St, D), *Mgr); } template <typename T> typename GRStateTrait<T>::context_type get_context() { return Mgr->get_context<T>(); } template<typename T> GRStateRef set(typename GRStateTrait<T>::key_type K, typename GRStateTrait<T>::value_type E, typename GRStateTrait<T>::context_type C) { return GRStateRef(Mgr->set<T>(St, K, E, C), *Mgr); } template<typename T> GRStateRef set(typename GRStateTrait<T>::key_type K, typename GRStateTrait<T>::value_type E) { return GRStateRef(Mgr->set<T>(St, K, E, get_context<T>()), *Mgr); } template<typename T> GRStateRef add(typename GRStateTrait<T>::key_type K) { return GRStateRef(Mgr->add<T>(St, K, get_context<T>()), *Mgr); } template<typename T> GRStateRef remove(typename GRStateTrait<T>::key_type K, typename GRStateTrait<T>::context_type C) { return GRStateRef(Mgr->remove<T>(St, K, C), *Mgr); } template<typename T> GRStateRef remove(typename GRStateTrait<T>::key_type K) { return GRStateRef(Mgr->remove<T>(St, K, get_context<T>()), *Mgr); } template<typename T> bool contains(typename GRStateTrait<T>::key_type key) const { return St->contains<T>(key); } // Lvalue methods. SVal GetLValue(const VarDecl* VD) { return Mgr->GetLValue(St, VD); } GRStateRef Assume(SVal Cond, bool Assumption, bool& isFeasible) { return GRStateRef(Mgr->Assume(St, Cond, Assumption, isFeasible), *Mgr); } template <typename CB> CB scanReachableSymbols(SVal val) { CB cb(*this); Mgr->scanReachableSymbols(val, St, cb); return cb; } SymbolManager& getSymbolManager() { return Mgr->getSymbolManager(); } BasicValueFactory& getBasicVals() { return Mgr->getBasicVals(); } // Pretty-printing. void print(std::ostream& Out, const char* nl = "\n", const char *sep = "") const; void printStdErr() const; void printDOT(std::ostream& Out) const; }; } // end clang namespace #endif <file_sep>/tools/clang-cc/ASTConsumers.cpp //===--- ASTConsumers.cpp - ASTConsumer implementations -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // AST Consumer Implementations. // //===----------------------------------------------------------------------===// #include "ASTConsumers.h" #include "clang/Frontend/PathDiagnosticClients.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/FileManager.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/CodeGen/ModuleBuilder.h" #include "llvm/Module.h" #include "llvm/Support/Streams.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" using namespace clang; //===----------------------------------------------------------------------===// /// DeclPrinter - Utility class for printing top-level decls. namespace { class DeclPrinter { public: llvm::raw_ostream& Out; unsigned Indentation; DeclPrinter(llvm::raw_ostream* out) : Out(out ? *out : llvm::errs()), Indentation(0) {} DeclPrinter() : Out(llvm::errs()), Indentation(0) {} virtual ~DeclPrinter(); void ChangeIndent(int I) { Indentation += I; } llvm::raw_ostream& Indent() { for (unsigned i = 0; i < Indentation; ++i) Out << " "; return Out; } void PrintDecl(Decl *D); void Print(NamedDecl *ND); void Print(NamespaceDecl *NS); void PrintFunctionDeclStart(FunctionDecl *FD); void PrintTypeDefDecl(TypedefDecl *TD); void PrintLinkageSpec(LinkageSpecDecl *LS); void PrintObjCMethodDecl(ObjCMethodDecl *OMD); void PrintObjCImplementationDecl(ObjCImplementationDecl *OID); void PrintObjCInterfaceDecl(ObjCInterfaceDecl *OID); void PrintObjCProtocolDecl(ObjCProtocolDecl *PID); void PrintObjCCategoryImplDecl(ObjCCategoryImplDecl *PID); void PrintObjCCategoryDecl(ObjCCategoryDecl *PID); void PrintObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID); void PrintObjCPropertyDecl(ObjCPropertyDecl *PD); void PrintObjCPropertyImplDecl(ObjCPropertyImplDecl *PID); void PrintTemplateDecl(TemplateDecl *TD); }; } // end anonymous namespace DeclPrinter::~DeclPrinter() { Out.flush(); } void DeclPrinter:: PrintDecl(Decl *D) { Indent(); if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { PrintFunctionDeclStart(FD); if (FD->getBody()) { Out << ' '; FD->getBody()->printPretty(Out, 0, Indentation, true); Out << '\n'; } } else if (isa<ObjCMethodDecl>(D)) { // Do nothing, methods definitions are printed in // PrintObjCImplementationDecl. } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { PrintTypeDefDecl(TD); } else if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(D)) { PrintObjCInterfaceDecl(OID); } else if (ObjCProtocolDecl *PID = dyn_cast<ObjCProtocolDecl>(D)) { PrintObjCProtocolDecl(PID); } else if (ObjCForwardProtocolDecl *OFPD = dyn_cast<ObjCForwardProtocolDecl>(D)) { Out << "@protocol "; for (ObjCForwardProtocolDecl::iterator I = OFPD->begin(), E = OFPD->end(); I != E; ++I) { if (I != OFPD->begin()) Out << ", "; Out << (*I)->getNameAsString(); } Out << ";\n"; } else if (ObjCImplementationDecl *OID = dyn_cast<ObjCImplementationDecl>(D)) { PrintObjCImplementationDecl(OID); } else if (ObjCCategoryImplDecl *OID = dyn_cast<ObjCCategoryImplDecl>(D)) { PrintObjCCategoryImplDecl(OID); } else if (ObjCCategoryDecl *OID = dyn_cast<ObjCCategoryDecl>(D)) { PrintObjCCategoryDecl(OID); } else if (ObjCCompatibleAliasDecl *OID = dyn_cast<ObjCCompatibleAliasDecl>(D)) { PrintObjCCompatibleAliasDecl(OID); } else if (ObjCClassDecl *OFCD = dyn_cast<ObjCClassDecl>(D)) { Out << "@class "; for (ObjCClassDecl::iterator I = OFCD->begin(), E = OFCD->end(); I != E; ++I) { if (I != OFCD->begin()) Out << ", "; Out << (*I)->getNameAsString(); } Out << ";\n"; } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { Out << "enum " << ED->getNameAsString() << " {\n"; // FIXME: Shouldn't pass a NULL context ASTContext *Context = 0; for (EnumDecl::enumerator_iterator E = ED->enumerator_begin(*Context), EEnd = ED->enumerator_end(*Context); E != EEnd; ++E) Out << " " << (*E)->getNameAsString() << ",\n"; Out << "};\n"; } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { // print a free standing tag decl (e.g. "struct x;"). Out << TD->getKindName(); Out << " "; if (const IdentifierInfo *II = TD->getIdentifier()) Out << II->getName(); Out << " {\n"; ChangeIndent(1); // FIXME: Shouldn't pass a NULL context ASTContext *Context = 0; for (DeclContext::decl_iterator i = TD->decls_begin(*Context); i != TD->decls_end(*Context); ++i) PrintDecl(*i); ChangeIndent(-1); Indent(); Out << "}"; Out << "\n"; } else if (TemplateDecl *TempD = dyn_cast<TemplateDecl>(D)) { PrintTemplateDecl(TempD); } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) { PrintLinkageSpec(LSD); } else if (FileScopeAsmDecl *AD = dyn_cast<FileScopeAsmDecl>(D)) { Out << "asm("; AD->getAsmString()->printPretty(Out); Out << ")\n"; } else if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) { Print(ND); } else { assert(0 && "Unknown decl type!"); } } void DeclPrinter::Print(NamedDecl *ND) { switch (ND->getKind()) { default: // FIXME: Handle the rest of the NamedDecls. Out << "### NamedDecl " << ND->getNameAsString() << "\n"; break; case Decl::Field: case Decl::Var: { // Emit storage class for vardecls. if (VarDecl *V = dyn_cast<VarDecl>(ND)) { switch (V->getStorageClass()) { default: assert(0 && "Unknown storage class!"); case VarDecl::None: break; case VarDecl::Auto: Out << "auto "; break; case VarDecl::Register: Out << "register "; break; case VarDecl::Extern: Out << "extern "; break; case VarDecl::Static: Out << "static "; break; case VarDecl::PrivateExtern: Out << "__private_extern__ "; break; } } std::string Name = ND->getNameAsString(); // This forms: "int a". dyn_cast<ValueDecl>(ND)->getType().getAsStringInternal(Name); Out << Name; if (VarDecl *Var = dyn_cast<VarDecl>(ND)) { if (Var->getInit()) { Out << " = "; Var->getInit()->printPretty(Out); } } Out << ";\n"; break; } case Decl::Namespace: Print(dyn_cast<NamespaceDecl>(ND)); break; } } void DeclPrinter::Print(NamespaceDecl *NS) { Out << "namespace " << NS->getNameAsString() << " {\n"; ChangeIndent(1); // FIXME: Shouldn't pass a NULL context ASTContext *Context = 0; for (DeclContext::decl_iterator i = NS->decls_begin(*Context); i != NS->decls_end(*Context); ++i) PrintDecl(*i); ChangeIndent(-1); Indent(); Out << "}\n"; } void DeclPrinter::PrintFunctionDeclStart(FunctionDecl *FD) { bool HasBody = FD->getBody(); Out << '\n'; Indent(); switch (FD->getStorageClass()) { default: assert(0 && "Unknown storage class"); case FunctionDecl::None: break; case FunctionDecl::Extern: Out << "extern "; break; case FunctionDecl::Static: Out << "static "; break; case FunctionDecl::PrivateExtern: Out << "__private_extern__ "; break; } if (FD->isInline()) Out << "inline "; std::string Proto = FD->getNameAsString(); const FunctionType *AFT = FD->getType()->getAsFunctionType(); if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT)) { Proto += "("; for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { if (i) Proto += ", "; std::string ParamStr; if (HasBody) ParamStr = FD->getParamDecl(i)->getNameAsString(); FT->getArgType(i).getAsStringInternal(ParamStr); Proto += ParamStr; } if (FT->isVariadic()) { if (FD->getNumParams()) Proto += ", "; Proto += "..."; } Proto += ")"; } else { assert(isa<FunctionNoProtoType>(AFT)); Proto += "()"; } AFT->getResultType().getAsStringInternal(Proto); Out << Proto; if (!FD->getBody()) Out << ";\n"; // Doesn't print the body. } void DeclPrinter::PrintTypeDefDecl(TypedefDecl *TD) { std::string S = TD->getNameAsString(); TD->getUnderlyingType().getAsStringInternal(S); Out << "typedef " << S << ";\n"; } void DeclPrinter::PrintLinkageSpec(LinkageSpecDecl *LS) { const char *l; if (LS->getLanguage() == LinkageSpecDecl::lang_c) l = "C"; else { assert(LS->getLanguage() == LinkageSpecDecl::lang_cxx && "unknown language in linkage specification"); l = "C++"; } Out << "extern \"" << l << "\" "; if (LS->hasBraces()) { Out << "{\n"; ChangeIndent(1); } // FIXME: Should not use a NULL DeclContext! ASTContext *Context = 0; for (LinkageSpecDecl::decl_iterator D = LS->decls_begin(*Context), DEnd = LS->decls_end(*Context); D != DEnd; ++D) PrintDecl(*D); if (LS->hasBraces()) { ChangeIndent(-1); Indent() << "}"; } Out << "\n"; } void DeclPrinter::PrintObjCMethodDecl(ObjCMethodDecl *OMD) { if (OMD->isInstanceMethod()) Out << "\n- "; else Out << "\n+ "; if (!OMD->getResultType().isNull()) Out << '(' << OMD->getResultType().getAsString() << ")"; std::string name = OMD->getSelector().getAsString(); std::string::size_type pos, lastPos = 0; for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), E = OMD->param_end(); PI != E; ++PI) { // FIXME: selector is missing here! pos = name.find_first_of(":", lastPos); Out << " " << name.substr(lastPos, pos - lastPos); Out << ":(" << (*PI)->getType().getAsString() << ")" << (*PI)->getNameAsString(); lastPos = pos + 1; } if (OMD->param_begin() == OMD->param_end()) Out << " " << name; if (OMD->isVariadic()) Out << ", ..."; Out << ";"; } void DeclPrinter::PrintObjCImplementationDecl(ObjCImplementationDecl *OID) { std::string I = OID->getNameAsString(); ObjCInterfaceDecl *SID = OID->getSuperClass(); if (SID) Out << "@implementation " << I << " : " << SID->getNameAsString(); else Out << "@implementation " << I; for (ObjCImplementationDecl::instmeth_iterator I = OID->instmeth_begin(), E = OID->instmeth_end(); I != E; ++I) { ObjCMethodDecl *OMD = *I; PrintObjCMethodDecl(OMD); if (OMD->getBody()) { Out << ' '; OMD->getBody()->printPretty(Out); Out << '\n'; } } for (ObjCImplementationDecl::classmeth_iterator I = OID->classmeth_begin(), E = OID->classmeth_end(); I != E; ++I) { ObjCMethodDecl *OMD = *I; PrintObjCMethodDecl(OMD); if (OMD->getBody()) { Out << ' '; OMD->getBody()->printPretty(Out); Out << '\n'; } } for (ObjCImplementationDecl::propimpl_iterator I = OID->propimpl_begin(), E = OID->propimpl_end(); I != E; ++I) PrintObjCPropertyImplDecl(*I); Out << "@end\n"; } void DeclPrinter::PrintObjCInterfaceDecl(ObjCInterfaceDecl *OID) { std::string I = OID->getNameAsString(); ObjCInterfaceDecl *SID = OID->getSuperClass(); if (SID) Out << "@interface " << I << " : " << SID->getNameAsString(); else Out << "@interface " << I; // Protocols? const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols(); if (!Protocols.empty()) { for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), E = Protocols.end(); I != E; ++I) Out << (I == Protocols.begin() ? '<' : ',') << (*I)->getNameAsString(); } if (!Protocols.empty()) Out << ">"; Out << '\n'; if (OID->ivar_size() > 0) { Out << '{'; for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(), E = OID->ivar_end(); I != E; ++I) { Out << '\t' << (*I)->getType().getAsString() << ' ' << (*I)->getNameAsString() << ";\n"; } Out << "}\n"; } // FIXME: Should not use a NULL DeclContext! ASTContext *Context = 0; for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(*Context), E = OID->prop_end(*Context); I != E; ++I) PrintObjCPropertyDecl(*I); bool eol_needed = false; for (ObjCInterfaceDecl::classmeth_iterator I = OID->classmeth_begin(*Context), E = OID->classmeth_end(*Context); I != E; ++I) eol_needed = true, PrintObjCMethodDecl(*I); for (ObjCInterfaceDecl::instmeth_iterator I = OID->instmeth_begin(*Context), E = OID->instmeth_end(*Context); I != E; ++I) eol_needed = true, PrintObjCMethodDecl(*I); Out << (eol_needed ? "\n@end\n" : "@end\n"); // FIXME: implement the rest... } void DeclPrinter::PrintObjCProtocolDecl(ObjCProtocolDecl *PID) { Out << "@protocol " << PID->getNameAsString() << '\n'; // FIXME: Should not use a NULL DeclContext! ASTContext *Context = 0; for (ObjCProtocolDecl::prop_iterator I = PID->prop_begin(*Context), E = PID->prop_end(*Context); I != E; ++I) PrintObjCPropertyDecl(*I); Out << "@end\n"; // FIXME: implement the rest... } void DeclPrinter::PrintObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) { Out << "@implementation " << PID->getClassInterface()->getNameAsString() << '(' << PID->getNameAsString() << ");\n"; for (ObjCCategoryImplDecl::propimpl_iterator I = PID->propimpl_begin(), E = PID->propimpl_end(); I != E; ++I) PrintObjCPropertyImplDecl(*I); Out << "@end\n"; // FIXME: implement the rest... } void DeclPrinter::PrintObjCCategoryDecl(ObjCCategoryDecl *PID) { // FIXME: Should not use a NULL DeclContext! ASTContext *Context = 0; Out << "@interface " << PID->getClassInterface()->getNameAsString() << '(' << PID->getNameAsString() << ");\n"; // Output property declarations. for (ObjCCategoryDecl::prop_iterator I = PID->prop_begin(*Context), E = PID->prop_end(*Context); I != E; ++I) PrintObjCPropertyDecl(*I); Out << "@end\n"; // FIXME: implement the rest... } void DeclPrinter::PrintObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) { Out << "@compatibility_alias " << AID->getNameAsString() << ' ' << AID->getClassInterface()->getNameAsString() << ";\n"; } /// PrintObjCPropertyDecl - print a property declaration. /// void DeclPrinter::PrintObjCPropertyDecl(ObjCPropertyDecl *PDecl) { if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required) Out << "@required\n"; else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional) Out << "@optional\n"; Out << "@property"; if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) { bool first = true; Out << " ("; if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly) { Out << (first ? ' ' : ',') << "readonly"; first = false; } if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { Out << (first ? ' ' : ',') << "getter = " << PDecl->getGetterName().getAsString(); first = false; } if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { Out << (first ? ' ' : ',') << "setter = " << PDecl->getSetterName().getAsString(); first = false; } if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) { Out << (first ? ' ' : ',') << "assign"; first = false; } if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite) { Out << (first ? ' ' : ',') << "readwrite"; first = false; } if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) { Out << (first ? ' ' : ',') << "retain"; first = false; } if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) { Out << (first ? ' ' : ',') << "copy"; first = false; } if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) { Out << (first ? ' ' : ',') << "nonatomic"; first = false; } Out << " )"; } Out << ' ' << PDecl->getType().getAsString() << ' ' << PDecl->getNameAsString(); Out << ";\n"; } /// PrintObjCPropertyImplDecl - Print an objective-c property implementation /// declaration syntax. /// void DeclPrinter::PrintObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) { if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) Out << "\n@synthesize "; else Out << "\n@dynamic "; Out << PID->getPropertyDecl()->getNameAsString(); if (PID->getPropertyIvarDecl()) Out << "=" << PID->getPropertyIvarDecl()->getNameAsString(); Out << ";\n"; } /// PrintTemplateParams - Print a template parameter list and recursively print /// it's underlying top-level definition. void DeclPrinter::PrintTemplateDecl(TemplateDecl *TD) { // TODO: Write template parameters. Out << "template <...> "; PrintDecl(TD->getTemplatedDecl()); } //===----------------------------------------------------------------------===// /// ASTPrinter - Pretty-printer of ASTs namespace { class ASTPrinter : public ASTConsumer, public DeclPrinter { public: ASTPrinter(llvm::raw_ostream* o = NULL) : DeclPrinter(o) {} virtual void HandleTopLevelDecl(DeclGroupRef D) { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) PrintDecl(*I); } }; } // end anonymous namespace ASTConsumer *clang::CreateASTPrinter(llvm::raw_ostream* out) { return new ASTPrinter(out); } //===----------------------------------------------------------------------===// /// ASTDumper - Low-level dumper of ASTs namespace { class ASTDumper : public ASTConsumer, public DeclPrinter { SourceManager *SM; public: ASTDumper() : DeclPrinter() {} void Initialize(ASTContext &Context) { SM = &Context.getSourceManager(); } virtual void HandleTopLevelDecl(DeclGroupRef D) { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) HandleTopLevelSingleDecl(*I); } void HandleTopLevelSingleDecl(Decl *D); }; } // end anonymous namespace void ASTDumper::HandleTopLevelSingleDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { PrintFunctionDeclStart(FD); if (FD->getBody()) { Out << '\n'; // FIXME: convert dumper to use std::ostream? FD->getBody()->dumpAll(*SM); Out << '\n'; } } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { PrintTypeDefDecl(TD); } else if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(D)) { Out << "Read objc interface '" << OID->getNameAsString() << "'\n"; } else if (ObjCProtocolDecl *OPD = dyn_cast<ObjCProtocolDecl>(D)) { Out << "Read objc protocol '" << OPD->getNameAsString() << "'\n"; } else if (ObjCCategoryDecl *OCD = dyn_cast<ObjCCategoryDecl>(D)) { Out << "Read objc category '" << OCD->getNameAsString() << "'\n"; } else if (isa<ObjCForwardProtocolDecl>(D)) { Out << "Read objc fwd protocol decl\n"; } else if (isa<ObjCClassDecl>(D)) { Out << "Read objc fwd class decl\n"; } else if (isa<FileScopeAsmDecl>(D)) { Out << "Read file scope asm decl\n"; } else if (ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D)) { Out << "Read objc method decl: '" << MD->getSelector().getAsString() << "'\n"; if (MD->getBody()) { // FIXME: convert dumper to use std::ostream? MD->getBody()->dumpAll(*SM); Out << '\n'; } } else if (isa<ObjCImplementationDecl>(D)) { Out << "Read objc implementation decl\n"; } else if (isa<ObjCCategoryImplDecl>(D)) { Out << "Read objc category implementation decl\n"; } else if (isa<LinkageSpecDecl>(D)) { Out << "Read linkage spec decl\n"; } else if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) { Out << "Read top-level variable decl: '" << ND->getNameAsString() << "'\n"; } else { assert(0 && "Unknown decl type!"); } } ASTConsumer *clang::CreateASTDumper() { return new ASTDumper(); } //===----------------------------------------------------------------------===// /// ASTViewer - AST Visualization namespace { class ASTViewer : public ASTConsumer { SourceManager *SM; public: void Initialize(ASTContext &Context) { SM = &Context.getSourceManager(); } virtual void HandleTopLevelDecl(DeclGroupRef D) { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) HandleTopLevelSingleDecl(*I); } void HandleTopLevelSingleDecl(Decl *D); }; } void ASTViewer::HandleTopLevelSingleDecl(Decl *D) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { DeclPrinter().PrintFunctionDeclStart(FD); if (FD->getBody()) { llvm::cerr << '\n'; FD->getBody()->viewAST(); llvm::cerr << '\n'; } return; } if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { DeclPrinter().PrintObjCMethodDecl(MD); if (MD->getBody()) { llvm::cerr << '\n'; MD->getBody()->viewAST(); llvm::cerr << '\n'; } } } ASTConsumer *clang::CreateASTViewer() { return new ASTViewer(); } //===----------------------------------------------------------------------===// /// DeclContextPrinter - Decl and DeclContext Visualization namespace { class DeclContextPrinter : public ASTConsumer { llvm::raw_ostream& Out; public: DeclContextPrinter() : Out(llvm::errs()) {} void HandleTranslationUnit(ASTContext &C) { PrintDeclContext(C.getTranslationUnitDecl(), 4); } void PrintDeclContext(const DeclContext* DC, unsigned Indentation); }; } // end anonymous namespace void DeclContextPrinter::PrintDeclContext(const DeclContext* DC, unsigned Indentation) { // Print DeclContext name. switch (DC->getDeclKind()) { case Decl::TranslationUnit: Out << "[translation unit] " << DC; break; case Decl::Namespace: { Out << "[namespace] "; const NamespaceDecl* ND = cast<NamespaceDecl>(DC); Out << ND->getNameAsString(); break; } case Decl::Enum: { const EnumDecl* ED = cast<EnumDecl>(DC); if (ED->isDefinition()) Out << "[enum] "; else Out << "<enum> "; Out << ED->getNameAsString(); break; } case Decl::Record: { const RecordDecl* RD = cast<RecordDecl>(DC); if (RD->isDefinition()) Out << "[struct] "; else Out << "<struct> "; Out << RD->getNameAsString(); break; } case Decl::CXXRecord: { const CXXRecordDecl* RD = cast<CXXRecordDecl>(DC); if (RD->isDefinition()) Out << "[class] "; else Out << "<class> "; Out << RD->getNameAsString() << " " << DC; break; } case Decl::ObjCMethod: Out << "[objc method]"; break; case Decl::ObjCInterface: Out << "[objc interface]"; break; case Decl::ObjCCategory: Out << "[objc category]"; break; case Decl::ObjCProtocol: Out << "[objc protocol]"; break; case Decl::ObjCImplementation: Out << "[objc implementation]"; break; case Decl::ObjCCategoryImpl: Out << "[objc categoryimpl]"; break; case Decl::LinkageSpec: Out << "[linkage spec]"; break; case Decl::Block: Out << "[block]"; break; case Decl::Function: { const FunctionDecl* FD = cast<FunctionDecl>(DC); if (FD->isThisDeclarationADefinition()) Out << "[function] "; else Out << "<function> "; Out << FD->getNameAsString(); // Print the parameters. Out << "("; bool PrintComma = false; for (FunctionDecl::param_const_iterator I = FD->param_begin(), E = FD->param_end(); I != E; ++I) { if (PrintComma) Out << ", "; else PrintComma = true; Out << (*I)->getNameAsString(); } Out << ")"; break; } case Decl::CXXMethod: { const CXXMethodDecl* D = cast<CXXMethodDecl>(DC); if (D->isOutOfLineDefinition()) Out << "[c++ method] "; else if (D->isImplicit()) Out << "(c++ method) "; else Out << "<c++ method> "; Out << D->getNameAsString(); // Print the parameters. Out << "("; bool PrintComma = false; for (FunctionDecl::param_const_iterator I = D->param_begin(), E = D->param_end(); I != E; ++I) { if (PrintComma) Out << ", "; else PrintComma = true; Out << (*I)->getNameAsString(); } Out << ")"; // Check the semantic DeclContext. const DeclContext* SemaDC = D->getDeclContext(); const DeclContext* LexicalDC = D->getLexicalDeclContext(); if (SemaDC != LexicalDC) Out << " [[" << SemaDC << "]]"; break; } case Decl::CXXConstructor: { const CXXConstructorDecl* D = cast<CXXConstructorDecl>(DC); if (D->isOutOfLineDefinition()) Out << "[c++ ctor] "; else if (D->isImplicit()) Out << "(c++ ctor) "; else Out << "<c++ ctor> "; Out << D->getNameAsString(); // Print the parameters. Out << "("; bool PrintComma = false; for (FunctionDecl::param_const_iterator I = D->param_begin(), E = D->param_end(); I != E; ++I) { if (PrintComma) Out << ", "; else PrintComma = true; Out << (*I)->getNameAsString(); } Out << ")"; // Check the semantic DC. const DeclContext* SemaDC = D->getDeclContext(); const DeclContext* LexicalDC = D->getLexicalDeclContext(); if (SemaDC != LexicalDC) Out << " [[" << SemaDC << "]]"; break; } case Decl::CXXDestructor: { const CXXDestructorDecl* D = cast<CXXDestructorDecl>(DC); if (D->isOutOfLineDefinition()) Out << "[c++ dtor] "; else if (D->isImplicit()) Out << "(c++ dtor) "; else Out << "<c++ dtor> "; Out << D->getNameAsString(); // Check the semantic DC. const DeclContext* SemaDC = D->getDeclContext(); const DeclContext* LexicalDC = D->getLexicalDeclContext(); if (SemaDC != LexicalDC) Out << " [[" << SemaDC << "]]"; break; } case Decl::CXXConversion: { const CXXConversionDecl* D = cast<CXXConversionDecl>(DC); if (D->isOutOfLineDefinition()) Out << "[c++ conversion] "; else if (D->isImplicit()) Out << "(c++ conversion) "; else Out << "<c++ conversion> "; Out << D->getNameAsString(); // Check the semantic DC. const DeclContext* SemaDC = D->getDeclContext(); const DeclContext* LexicalDC = D->getLexicalDeclContext(); if (SemaDC != LexicalDC) Out << " [[" << SemaDC << "]]"; break; } default: assert(0 && "a decl that inherits DeclContext isn't handled"); } Out << "\n"; // Print decls in the DeclContext. // FIXME: Should not use a NULL DeclContext! ASTContext *Context = 0; for (DeclContext::decl_iterator I = DC->decls_begin(*Context), E = DC->decls_end(*Context); I != E; ++I) { for (unsigned i = 0; i < Indentation; ++i) Out << " "; Decl::Kind DK = I->getKind(); switch (DK) { case Decl::Namespace: case Decl::Enum: case Decl::Record: case Decl::CXXRecord: case Decl::ObjCMethod: case Decl::ObjCInterface: case Decl::ObjCCategory: case Decl::ObjCProtocol: case Decl::ObjCImplementation: case Decl::ObjCCategoryImpl: case Decl::LinkageSpec: case Decl::Block: case Decl::Function: case Decl::CXXMethod: case Decl::CXXConstructor: case Decl::CXXDestructor: case Decl::CXXConversion: { DeclContext* DC = cast<DeclContext>(*I); PrintDeclContext(DC, Indentation+2); break; } case Decl::Field: { FieldDecl* FD = cast<FieldDecl>(*I); Out << "<field> " << FD->getNameAsString() << "\n"; break; } case Decl::Typedef: { TypedefDecl* TD = cast<TypedefDecl>(*I); Out << "<typedef> " << TD->getNameAsString() << "\n"; break; } case Decl::EnumConstant: { EnumConstantDecl* ECD = cast<EnumConstantDecl>(*I); Out << "<enum constant> " << ECD->getNameAsString() << "\n"; break; } case Decl::Var: { VarDecl* VD = cast<VarDecl>(*I); Out << "<var> " << VD->getNameAsString() << "\n"; break; } case Decl::ImplicitParam: { ImplicitParamDecl* IPD = cast<ImplicitParamDecl>(*I); Out << "<implicit parameter> " << IPD->getNameAsString() << "\n"; break; } case Decl::ParmVar: { ParmVarDecl* PVD = cast<ParmVarDecl>(*I); Out << "<parameter> " << PVD->getNameAsString() << "\n"; break; } case Decl::OriginalParmVar: { OriginalParmVarDecl* OPVD = cast<OriginalParmVarDecl>(*I); Out << "<original parameter> " << OPVD->getNameAsString() << "\n"; break; } case Decl::ObjCProperty: { ObjCPropertyDecl* OPD = cast<ObjCPropertyDecl>(*I); Out << "<objc property> " << OPD->getNameAsString() << "\n"; break; } default: fprintf(stderr, "DeclKind: %d \"%s\"\n", DK, I->getDeclKindName()); assert(0 && "decl unhandled"); } } } ASTConsumer *clang::CreateDeclContextPrinter() { return new DeclContextPrinter(); } //===----------------------------------------------------------------------===// /// InheritanceViewer - C++ Inheritance Visualization namespace { class InheritanceViewer : public ASTConsumer { const std::string clsname; public: InheritanceViewer(const std::string& cname) : clsname(cname) {} void HandleTranslationUnit(ASTContext &C) { for (ASTContext::type_iterator I=C.types_begin(),E=C.types_end(); I!=E; ++I) if (RecordType *T = dyn_cast<RecordType>(*I)) { if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(T->getDecl())) { // FIXME: This lookup needs to be generalized to handle namespaces and // (when we support them) templates. if (D->getNameAsString() == clsname) { D->viewInheritance(C); } } } } }; } ASTConsumer *clang::CreateInheritanceViewer(const std::string& clsname) { return new InheritanceViewer(clsname); } //===----------------------------------------------------------------------===// // AST Serializer namespace { class ASTSerializer : public ASTConsumer { protected: Diagnostic& Diags; public: ASTSerializer(Diagnostic& diags) : Diags(diags) {} }; class SingleFileSerializer : public ASTSerializer { const llvm::sys::Path FName; public: SingleFileSerializer(const llvm::sys::Path& F, Diagnostic& diags) : ASTSerializer(diags), FName(F) {} virtual void HandleTranslationUnit(ASTContext &Ctx) { if (Diags.hasErrorOccurred()) return; // Reserve 256K for bitstream buffer. std::vector<unsigned char> Buffer; Buffer.reserve(256*1024); Ctx.EmitASTBitcodeBuffer(Buffer); // Write the bits to disk. if (FILE* fp = fopen(FName.c_str(),"wb")) { fwrite((char*)&Buffer.front(), sizeof(char), Buffer.size(), fp); fclose(fp); } } }; class BuildSerializer : public ASTSerializer { llvm::sys::Path EmitDir; public: BuildSerializer(const llvm::sys::Path& dir, Diagnostic& diags) : ASTSerializer(diags), EmitDir(dir) {} virtual void HandleTranslationUnit(ASTContext &Ctx); }; } // end anonymous namespace void BuildSerializer::HandleTranslationUnit(ASTContext &Ctx) { if (Diags.hasErrorOccurred()) return; SourceManager& SourceMgr = Ctx.getSourceManager(); FileID ID = SourceMgr.getMainFileID(); assert(!ID.isInvalid() && "MainFileID not set!"); const FileEntry* FE = SourceMgr.getFileEntryForID(ID); assert(FE && "No FileEntry for main file."); // FIXME: This is not portable to Windows. // FIXME: This logic should probably be moved elsewhere later. llvm::sys::Path FName(EmitDir); std::vector<char> buf; buf.reserve(strlen(FE->getName())+100); sprintf(&buf[0], "dev_%llx", (unsigned long long) FE->getDevice()); FName.appendComponent(&buf[0]); FName.createDirectoryOnDisk(true); if (!FName.canWrite() || !FName.isDirectory()) { assert (false && "Could not create 'device' serialization directory."); return; } sprintf(&buf[0], "%s-%llX.ast", FE->getName(), (unsigned long long) FE->getInode()); FName.appendComponent(&buf[0]); // Reserve 256K for bitstream buffer. std::vector<unsigned char> Buffer; Buffer.reserve(256*1024); Ctx.EmitASTBitcodeBuffer(Buffer); // Write the bits to disk. if (FILE* fp = fopen(FName.c_str(),"wb")) { fwrite((char*)&Buffer.front(), sizeof(char), Buffer.size(), fp); fclose(fp); } // Now emit the sources. } ASTConsumer* clang::CreateASTSerializer(const std::string& InFile, const std::string& OutputFile, Diagnostic &Diags) { if (OutputFile.size()) { if (InFile == "-") { llvm::cerr << "error: Cannot use --serialize with -o for source read from STDIN.\n"; return NULL; } // The user specified an AST-emission directory. Determine if the path // is absolute. llvm::sys::Path EmitDir(OutputFile); if (!EmitDir.isAbsolute()) { llvm::cerr << "error: Output directory for --serialize must be an absolute path.\n"; return NULL; } // Create the directory if it does not exist. EmitDir.createDirectoryOnDisk(true); if (!EmitDir.canWrite() || !EmitDir.isDirectory()) { llvm::cerr << "error: Could not create output directory for --serialize.\n"; return NULL; } // FIXME: We should probably only allow using BuildSerializer when // the ASTs come from parsed source files, and not from .ast files. return new BuildSerializer(EmitDir, Diags); } // The user did not specify an output directory for serialized ASTs. // Serialize the translation to a single file whose name is the same // as the input file with the ".ast" extension appended. llvm::sys::Path FName(InFile.c_str()); FName.appendSuffix("ast"); return new SingleFileSerializer(FName, Diags); } <file_sep>/test/Lexer/badstring_in_if0.c // RUN: clang-cc -E %s 2>&1 | not grep error #if 0 " ' #endif <file_sep>/tools/clang-cc/clang-cc.h //===--- clang-cc.h - C-Language Front-end --------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the header file that pulls together the top-level driver. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_CLANG_CC_H #define LLVM_CLANG_CLANG_CC_H #include <vector> #include <string> namespace clang { class Preprocessor; class MinimalAction; class TargetInfo; class Diagnostic; class ASTConsumer; class IdentifierTable; class SourceManager; /// ProcessWarningOptions - Initialize the diagnostic client and process the /// warning options specified on the command line. bool ProcessWarningOptions(Diagnostic &Diags); /// DoPrintPreprocessedInput - Implement -E mode. void DoPrintPreprocessedInput(Preprocessor &PP, const std::string& OutFile); /// RewriteMacrosInInput - Implement -rewrite-macros mode. void RewriteMacrosInInput(Preprocessor &PP, const std::string &InFileName, const std::string& OutFile); void DoRewriteTest(Preprocessor &PP, const std::string &InFileName, const std::string &OutFileName); /// CreatePrintParserActionsAction - Return the actions implementation that /// implements the -parse-print-callbacks option. MinimalAction *CreatePrintParserActionsAction(Preprocessor &PP); /// CheckDiagnostics - Gather the expected diagnostics and check them. bool CheckDiagnostics(Preprocessor &PP); /// CreateDependencyFileGen - Create dependency file generator. /// This is only done if either -MD or -MMD has been specified. bool CreateDependencyFileGen(Preprocessor *PP, std::string &ErrStr); /// CacheTokens - Cache tokens for use with PCH. void CacheTokens(Preprocessor& PP, const std::string& OutFile); } // end namespace clang #endif <file_sep>/lib/Frontend/PCHWriter.cpp //===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PCHWriter class, which writes a precompiled header. // //===----------------------------------------------------------------------===// #include "clang/Frontend/PCHWriter.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclContextInternals.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/Expr.h" #include "clang/AST/StmtVisitor.h" #include "clang/AST/Type.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/SourceManagerInternals.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MemoryBuffer.h" #include <cstdio> using namespace clang; //===----------------------------------------------------------------------===// // Type serialization //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN PCHTypeWriter { PCHWriter &Writer; PCHWriter::RecordData &Record; public: /// \brief Type code that corresponds to the record generated. pch::TypeCode Code; PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record) : Writer(Writer), Record(Record) { } void VisitArrayType(const ArrayType *T); void VisitFunctionType(const FunctionType *T); void VisitTagType(const TagType *T); #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T); #define ABSTRACT_TYPE(Class, Base) #define DEPENDENT_TYPE(Class, Base) #include "clang/AST/TypeNodes.def" }; } void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) { Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record); Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values Record.push_back(T->getAddressSpace()); Code = pch::TYPE_EXT_QUAL; } void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) { assert(false && "Built-in types are never serialized"); } void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) { Record.push_back(T->getWidth()); Record.push_back(T->isSigned()); Code = pch::TYPE_FIXED_WIDTH_INT; } void PCHTypeWriter::VisitComplexType(const ComplexType *T) { Writer.AddTypeRef(T->getElementType(), Record); Code = pch::TYPE_COMPLEX; } void PCHTypeWriter::VisitPointerType(const PointerType *T) { Writer.AddTypeRef(T->getPointeeType(), Record); Code = pch::TYPE_POINTER; } void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) { Writer.AddTypeRef(T->getPointeeType(), Record); Code = pch::TYPE_BLOCK_POINTER; } void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) { Writer.AddTypeRef(T->getPointeeType(), Record); Code = pch::TYPE_LVALUE_REFERENCE; } void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) { Writer.AddTypeRef(T->getPointeeType(), Record); Code = pch::TYPE_RVALUE_REFERENCE; } void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) { Writer.AddTypeRef(T->getPointeeType(), Record); Writer.AddTypeRef(QualType(T->getClass(), 0), Record); Code = pch::TYPE_MEMBER_POINTER; } void PCHTypeWriter::VisitArrayType(const ArrayType *T) { Writer.AddTypeRef(T->getElementType(), Record); Record.push_back(T->getSizeModifier()); // FIXME: stable values Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values } void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) { VisitArrayType(T); Writer.AddAPInt(T->getSize(), Record); Code = pch::TYPE_CONSTANT_ARRAY; } void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) { VisitArrayType(T); Code = pch::TYPE_INCOMPLETE_ARRAY; } void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) { VisitArrayType(T); Writer.AddExpr(T->getSizeExpr()); Code = pch::TYPE_VARIABLE_ARRAY; } void PCHTypeWriter::VisitVectorType(const VectorType *T) { Writer.AddTypeRef(T->getElementType(), Record); Record.push_back(T->getNumElements()); Code = pch::TYPE_VECTOR; } void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) { VisitVectorType(T); Code = pch::TYPE_EXT_VECTOR; } void PCHTypeWriter::VisitFunctionType(const FunctionType *T) { Writer.AddTypeRef(T->getResultType(), Record); } void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { VisitFunctionType(T); Code = pch::TYPE_FUNCTION_NO_PROTO; } void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) { VisitFunctionType(T); Record.push_back(T->getNumArgs()); for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I) Writer.AddTypeRef(T->getArgType(I), Record); Record.push_back(T->isVariadic()); Record.push_back(T->getTypeQuals()); Code = pch::TYPE_FUNCTION_PROTO; } void PCHTypeWriter::VisitTypedefType(const TypedefType *T) { Writer.AddDeclRef(T->getDecl(), Record); Code = pch::TYPE_TYPEDEF; } void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) { Writer.AddExpr(T->getUnderlyingExpr()); Code = pch::TYPE_TYPEOF_EXPR; } void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) { Writer.AddTypeRef(T->getUnderlyingType(), Record); Code = pch::TYPE_TYPEOF; } void PCHTypeWriter::VisitTagType(const TagType *T) { Writer.AddDeclRef(T->getDecl(), Record); assert(!T->isBeingDefined() && "Cannot serialize in the middle of a type definition"); } void PCHTypeWriter::VisitRecordType(const RecordType *T) { VisitTagType(T); Code = pch::TYPE_RECORD; } void PCHTypeWriter::VisitEnumType(const EnumType *T) { VisitTagType(T); Code = pch::TYPE_ENUM; } void PCHTypeWriter::VisitTemplateSpecializationType( const TemplateSpecializationType *T) { // FIXME: Serialize this type (C++ only) assert(false && "Cannot serialize template specialization types"); } void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) { // FIXME: Serialize this type (C++ only) assert(false && "Cannot serialize qualified name types"); } void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { Writer.AddDeclRef(T->getDecl(), Record); Code = pch::TYPE_OBJC_INTERFACE; } void PCHTypeWriter::VisitObjCQualifiedInterfaceType( const ObjCQualifiedInterfaceType *T) { VisitObjCInterfaceType(T); Record.push_back(T->getNumProtocols()); for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I) Writer.AddDeclRef(T->getProtocol(I), Record); Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE; } void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) { Record.push_back(T->getNumProtocols()); for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I) Writer.AddDeclRef(T->getProtocols(I), Record); Code = pch::TYPE_OBJC_QUALIFIED_ID; } void PCHTypeWriter::VisitObjCQualifiedClassType(const ObjCQualifiedClassType *T) { Record.push_back(T->getNumProtocols()); for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I) Writer.AddDeclRef(T->getProtocols(I), Record); Code = pch::TYPE_OBJC_QUALIFIED_CLASS; } //===----------------------------------------------------------------------===// // Declaration serialization //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN PCHDeclWriter : public DeclVisitor<PCHDeclWriter, void> { PCHWriter &Writer; PCHWriter::RecordData &Record; public: pch::DeclCode Code; PCHDeclWriter(PCHWriter &Writer, PCHWriter::RecordData &Record) : Writer(Writer), Record(Record) { } void VisitDecl(Decl *D); void VisitTranslationUnitDecl(TranslationUnitDecl *D); void VisitNamedDecl(NamedDecl *D); void VisitTypeDecl(TypeDecl *D); void VisitTypedefDecl(TypedefDecl *D); void VisitTagDecl(TagDecl *D); void VisitEnumDecl(EnumDecl *D); void VisitRecordDecl(RecordDecl *D); void VisitValueDecl(ValueDecl *D); void VisitEnumConstantDecl(EnumConstantDecl *D); void VisitFunctionDecl(FunctionDecl *D); void VisitFieldDecl(FieldDecl *D); void VisitVarDecl(VarDecl *D); void VisitParmVarDecl(ParmVarDecl *D); void VisitOriginalParmVarDecl(OriginalParmVarDecl *D); void VisitFileScopeAsmDecl(FileScopeAsmDecl *D); void VisitBlockDecl(BlockDecl *D); void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset, uint64_t VisibleOffset); }; } void PCHDeclWriter::VisitDecl(Decl *D) { Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record); Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record); Writer.AddSourceLocation(D->getLocation(), Record); Record.push_back(D->isInvalidDecl()); Record.push_back(D->hasAttrs()); Record.push_back(D->isImplicit()); Record.push_back(D->getAccess()); } void PCHDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { VisitDecl(D); Code = pch::DECL_TRANSLATION_UNIT; } void PCHDeclWriter::VisitNamedDecl(NamedDecl *D) { VisitDecl(D); Writer.AddDeclarationName(D->getDeclName(), Record); } void PCHDeclWriter::VisitTypeDecl(TypeDecl *D) { VisitNamedDecl(D); Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record); } void PCHDeclWriter::VisitTypedefDecl(TypedefDecl *D) { VisitTypeDecl(D); Writer.AddTypeRef(D->getUnderlyingType(), Record); Code = pch::DECL_TYPEDEF; } void PCHDeclWriter::VisitTagDecl(TagDecl *D) { VisitTypeDecl(D); Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding Record.push_back(D->isDefinition()); Writer.AddDeclRef(D->getTypedefForAnonDecl(), Record); } void PCHDeclWriter::VisitEnumDecl(EnumDecl *D) { VisitTagDecl(D); Writer.AddTypeRef(D->getIntegerType(), Record); Code = pch::DECL_ENUM; } void PCHDeclWriter::VisitRecordDecl(RecordDecl *D) { VisitTagDecl(D); Record.push_back(D->hasFlexibleArrayMember()); Record.push_back(D->isAnonymousStructOrUnion()); Code = pch::DECL_RECORD; } void PCHDeclWriter::VisitValueDecl(ValueDecl *D) { VisitNamedDecl(D); Writer.AddTypeRef(D->getType(), Record); } void PCHDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) { VisitValueDecl(D); Record.push_back(D->getInitExpr()? 1 : 0); if (D->getInitExpr()) Writer.AddExpr(D->getInitExpr()); Writer.AddAPSInt(D->getInitVal(), Record); Code = pch::DECL_ENUM_CONSTANT; } void PCHDeclWriter::VisitFunctionDecl(FunctionDecl *D) { VisitValueDecl(D); // FIXME: function body Writer.AddDeclRef(D->getPreviousDeclaration(), Record); Record.push_back(D->getStorageClass()); // FIXME: stable encoding Record.push_back(D->isInline()); Record.push_back(D->isVirtual()); Record.push_back(D->isPure()); Record.push_back(D->inheritedPrototype()); Record.push_back(D->hasPrototype() && !D->inheritedPrototype()); Record.push_back(D->isDeleted()); Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record); Record.push_back(D->param_size()); for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end(); P != PEnd; ++P) Writer.AddDeclRef(*P, Record); Code = pch::DECL_FUNCTION; } void PCHDeclWriter::VisitFieldDecl(FieldDecl *D) { VisitValueDecl(D); Record.push_back(D->isMutable()); Record.push_back(D->getBitWidth()? 1 : 0); if (D->getBitWidth()) Writer.AddExpr(D->getBitWidth()); Code = pch::DECL_FIELD; } void PCHDeclWriter::VisitVarDecl(VarDecl *D) { VisitValueDecl(D); Record.push_back(D->getStorageClass()); // FIXME: stable encoding Record.push_back(D->isThreadSpecified()); Record.push_back(D->hasCXXDirectInitializer()); Record.push_back(D->isDeclaredInCondition()); Writer.AddDeclRef(D->getPreviousDeclaration(), Record); Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record); Record.push_back(D->getInit()? 1 : 0); if (D->getInit()) Writer.AddExpr(D->getInit()); Code = pch::DECL_VAR; } void PCHDeclWriter::VisitParmVarDecl(ParmVarDecl *D) { VisitVarDecl(D); Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding // FIXME: emit default argument (C++) // FIXME: why isn't the "default argument" just stored as the initializer // in VarDecl? Code = pch::DECL_PARM_VAR; } void PCHDeclWriter::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) { VisitParmVarDecl(D); Writer.AddTypeRef(D->getOriginalType(), Record); Code = pch::DECL_ORIGINAL_PARM_VAR; } void PCHDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) { VisitDecl(D); Writer.AddExpr(D->getAsmString()); Code = pch::DECL_FILE_SCOPE_ASM; } void PCHDeclWriter::VisitBlockDecl(BlockDecl *D) { VisitDecl(D); // FIXME: emit block body Record.push_back(D->param_size()); for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end(); P != PEnd; ++P) Writer.AddDeclRef(*P, Record); Code = pch::DECL_BLOCK; } /// \brief Emit the DeclContext part of a declaration context decl. /// /// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL /// block for this declaration context is stored. May be 0 to indicate /// that there are no declarations stored within this context. /// /// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE /// block for this declaration context is stored. May be 0 to indicate /// that there are no declarations visible from this context. Note /// that this value will not be emitted for non-primary declaration /// contexts. void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset, uint64_t VisibleOffset) { Record.push_back(LexicalOffset); if (DC->getPrimaryContext() == DC) Record.push_back(VisibleOffset); } //===----------------------------------------------------------------------===// // Statement/expression serialization //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN PCHStmtWriter : public StmtVisitor<PCHStmtWriter, void> { PCHWriter &Writer; PCHWriter::RecordData &Record; public: pch::StmtCode Code; PCHStmtWriter(PCHWriter &Writer, PCHWriter::RecordData &Record) : Writer(Writer), Record(Record) { } void VisitExpr(Expr *E); void VisitPredefinedExpr(PredefinedExpr *E); void VisitDeclRefExpr(DeclRefExpr *E); void VisitIntegerLiteral(IntegerLiteral *E); void VisitFloatingLiteral(FloatingLiteral *E); void VisitImaginaryLiteral(ImaginaryLiteral *E); void VisitStringLiteral(StringLiteral *E); void VisitCharacterLiteral(CharacterLiteral *E); void VisitParenExpr(ParenExpr *E); void VisitUnaryOperator(UnaryOperator *E); void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); void VisitArraySubscriptExpr(ArraySubscriptExpr *E); void VisitCallExpr(CallExpr *E); void VisitMemberExpr(MemberExpr *E); void VisitCastExpr(CastExpr *E); void VisitBinaryOperator(BinaryOperator *E); void VisitCompoundAssignOperator(CompoundAssignOperator *E); void VisitConditionalOperator(ConditionalOperator *E); void VisitImplicitCastExpr(ImplicitCastExpr *E); void VisitExplicitCastExpr(ExplicitCastExpr *E); void VisitCStyleCastExpr(CStyleCastExpr *E); void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); void VisitExtVectorElementExpr(ExtVectorElementExpr *E); void VisitInitListExpr(InitListExpr *E); void VisitDesignatedInitExpr(DesignatedInitExpr *E); void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); void VisitVAArgExpr(VAArgExpr *E); void VisitTypesCompatibleExpr(TypesCompatibleExpr *E); void VisitChooseExpr(ChooseExpr *E); void VisitGNUNullExpr(GNUNullExpr *E); void VisitShuffleVectorExpr(ShuffleVectorExpr *E); void VisitBlockDeclRefExpr(BlockDeclRefExpr *E); }; } void PCHStmtWriter::VisitExpr(Expr *E) { Writer.AddTypeRef(E->getType(), Record); Record.push_back(E->isTypeDependent()); Record.push_back(E->isValueDependent()); } void PCHStmtWriter::VisitPredefinedExpr(PredefinedExpr *E) { VisitExpr(E); Writer.AddSourceLocation(E->getLocation(), Record); Record.push_back(E->getIdentType()); // FIXME: stable encoding Code = pch::EXPR_PREDEFINED; } void PCHStmtWriter::VisitDeclRefExpr(DeclRefExpr *E) { VisitExpr(E); Writer.AddDeclRef(E->getDecl(), Record); Writer.AddSourceLocation(E->getLocation(), Record); Code = pch::EXPR_DECL_REF; } void PCHStmtWriter::VisitIntegerLiteral(IntegerLiteral *E) { VisitExpr(E); Writer.AddSourceLocation(E->getLocation(), Record); Writer.AddAPInt(E->getValue(), Record); Code = pch::EXPR_INTEGER_LITERAL; } void PCHStmtWriter::VisitFloatingLiteral(FloatingLiteral *E) { VisitExpr(E); Writer.AddAPFloat(E->getValue(), Record); Record.push_back(E->isExact()); Writer.AddSourceLocation(E->getLocation(), Record); Code = pch::EXPR_FLOATING_LITERAL; } void PCHStmtWriter::VisitImaginaryLiteral(ImaginaryLiteral *E) { VisitExpr(E); Writer.WriteSubExpr(E->getSubExpr()); Code = pch::EXPR_IMAGINARY_LITERAL; } void PCHStmtWriter::VisitStringLiteral(StringLiteral *E) { VisitExpr(E); Record.push_back(E->getByteLength()); Record.push_back(E->getNumConcatenated()); Record.push_back(E->isWide()); // FIXME: String data should be stored as a blob at the end of the // StringLiteral. However, we can't do so now because we have no // provision for coping with abbreviations when we're jumping around // the PCH file during deserialization. Record.insert(Record.end(), E->getStrData(), E->getStrData() + E->getByteLength()); for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I) Writer.AddSourceLocation(E->getStrTokenLoc(I), Record); Code = pch::EXPR_STRING_LITERAL; } void PCHStmtWriter::VisitCharacterLiteral(CharacterLiteral *E) { VisitExpr(E); Record.push_back(E->getValue()); Writer.AddSourceLocation(E->getLoc(), Record); Record.push_back(E->isWide()); Code = pch::EXPR_CHARACTER_LITERAL; } void PCHStmtWriter::VisitParenExpr(ParenExpr *E) { VisitExpr(E); Writer.AddSourceLocation(E->getLParen(), Record); Writer.AddSourceLocation(E->getRParen(), Record); Writer.WriteSubExpr(E->getSubExpr()); Code = pch::EXPR_PAREN; } void PCHStmtWriter::VisitUnaryOperator(UnaryOperator *E) { VisitExpr(E); Writer.WriteSubExpr(E->getSubExpr()); Record.push_back(E->getOpcode()); // FIXME: stable encoding Writer.AddSourceLocation(E->getOperatorLoc(), Record); Code = pch::EXPR_UNARY_OPERATOR; } void PCHStmtWriter::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { VisitExpr(E); Record.push_back(E->isSizeOf()); if (E->isArgumentType()) Writer.AddTypeRef(E->getArgumentType(), Record); else { Record.push_back(0); Writer.WriteSubExpr(E->getArgumentExpr()); } Writer.AddSourceLocation(E->getOperatorLoc(), Record); Writer.AddSourceLocation(E->getRParenLoc(), Record); Code = pch::EXPR_SIZEOF_ALIGN_OF; } void PCHStmtWriter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { VisitExpr(E); Writer.WriteSubExpr(E->getLHS()); Writer.WriteSubExpr(E->getRHS()); Writer.AddSourceLocation(E->getRBracketLoc(), Record); Code = pch::EXPR_ARRAY_SUBSCRIPT; } void PCHStmtWriter::VisitCallExpr(CallExpr *E) { VisitExpr(E); Record.push_back(E->getNumArgs()); Writer.AddSourceLocation(E->getRParenLoc(), Record); Writer.WriteSubExpr(E->getCallee()); for (CallExpr::arg_iterator Arg = E->arg_begin(), ArgEnd = E->arg_end(); Arg != ArgEnd; ++Arg) Writer.WriteSubExpr(*Arg); Code = pch::EXPR_CALL; } void PCHStmtWriter::VisitMemberExpr(MemberExpr *E) { VisitExpr(E); Writer.WriteSubExpr(E->getBase()); Writer.AddDeclRef(E->getMemberDecl(), Record); Writer.AddSourceLocation(E->getMemberLoc(), Record); Record.push_back(E->isArrow()); Code = pch::EXPR_MEMBER; } void PCHStmtWriter::VisitCastExpr(CastExpr *E) { VisitExpr(E); Writer.WriteSubExpr(E->getSubExpr()); } void PCHStmtWriter::VisitBinaryOperator(BinaryOperator *E) { VisitExpr(E); Writer.WriteSubExpr(E->getLHS()); Writer.WriteSubExpr(E->getRHS()); Record.push_back(E->getOpcode()); // FIXME: stable encoding Writer.AddSourceLocation(E->getOperatorLoc(), Record); Code = pch::EXPR_BINARY_OPERATOR; } void PCHStmtWriter::VisitCompoundAssignOperator(CompoundAssignOperator *E) { VisitBinaryOperator(E); Writer.AddTypeRef(E->getComputationLHSType(), Record); Writer.AddTypeRef(E->getComputationResultType(), Record); Code = pch::EXPR_COMPOUND_ASSIGN_OPERATOR; } void PCHStmtWriter::VisitConditionalOperator(ConditionalOperator *E) { VisitExpr(E); Writer.WriteSubExpr(E->getCond()); Writer.WriteSubExpr(E->getLHS()); Writer.WriteSubExpr(E->getRHS()); Code = pch::EXPR_CONDITIONAL_OPERATOR; } void PCHStmtWriter::VisitImplicitCastExpr(ImplicitCastExpr *E) { VisitCastExpr(E); Record.push_back(E->isLvalueCast()); Code = pch::EXPR_IMPLICIT_CAST; } void PCHStmtWriter::VisitExplicitCastExpr(ExplicitCastExpr *E) { VisitCastExpr(E); Writer.AddTypeRef(E->getTypeAsWritten(), Record); } void PCHStmtWriter::VisitCStyleCastExpr(CStyleCastExpr *E) { VisitExplicitCastExpr(E); Writer.AddSourceLocation(E->getLParenLoc(), Record); Writer.AddSourceLocation(E->getRParenLoc(), Record); Code = pch::EXPR_CSTYLE_CAST; } void PCHStmtWriter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { VisitExpr(E); Writer.AddSourceLocation(E->getLParenLoc(), Record); Writer.WriteSubExpr(E->getInitializer()); Record.push_back(E->isFileScope()); Code = pch::EXPR_COMPOUND_LITERAL; } void PCHStmtWriter::VisitExtVectorElementExpr(ExtVectorElementExpr *E) { VisitExpr(E); Writer.WriteSubExpr(E->getBase()); Writer.AddIdentifierRef(&E->getAccessor(), Record); Writer.AddSourceLocation(E->getAccessorLoc(), Record); Code = pch::EXPR_EXT_VECTOR_ELEMENT; } void PCHStmtWriter::VisitInitListExpr(InitListExpr *E) { VisitExpr(E); Record.push_back(E->getNumInits()); for (unsigned I = 0, N = E->getNumInits(); I != N; ++I) Writer.WriteSubExpr(E->getInit(I)); Writer.WriteSubExpr(E->getSyntacticForm()); Writer.AddSourceLocation(E->getLBraceLoc(), Record); Writer.AddSourceLocation(E->getRBraceLoc(), Record); Writer.AddDeclRef(E->getInitializedFieldInUnion(), Record); Record.push_back(E->hadArrayRangeDesignator()); Code = pch::EXPR_INIT_LIST; } void PCHStmtWriter::VisitDesignatedInitExpr(DesignatedInitExpr *E) { VisitExpr(E); Record.push_back(E->getNumSubExprs()); for (unsigned I = 0, N = E->getNumSubExprs(); I != N; ++I) Writer.WriteSubExpr(E->getSubExpr(I)); Writer.AddSourceLocation(E->getEqualOrColonLoc(), Record); Record.push_back(E->usesGNUSyntax()); for (DesignatedInitExpr::designators_iterator D = E->designators_begin(), DEnd = E->designators_end(); D != DEnd; ++D) { if (D->isFieldDesignator()) { if (FieldDecl *Field = D->getField()) { Record.push_back(pch::DESIG_FIELD_DECL); Writer.AddDeclRef(Field, Record); } else { Record.push_back(pch::DESIG_FIELD_NAME); Writer.AddIdentifierRef(D->getFieldName(), Record); } Writer.AddSourceLocation(D->getDotLoc(), Record); Writer.AddSourceLocation(D->getFieldLoc(), Record); } else if (D->isArrayDesignator()) { Record.push_back(pch::DESIG_ARRAY); Record.push_back(D->getFirstExprIndex()); Writer.AddSourceLocation(D->getLBracketLoc(), Record); Writer.AddSourceLocation(D->getRBracketLoc(), Record); } else { assert(D->isArrayRangeDesignator() && "Unknown designator"); Record.push_back(pch::DESIG_ARRAY_RANGE); Record.push_back(D->getFirstExprIndex()); Writer.AddSourceLocation(D->getLBracketLoc(), Record); Writer.AddSourceLocation(D->getEllipsisLoc(), Record); Writer.AddSourceLocation(D->getRBracketLoc(), Record); } } Code = pch::EXPR_DESIGNATED_INIT; } void PCHStmtWriter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { VisitExpr(E); Code = pch::EXPR_IMPLICIT_VALUE_INIT; } void PCHStmtWriter::VisitVAArgExpr(VAArgExpr *E) { VisitExpr(E); Writer.WriteSubExpr(E->getSubExpr()); Writer.AddSourceLocation(E->getBuiltinLoc(), Record); Writer.AddSourceLocation(E->getRParenLoc(), Record); Code = pch::EXPR_VA_ARG; } void PCHStmtWriter::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) { VisitExpr(E); Writer.AddTypeRef(E->getArgType1(), Record); Writer.AddTypeRef(E->getArgType2(), Record); Writer.AddSourceLocation(E->getBuiltinLoc(), Record); Writer.AddSourceLocation(E->getRParenLoc(), Record); Code = pch::EXPR_TYPES_COMPATIBLE; } void PCHStmtWriter::VisitChooseExpr(ChooseExpr *E) { VisitExpr(E); Writer.WriteSubExpr(E->getCond()); Writer.WriteSubExpr(E->getLHS()); Writer.WriteSubExpr(E->getRHS()); Writer.AddSourceLocation(E->getBuiltinLoc(), Record); Writer.AddSourceLocation(E->getRParenLoc(), Record); Code = pch::EXPR_CHOOSE; } void PCHStmtWriter::VisitGNUNullExpr(GNUNullExpr *E) { VisitExpr(E); Writer.AddSourceLocation(E->getTokenLocation(), Record); Code = pch::EXPR_GNU_NULL; } void PCHStmtWriter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { VisitExpr(E); Record.push_back(E->getNumSubExprs()); for (unsigned I = 0, N = E->getNumSubExprs(); I != N; ++I) Writer.WriteSubExpr(E->getExpr(I)); Writer.AddSourceLocation(E->getBuiltinLoc(), Record); Writer.AddSourceLocation(E->getRParenLoc(), Record); Code = pch::EXPR_SHUFFLE_VECTOR; } void PCHStmtWriter::VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { VisitExpr(E); Writer.AddDeclRef(E->getDecl(), Record); Writer.AddSourceLocation(E->getLocation(), Record); Record.push_back(E->isByRef()); Code = pch::EXPR_BLOCK_DECL_REF; } //===----------------------------------------------------------------------===// // PCHWriter Implementation //===----------------------------------------------------------------------===// /// \brief Write the target triple (e.g., i686-apple-darwin9). void PCHWriter::WriteTargetTriple(const TargetInfo &Target) { using namespace llvm; BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name unsigned TripleAbbrev = S.EmitAbbrev(Abbrev); RecordData Record; Record.push_back(pch::TARGET_TRIPLE); const char *Triple = Target.getTargetTriple(); S.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple)); } /// \brief Write the LangOptions structure. void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) { RecordData Record; Record.push_back(LangOpts.Trigraphs); Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments. Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers. Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode. Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc) Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'. Record.push_back(LangOpts.Digraphs); // C94, C99 and C++ Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants. Record.push_back(LangOpts.C99); // C99 Support Record.push_back(LangOpts.Microsoft); // Microsoft extensions. Record.push_back(LangOpts.CPlusPlus); // C++ Support Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode. Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords. Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled. Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled. Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings Record.push_back(LangOpts.Boolean); // Allow bool/true/false Record.push_back(LangOpts.WritableStrings); // Allow writable strings Record.push_back(LangOpts.LaxVectorConversions); Record.push_back(LangOpts.Exceptions); // Support exception handling. Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime. Record.push_back(LangOpts.Freestanding); // Freestanding implementation Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin) Record.push_back(LangOpts.ThreadsafeStatics); // Whether static initializers are protected // by locks. Record.push_back(LangOpts.Blocks); // block extension to C Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if // they are unused. Record.push_back(LangOpts.MathErrno); // Math functions must respect errno // (modulo the platform support). Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when // signed integer arithmetic overflows. Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and // may be ripped out at any time. Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined. Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be // defined. Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as // opposed to __DYNAMIC__). Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero. Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be // used (instead of C99 semantics). Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined. Record.push_back(LangOpts.getGCMode()); Record.push_back(LangOpts.getVisibilityMode()); Record.push_back(LangOpts.InstantiationDepth); S.EmitRecord(pch::LANGUAGE_OPTIONS, Record); } //===----------------------------------------------------------------------===// // Source Manager Serialization //===----------------------------------------------------------------------===// /// \brief Create an abbreviation for the SLocEntry that refers to a /// file. static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &S) { using namespace llvm; BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name return S.EmitAbbrev(Abbrev); } /// \brief Create an abbreviation for the SLocEntry that refers to a /// buffer. static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &S) { using namespace llvm; BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob return S.EmitAbbrev(Abbrev); } /// \brief Create an abbreviation for the SLocEntry that refers to a /// buffer's blob. static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &S) { using namespace llvm; BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob return S.EmitAbbrev(Abbrev); } /// \brief Create an abbreviation for the SLocEntry that refers to an /// buffer. static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &S) { using namespace llvm; BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length return S.EmitAbbrev(Abbrev); } /// \brief Writes the block containing the serialized form of the /// source manager. /// /// TODO: We should probably use an on-disk hash table (stored in a /// blob), indexed based on the file name, so that we only create /// entries for files that we actually need. In the common case (no /// errors), we probably won't have to create file entries for any of /// the files in the AST. void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) { // Enter the source manager block. S.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3); // Abbreviations for the various kinds of source-location entries. int SLocFileAbbrv = -1; int SLocBufferAbbrv = -1; int SLocBufferBlobAbbrv = -1; int SLocInstantiationAbbrv = -1; // Write out the source location entry table. We skip the first // entry, which is always the same dummy entry. RecordData Record; for (SourceManager::sloc_entry_iterator SLoc = SourceMgr.sloc_entry_begin() + 1, SLocEnd = SourceMgr.sloc_entry_end(); SLoc != SLocEnd; ++SLoc) { // Figure out which record code to use. unsigned Code; if (SLoc->isFile()) { if (SLoc->getFile().getContentCache()->Entry) Code = pch::SM_SLOC_FILE_ENTRY; else Code = pch::SM_SLOC_BUFFER_ENTRY; } else Code = pch::SM_SLOC_INSTANTIATION_ENTRY; Record.push_back(Code); Record.push_back(SLoc->getOffset()); if (SLoc->isFile()) { const SrcMgr::FileInfo &File = SLoc->getFile(); Record.push_back(File.getIncludeLoc().getRawEncoding()); Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding Record.push_back(File.hasLineDirectives()); const SrcMgr::ContentCache *Content = File.getContentCache(); if (Content->Entry) { // The source location entry is a file. The blob associated // with this entry is the file name. if (SLocFileAbbrv == -1) SLocFileAbbrv = CreateSLocFileAbbrev(S); S.EmitRecordWithBlob(SLocFileAbbrv, Record, Content->Entry->getName(), strlen(Content->Entry->getName())); } else { // The source location entry is a buffer. The blob associated // with this entry contains the contents of the buffer. if (SLocBufferAbbrv == -1) { SLocBufferAbbrv = CreateSLocBufferAbbrev(S); SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(S); } // We add one to the size so that we capture the trailing NULL // that is required by llvm::MemoryBuffer::getMemBuffer (on // the reader side). const llvm::MemoryBuffer *Buffer = Content->getBuffer(); const char *Name = Buffer->getBufferIdentifier(); S.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1); Record.clear(); Record.push_back(pch::SM_SLOC_BUFFER_BLOB); S.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Buffer->getBufferStart(), Buffer->getBufferSize() + 1); } } else { // The source location entry is an instantiation. const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation(); Record.push_back(Inst.getSpellingLoc().getRawEncoding()); Record.push_back(Inst.getInstantiationLocStart().getRawEncoding()); Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding()); // Compute the token length for this macro expansion. unsigned NextOffset = SourceMgr.getNextOffset(); SourceManager::sloc_entry_iterator NextSLoc = SLoc; if (++NextSLoc != SLocEnd) NextOffset = NextSLoc->getOffset(); Record.push_back(NextOffset - SLoc->getOffset() - 1); if (SLocInstantiationAbbrv == -1) SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(S); S.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record); } Record.clear(); } // Write the line table. if (SourceMgr.hasLineTable()) { LineTableInfo &LineTable = SourceMgr.getLineTable(); // Emit the file names Record.push_back(LineTable.getNumFilenames()); for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) { // Emit the file name const char *Filename = LineTable.getFilename(I); unsigned FilenameLen = Filename? strlen(Filename) : 0; Record.push_back(FilenameLen); if (FilenameLen) Record.insert(Record.end(), Filename, Filename + FilenameLen); } // Emit the line entries for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); L != LEnd; ++L) { // Emit the file ID Record.push_back(L->first); // Emit the line entries Record.push_back(L->second.size()); for (std::vector<LineEntry>::iterator LE = L->second.begin(), LEEnd = L->second.end(); LE != LEEnd; ++LE) { Record.push_back(LE->FileOffset); Record.push_back(LE->LineNo); Record.push_back(LE->FilenameID); Record.push_back((unsigned)LE->FileKind); Record.push_back(LE->IncludeOffset); } S.EmitRecord(pch::SM_LINE_TABLE, Record); } } S.ExitBlock(); } /// \brief Writes the block containing the serialized form of the /// preprocessor. /// void PCHWriter::WritePreprocessor(const Preprocessor &PP) { // Enter the preprocessor block. S.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 3); // If the PCH file contains __DATE__ or __TIME__ emit a warning about this. // FIXME: use diagnostics subsystem for localization etc. if (PP.SawDateOrTime()) fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); RecordData Record; // If the preprocessor __COUNTER__ value has been bumped, remember it. if (PP.getCounterValue() != 0) { Record.push_back(PP.getCounterValue()); S.EmitRecord(pch::PP_COUNTER_VALUE, Record); Record.clear(); } // Loop over all the macro definitions that are live at the end of the file, // emitting each to the PP section. // FIXME: Eventually we want to emit an index so that we can lazily load // macros. for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end(); I != E; ++I) { // FIXME: This emits macros in hash table order, we should do it in a stable // order so that output is reproducible. MacroInfo *MI = I->second; // Don't emit builtin macros like __LINE__ to the PCH file unless they have // been redefined by the header (in which case they are not isBuiltinMacro). if (MI->isBuiltinMacro()) continue; AddIdentifierRef(I->first, Record); Record.push_back(MI->getDefinitionLoc().getRawEncoding()); Record.push_back(MI->isUsed()); unsigned Code; if (MI->isObjectLike()) { Code = pch::PP_MACRO_OBJECT_LIKE; } else { Code = pch::PP_MACRO_FUNCTION_LIKE; Record.push_back(MI->isC99Varargs()); Record.push_back(MI->isGNUVarargs()); Record.push_back(MI->getNumArgs()); for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); I != E; ++I) AddIdentifierRef(*I, Record); } S.EmitRecord(Code, Record); Record.clear(); // Emit the tokens array. for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { // Note that we know that the preprocessor does not have any annotation // tokens in it because they are created by the parser, and thus can't be // in a macro definition. const Token &Tok = MI->getReplacementToken(TokNo); Record.push_back(Tok.getLocation().getRawEncoding()); Record.push_back(Tok.getLength()); // FIXME: When reading literal tokens, reconstruct the literal pointer if // it is needed. AddIdentifierRef(Tok.getIdentifierInfo(), Record); // FIXME: Should translate token kind to a stable encoding. Record.push_back(Tok.getKind()); // FIXME: Should translate token flags to a stable encoding. Record.push_back(Tok.getFlags()); S.EmitRecord(pch::PP_TOKEN, Record); Record.clear(); } } S.ExitBlock(); } /// \brief Write the representation of a type to the PCH stream. void PCHWriter::WriteType(const Type *T) { pch::TypeID &ID = TypeIDs[T]; if (ID == 0) // we haven't seen this type before. ID = NextTypeID++; // Record the offset for this type. if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS) TypeOffsets.push_back(S.GetCurrentBitNo()); else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) { TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS); TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = S.GetCurrentBitNo(); } RecordData Record; // Emit the type's representation. PCHTypeWriter W(*this, Record); switch (T->getTypeClass()) { // For all of the concrete, non-dependent types, call the // appropriate visitor function. #define TYPE(Class, Base) \ case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break; #define ABSTRACT_TYPE(Class, Base) #define DEPENDENT_TYPE(Class, Base) #include "clang/AST/TypeNodes.def" // For all of the dependent type nodes (which only occur in C++ // templates), produce an error. #define TYPE(Class, Base) #define DEPENDENT_TYPE(Class, Base) case Type::Class: #include "clang/AST/TypeNodes.def" assert(false && "Cannot serialize dependent type nodes"); break; } // Emit the serialized record. S.EmitRecord(W.Code, Record); // Flush any expressions that were written as part of this type. FlushExprs(); } /// \brief Write a block containing all of the types. void PCHWriter::WriteTypesBlock(ASTContext &Context) { // Enter the types block. S.EnterSubblock(pch::TYPES_BLOCK_ID, 2); // Emit all of the types in the ASTContext for (std::vector<Type*>::const_iterator T = Context.getTypes().begin(), TEnd = Context.getTypes().end(); T != TEnd; ++T) { // Builtin types are never serialized. if (isa<BuiltinType>(*T)) continue; WriteType(*T); } // Exit the types block S.ExitBlock(); } /// \brief Write the block containing all of the declaration IDs /// lexically declared within the given DeclContext. /// /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the /// bistream, or 0 if no block was written. uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC) { if (DC->decls_empty(Context)) return 0; uint64_t Offset = S.GetCurrentBitNo(); RecordData Record; for (DeclContext::decl_iterator D = DC->decls_begin(Context), DEnd = DC->decls_end(Context); D != DEnd; ++D) AddDeclRef(*D, Record); S.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record); return Offset; } /// \brief Write the block containing all of the declaration IDs /// visible from the given DeclContext. /// /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the /// bistream, or 0 if no block was written. uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC) { if (DC->getPrimaryContext() != DC) return 0; // Force the DeclContext to build a its name-lookup table. DC->lookup(Context, DeclarationName()); // Serialize the contents of the mapping used for lookup. Note that, // although we have two very different code paths, the serialized // representation is the same for both cases: a declaration name, // followed by a size, followed by references to the visible // declarations that have that name. uint64_t Offset = S.GetCurrentBitNo(); RecordData Record; StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); if (!Map) return 0; for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); D != DEnd; ++D) { AddDeclarationName(D->first, Record); DeclContext::lookup_result Result = D->second.getLookupResult(Context); Record.push_back(Result.second - Result.first); for(; Result.first != Result.second; ++Result.first) AddDeclRef(*Result.first, Record); } if (Record.size() == 0) return 0; S.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record); return Offset; } /// \brief Write a block containing all of the declarations. void PCHWriter::WriteDeclsBlock(ASTContext &Context) { // Enter the declarations block. S.EnterSubblock(pch::DECLS_BLOCK_ID, 2); // Emit all of the declarations. RecordData Record; PCHDeclWriter W(*this, Record); while (!DeclsToEmit.empty()) { // Pull the next declaration off the queue Decl *D = DeclsToEmit.front(); DeclsToEmit.pop(); // If this declaration is also a DeclContext, write blocks for the // declarations that lexically stored inside its context and those // declarations that are visible from its context. These blocks // are written before the declaration itself so that we can put // their offsets into the record for the declaration. uint64_t LexicalOffset = 0; uint64_t VisibleOffset = 0; DeclContext *DC = dyn_cast<DeclContext>(D); if (DC) { LexicalOffset = WriteDeclContextLexicalBlock(Context, DC); VisibleOffset = WriteDeclContextVisibleBlock(Context, DC); } // Determine the ID for this declaration pch::DeclID ID = DeclIDs[D]; if (ID == 0) ID = DeclIDs.size(); unsigned Index = ID - 1; // Record the offset for this declaration if (DeclOffsets.size() == Index) DeclOffsets.push_back(S.GetCurrentBitNo()); else if (DeclOffsets.size() < Index) { DeclOffsets.resize(Index+1); DeclOffsets[Index] = S.GetCurrentBitNo(); } // Build and emit a record for this declaration Record.clear(); W.Code = (pch::DeclCode)0; W.Visit(D); if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset); assert(W.Code && "Unhandled declaration kind while generating PCH"); S.EmitRecord(W.Code, Record); // If the declaration had any attributes, write them now. if (D->hasAttrs()) WriteAttributeRecord(D->getAttrs()); // Flush any expressions that were written as part of this declaration. FlushExprs(); // Note external declarations so that we can add them to a record // in the PCH file later. if (isa<FileScopeAsmDecl>(D)) ExternalDefinitions.push_back(ID); else if (VarDecl *Var = dyn_cast<VarDecl>(D)) { if (// Non-static file-scope variables with initializers or that // are tentative definitions. (Var->isFileVarDecl() && (Var->getInit() || Var->getStorageClass() == VarDecl::None)) || // Out-of-line definitions of static data members (C++). (Var->getDeclContext()->isRecord() && !Var->getLexicalDeclContext()->isRecord() && Var->getStorageClass() == VarDecl::Static)) ExternalDefinitions.push_back(ID); } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) { if (Func->isThisDeclarationADefinition() && Func->getStorageClass() != FunctionDecl::Static && !Func->isInline()) ExternalDefinitions.push_back(ID); } } // Exit the declarations block S.ExitBlock(); } /// \brief Write the identifier table into the PCH file. /// /// The identifier table consists of a blob containing string data /// (the actual identifiers themselves) and a separate "offsets" index /// that maps identifier IDs to locations within the blob. void PCHWriter::WriteIdentifierTable() { using namespace llvm; // Create and write out the blob that contains the identifier // strings. RecordData IdentOffsets; IdentOffsets.resize(IdentifierIDs.size()); { // Create the identifier string data. std::vector<char> Data; Data.push_back(0); // Data must not be empty. for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end(); ID != IDEnd; ++ID) { assert(ID->first && "NULL identifier in identifier table"); // Make sure we're starting on an odd byte. The PCH reader // expects the low bit to be set on all of the offsets. if ((Data.size() & 0x01) == 0) Data.push_back((char)0); IdentOffsets[ID->second - 1] = Data.size(); Data.insert(Data.end(), ID->first->getName(), ID->first->getName() + ID->first->getLength()); Data.push_back((char)0); } // Create a blob abbreviation BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name unsigned IDTableAbbrev = S.EmitAbbrev(Abbrev); // Write the identifier table RecordData Record; Record.push_back(pch::IDENTIFIER_TABLE); S.EmitRecordWithBlob(IDTableAbbrev, Record, &Data.front(), Data.size()); } // Write the offsets table for identifier IDs. S.EmitRecord(pch::IDENTIFIER_OFFSET, IdentOffsets); } /// \brief Write a record containing the given attributes. void PCHWriter::WriteAttributeRecord(const Attr *Attr) { RecordData Record; for (; Attr; Attr = Attr->getNext()) { Record.push_back(Attr->getKind()); // FIXME: stable encoding Record.push_back(Attr->isInherited()); switch (Attr->getKind()) { case Attr::Alias: AddString(cast<AliasAttr>(Attr)->getAliasee(), Record); break; case Attr::Aligned: Record.push_back(cast<AlignedAttr>(Attr)->getAlignment()); break; case Attr::AlwaysInline: break; case Attr::AnalyzerNoReturn: break; case Attr::Annotate: AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record); break; case Attr::AsmLabel: AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record); break; case Attr::Blocks: Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable break; case Attr::Cleanup: AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record); break; case Attr::Const: break; case Attr::Constructor: Record.push_back(cast<ConstructorAttr>(Attr)->getPriority()); break; case Attr::DLLExport: case Attr::DLLImport: case Attr::Deprecated: break; case Attr::Destructor: Record.push_back(cast<DestructorAttr>(Attr)->getPriority()); break; case Attr::FastCall: break; case Attr::Format: { const FormatAttr *Format = cast<FormatAttr>(Attr); AddString(Format->getType(), Record); Record.push_back(Format->getFormatIdx()); Record.push_back(Format->getFirstArg()); break; } case Attr::GNUCInline: case Attr::IBOutletKind: case Attr::NoReturn: case Attr::NoThrow: case Attr::Nodebug: case Attr::Noinline: break; case Attr::NonNull: { const NonNullAttr *NonNull = cast<NonNullAttr>(Attr); Record.push_back(NonNull->size()); Record.insert(Record.end(), NonNull->begin(), NonNull->end()); break; } case Attr::ObjCException: case Attr::ObjCNSObject: case Attr::Overloadable: break; case Attr::Packed: Record.push_back(cast<PackedAttr>(Attr)->getAlignment()); break; case Attr::Pure: break; case Attr::Regparm: Record.push_back(cast<RegparmAttr>(Attr)->getNumParams()); break; case Attr::Section: AddString(cast<SectionAttr>(Attr)->getName(), Record); break; case Attr::StdCall: case Attr::TransparentUnion: case Attr::Unavailable: case Attr::Unused: case Attr::Used: break; case Attr::Visibility: // FIXME: stable encoding Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility()); break; case Attr::WarnUnusedResult: case Attr::Weak: case Attr::WeakImport: break; } } S.EmitRecord(pch::DECL_ATTR, Record); } void PCHWriter::AddString(const std::string &Str, RecordData &Record) { Record.push_back(Str.size()); Record.insert(Record.end(), Str.begin(), Str.end()); } PCHWriter::PCHWriter(llvm::BitstreamWriter &S) : S(S), NextTypeID(pch::NUM_PREDEF_TYPE_IDS) { } void PCHWriter::WritePCH(ASTContext &Context, const Preprocessor &PP) { // Emit the file header. S.Emit((unsigned)'C', 8); S.Emit((unsigned)'P', 8); S.Emit((unsigned)'C', 8); S.Emit((unsigned)'H', 8); // The translation unit is the first declaration we'll emit. DeclIDs[Context.getTranslationUnitDecl()] = 1; DeclsToEmit.push(Context.getTranslationUnitDecl()); // Write the remaining PCH contents. S.EnterSubblock(pch::PCH_BLOCK_ID, 3); WriteTargetTriple(Context.Target); WriteLanguageOptions(Context.getLangOptions()); WriteSourceManagerBlock(Context.getSourceManager()); WritePreprocessor(PP); WriteTypesBlock(Context); WriteDeclsBlock(Context); WriteIdentifierTable(); S.EmitRecord(pch::TYPE_OFFSET, TypeOffsets); S.EmitRecord(pch::DECL_OFFSET, DeclOffsets); if (!ExternalDefinitions.empty()) S.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions); S.ExitBlock(); } void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) { Record.push_back(Loc.getRawEncoding()); } void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) { Record.push_back(Value.getBitWidth()); unsigned N = Value.getNumWords(); const uint64_t* Words = Value.getRawData(); for (unsigned I = 0; I != N; ++I) Record.push_back(Words[I]); } void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) { Record.push_back(Value.isUnsigned()); AddAPInt(Value, Record); } void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) { AddAPInt(Value.bitcastToAPInt(), Record); } void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) { if (II == 0) { Record.push_back(0); return; } pch::IdentID &ID = IdentifierIDs[II]; if (ID == 0) ID = IdentifierIDs.size(); Record.push_back(ID); } void PCHWriter::AddTypeRef(QualType T, RecordData &Record) { if (T.isNull()) { Record.push_back(pch::PREDEF_TYPE_NULL_ID); return; } if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) { pch::TypeID ID = 0; switch (BT->getKind()) { case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break; case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break; case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break; case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break; case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break; case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break; case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break; case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break; case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break; case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break; case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break; case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break; case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break; case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break; case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break; case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break; case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break; case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break; case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break; case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break; } Record.push_back((ID << 3) | T.getCVRQualifiers()); return; } pch::TypeID &ID = TypeIDs[T.getTypePtr()]; if (ID == 0) // we haven't seen this type before ID = NextTypeID++; // Encode the type qualifiers in the type reference. Record.push_back((ID << 3) | T.getCVRQualifiers()); } void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) { if (D == 0) { Record.push_back(0); return; } pch::DeclID &ID = DeclIDs[D]; if (ID == 0) { // We haven't seen this declaration before. Give it a new ID and // enqueue it in the list of declarations to emit. ID = DeclIDs.size(); DeclsToEmit.push(const_cast<Decl *>(D)); } Record.push_back(ID); } void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) { Record.push_back(Name.getNameKind()); switch (Name.getNameKind()) { case DeclarationName::Identifier: AddIdentifierRef(Name.getAsIdentifierInfo(), Record); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: assert(false && "Serialization of Objective-C selectors unavailable"); break; case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: AddTypeRef(Name.getCXXNameType(), Record); break; case DeclarationName::CXXOperatorName: Record.push_back(Name.getCXXOverloadedOperator()); break; case DeclarationName::CXXUsingDirective: // No extra data to emit break; } } /// \brief Write the given subexpression to the bitstream. void PCHWriter::WriteSubExpr(Expr *E) { RecordData Record; PCHStmtWriter Writer(*this, Record); if (!E) { S.EmitRecord(pch::EXPR_NULL, Record); return; } Writer.Code = pch::EXPR_NULL; Writer.Visit(E); assert(Writer.Code != pch::EXPR_NULL && "Unhandled expression writing PCH file"); S.EmitRecord(Writer.Code, Record); } /// \brief Flush all of the expressions that have been added to the /// queue via AddExpr(). void PCHWriter::FlushExprs() { RecordData Record; PCHStmtWriter Writer(*this, Record); for (unsigned I = 0, N = ExprsToEmit.size(); I != N; ++I) { Expr *E = ExprsToEmit[I]; if (!E) { S.EmitRecord(pch::EXPR_NULL, Record); continue; } Writer.Code = pch::EXPR_NULL; Writer.Visit(E); assert(Writer.Code != pch::EXPR_NULL && "Unhandled expression writing PCH file"); S.EmitRecord(Writer.Code, Record); assert(N == ExprsToEmit.size() && "Subexpression writen via AddExpr rather than WriteSubExpr!"); // Note that we are at the end of a full expression. Any // expression records that follow this one are part of a different // expression. Record.clear(); S.EmitRecord(pch::EXPR_STOP, Record); } ExprsToEmit.clear(); } <file_sep>/test/Coverage/targets.c // RUN: clang-cc -g -triple i686-unknown-unknown -emit-llvm -o %t %s && // RUN: clang-cc -g -triple i686-pc-linux-gnu -emit-llvm -o %t %s && // RUN: clang-cc -g -triple i686-unknown-dragonfly -emit-llvm -o %t %s && // RUN: clang-cc -g -triple i686-unknown-win32 -emit-llvm -o %t %s && // RUN: clang-cc -g -triple i686-apple-darwin9 -emit-llvm -o %t %s && // RUN: clang-cc -g -triple x86_64-unknown-unknown -emit-llvm -o %t %s && // RUN: clang-cc -g -triple x86_64-pc-linux-gnu -emit-llvm -o %t %s && // RUN: clang-cc -g -triple x86_64-apple-darwin9 -emit-llvm -o %t %s && // RUN: clang-cc -g -triple ppc-unknown-unknown -emit-llvm -o %t %s && // RUN: clang-cc -g -triple ppc-apple-darwin9 -emit-llvm -o %t %s && // RUN: clang-cc -g -triple ppc64-unknown-unknown -emit-llvm -o %t %s && // RUN: clang-cc -g -triple ppc64-apple-darwin9 -emit-llvm -o %t %s && // RUN: clang-cc -g -triple armv6-unknown-unknown -emit-llvm -o %t %s && // RUN: clang-cc -g -triple armv6-apple-darwin9 -emit-llvm -o %t %s && // RUN: clang-cc -g -triple sparc-unknown-unknown -emit-llvm -o %t %s && // RUN: clang-cc -g -triple sparc-unknown-solaris -emit-llvm -o %t %s && // RUN: clang-cc -g -triple pic16-unknown-unknown -emit-llvm -o %t %s && // RUN: true <file_sep>/test/SemaTemplate/instantiate-enum.cpp // RUN: clang-cc -fsyntax-only %s template<typename T, T I, int J> struct adder { enum { value = I + J, value2 }; }; int array1[adder<long, 3, 4>::value == 7? 1 : -1]; <file_sep>/test/SemaCXX/try-catch.cpp // RUN: clang-cc -fsyntax-only -verify %s struct A; // expected-note 3 {{forward declaration of 'struct A'}} void f() { try { } catch(int i) { // expected-note {{previous definition}} int j = i; int i; // expected-error {{redefinition of 'i'}} } catch(float i) { } catch(void v) { // expected-error {{cannot catch incomplete type 'void'}} } catch(A a) { // expected-error {{cannot catch incomplete type 'struct A'}} } catch(A *a) { // expected-error {{cannot catch pointer to incomplete type 'struct A'}} } catch(A &a) { // expected-error {{cannot catch reference to incomplete type 'struct A'}} } catch(...) { int j = i; // expected-error {{use of undeclared identifier 'i'}} } try { } catch(...) { // expected-error {{catch-all handler must come last}} } catch(int) { } } <file_sep>/test/CodeGen/vector.c // RUN: clang-cc -emit-llvm %s -o - typedef short __v4hi __attribute__ ((__vector_size__ (8))); void f() { __v4hi A = (__v4hi)0LL; } __v4hi x = {1,2,3}; __v4hi y = {1,2,3,4}; typedef int vty __attribute((vector_size(16))); int a() { vty b; return b[2LL]; } <file_sep>/include/clang/AST/ExternalASTSource.h //===--- ExternalASTSource.h - Abstract External AST Interface --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ExternalASTSource interface, // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H #define LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H #include "clang/AST/DeclarationName.h" #include "clang/AST/Type.h" #include "llvm/ADT/SmallVector.h" namespace clang { class ASTConsumer; class Decl; class DeclContext; /// \brief The deserialized representation of a set of declarations /// with the same name that are visible in a given context. struct VisibleDeclaration { /// \brief The name of the declarations. DeclarationName Name; /// \brief The ID numbers of all of the declarations with this name. /// /// These declarations have not necessarily been de-serialized. llvm::SmallVector<unsigned, 4> Declarations; }; /// \brief Abstract interface for external sources of AST nodes. /// /// External AST sources provide AST nodes constructed from some /// external source, such as a precompiled header. External AST /// sources can resolve types and declarations from abstract IDs into /// actual type and declaration nodes, and read parts of declaration /// contexts. class ExternalASTSource { public: virtual ~ExternalASTSource(); /// \brief Resolve a type ID into a type, potentially building a new /// type. virtual QualType GetType(unsigned ID) = 0; /// \brief Resolve a declaration ID into a declaration, potentially /// building a new declaration. virtual Decl *GetDecl(unsigned ID) = 0; /// \brief Read all of the declarations lexically stored in a /// declaration context. /// /// \param DC The declaration context whose declarations will be /// read. /// /// \param Decls Vector that will contain the declarations loaded /// from the external source. The caller is responsible for merging /// these declarations with any declarations already stored in the /// declaration context. /// /// \returns true if there was an error while reading the /// declarations for this declaration context. virtual bool ReadDeclsLexicallyInContext(DeclContext *DC, llvm::SmallVectorImpl<unsigned> &Decls) = 0; /// \brief Read all of the declarations visible from a declaration /// context. /// /// \param DC The declaration context whose visible declarations /// will be read. /// /// \param Decls A vector of visible declaration structures, /// providing the mapping from each name visible in the declaration /// context to the declaration IDs of declarations with that name. /// /// \returns true if there was an error while reading the /// declarations for this declaration context. virtual bool ReadDeclsVisibleInContext(DeclContext *DC, llvm::SmallVectorImpl<VisibleDeclaration> & Decls) = 0; /// \brief Function that will be invoked when we begin parsing a new /// translation unit involving this external AST source. virtual void StartTranslationUnit(ASTConsumer *Consumer) { } /// \brief Print any statistics that have been gathered regarding /// the external AST source. virtual void PrintStats(); }; } // end namespace clang #endif // LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H <file_sep>/include/clang/Basic/FileManager.h //===--- FileManager.h - File System Probing and Caching --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the FileManager interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FILEMANAGER_H #define LLVM_CLANG_FILEMANAGER_H #include "llvm/ADT/StringMap.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Bitcode/SerializationFwd.h" #include "llvm/Support/Allocator.h" #include "llvm/Config/config.h" // for mode_t #include <map> #include <set> #include <string> // FIXME: Enhance libsystem to support inode and other fields in stat. #include <sys/types.h> #include <sys/stat.h> namespace clang { class FileManager; /// DirectoryEntry - Cached information about one directory on the disk. /// class DirectoryEntry { const char *Name; // Name of the directory. friend class FileManager; public: DirectoryEntry() : Name(0) {} const char *getName() const { return Name; } }; /// FileEntry - Cached information about one file on the disk. /// class FileEntry { const char *Name; // Name of the file. off_t Size; // File size in bytes. time_t ModTime; // Modification time of file. const DirectoryEntry *Dir; // Directory file lives in. unsigned UID; // A unique (small) ID for the file. dev_t Device; // ID for the device containing the file. ino_t Inode; // Inode number for the file. mode_t FileMode; // The file mode as returned by 'stat'. friend class FileManager; public: FileEntry(dev_t device, ino_t inode, mode_t m) : Name(0), Device(device), Inode(inode), FileMode(m) {} // Add a default constructor for use with llvm::StringMap FileEntry() : Name(0), Device(0), Inode(0), FileMode(0) {} const char *getName() const { return Name; } off_t getSize() const { return Size; } unsigned getUID() const { return UID; } ino_t getInode() const { return Inode; } dev_t getDevice() const { return Device; } time_t getModificationTime() const { return ModTime; } mode_t getFileMode() const { return FileMode; } /// getDir - Return the directory the file lives in. /// const DirectoryEntry *getDir() const { return Dir; } bool operator<(const FileEntry& RHS) const { return Device < RHS.Device || (Device == RHS.Device && Inode < RHS.Inode); } }; // FIXME: This is a lightweight shim that is used by FileManager to cache // 'stat' system calls. We will use it with PTH to identify if caching // stat calls in PTH files is a performance win. class StatSysCallCache { public: virtual ~StatSysCallCache() {} virtual int stat(const char *path, struct stat *buf) = 0; }; /// FileManager - Implements support for file system lookup, file system /// caching, and directory search management. This also handles more advanced /// properties, such as uniquing files based on "inode", so that a file with two /// names (e.g. symlinked) will be treated as a single file. /// class FileManager { class UniqueDirContainer; class UniqueFileContainer; /// UniqueDirs/UniqueFiles - Cache for existing directories/files. /// UniqueDirContainer &UniqueDirs; UniqueFileContainer &UniqueFiles; /// DirEntries/FileEntries - This is a cache of directory/file entries we have /// looked up. The actual Entry is owned by UniqueFiles/UniqueDirs above. /// llvm::StringMap<DirectoryEntry*, llvm::BumpPtrAllocator> DirEntries; llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator> FileEntries; /// NextFileUID - Each FileEntry we create is assigned a unique ID #. /// unsigned NextFileUID; // Statistics. unsigned NumDirLookups, NumFileLookups; unsigned NumDirCacheMisses, NumFileCacheMisses; // Caching. llvm::OwningPtr<StatSysCallCache> StatCache; int stat_cached(const char* path, struct stat* buf) { return StatCache.get() ? StatCache->stat(path, buf) : stat(path, buf); } public: FileManager(); ~FileManager(); /// setStatCache - Installs the provided StatSysCallCache object within /// the FileManager. Ownership of this object is transferred to the /// FileManager. void setStatCache(StatSysCallCache *statCache) { StatCache.reset(statCache); } /// getDirectory - Lookup, cache, and verify the specified directory. This /// returns null if the directory doesn't exist. /// const DirectoryEntry *getDirectory(const std::string &Filename) { return getDirectory(&Filename[0], &Filename[0] + Filename.size()); } const DirectoryEntry *getDirectory(const char *FileStart,const char *FileEnd); /// getFile - Lookup, cache, and verify the specified file. This returns null /// if the file doesn't exist. /// const FileEntry *getFile(const std::string &Filename) { return getFile(&Filename[0], &Filename[0] + Filename.size()); } const FileEntry *getFile(const char *FilenameStart, const char *FilenameEnd); void PrintStats() const; }; } // end namespace clang #endif <file_sep>/test/CodeGen/designated-initializers.c // RUN: clang-cc -triple i386-unknown-unknown %s -emit-llvm -o - | grep "<{ i8\* null, i32 1024 }>" && // RUN: clang-cc -triple i386-unknown-unknown %s -emit-llvm -o - | grep "i32 0, i32 22" struct foo { void *a; int b; }; union { int i; float f; } u = { }; int main(int argc, char **argv) { union { int i; float f; } u2 = { }; static struct foo foo = { .b = 1024, }; } int b[2] = { [1] 22 }; <file_sep>/test/CodeGen/cfstring.c // RUN: clang-cc -emit-llvm %s -o %t #define CFSTR __builtin___CFStringMakeConstantString void f() { CFSTR("Hello, World!"); } // rdar://6248329 void *G = CFSTR("yo joe"); void h() { static void* h = CFSTR("Goodbye, World!"); } <file_sep>/test/CodeGen/PR3589-freestanding-libcalls.c // RUN: clang-cc -emit-llvm %s -o - | grep 'declare i32 @printf' | count 1 && // RUN: clang-cc -O2 -emit-llvm %s -o - | grep 'declare i32 @puts' | count 1 && // RUN: clang-cc -ffreestanding -O2 -emit-llvm %s -o - | grep 'declare i32 @puts' | count 0 #include <stdio.h> void f0() { printf("hello\n"); } <file_sep>/test/Lexer/cxx0x_keyword.cpp // RUN: clang-cc -fsyntax-only -verify -std=c++0x %s 2>&1 int static_assert; /* expected-error {{expected unqualified-id}} */ <file_sep>/test/Frontend/dependency-gen.c // rdar://6533411 // RUN: clang -MD -MF %t.d -c -x c -o %t.o /dev/null && // RUN: grep '.*dependency-gen.c.out.tmp.o:' %t.d && // RUN: grep '/dev/null' %t.d && // RUN: clang -M -x c /dev/null -o %t.deps && // RUN: grep 'null.o: /dev/null' %t.deps <file_sep>/tools/clang-cc/clang-cc.cpp //===--- clang.cpp - C-Language Front-end ---------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility may be invoked in the following manner: // clang --help - Output help info. // clang [options] - Read from stdin. // clang [options] file - Read from "file". // clang [options] file1 file2 - Read these files. // //===----------------------------------------------------------------------===// // // TODO: Options to support: // // -Wfatal-errors // -ftabstop=width // //===----------------------------------------------------------------------===// #include "clang-cc.h" #include "ASTConsumers.h" #include "clang/Frontend/CompileOptions.h" #include "clang/Frontend/FixItRewriter.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/InitHeaderSearch.h" #include "clang/Frontend/PathDiagnosticClients.h" #include "clang/Frontend/PCHReader.h" #include "clang/Frontend/TextDiagnosticBuffer.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Analysis/PathDiagnostic.h" #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Sema/ParseAST.h" #include "clang/Sema/SemaDiagnostic.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "clang/Parse/Parser.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Config/config.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Timer.h" #include "llvm/System/Host.h" #include "llvm/System/Path.h" #include "llvm/System/Signals.h" #include <cstdlib> using namespace clang; //===----------------------------------------------------------------------===// // Source Location Parser //===----------------------------------------------------------------------===// /// \brief A source location that has been parsed on the command line. struct ParsedSourceLocation { std::string FileName; unsigned Line; unsigned Column; /// \brief Try to resolve the file name of a parsed source location. /// /// \returns true if there was an error, false otherwise. bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result); }; bool ParsedSourceLocation::ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result) { const FileEntry *File = FileMgr.getFile(FileName); if (!File) return true; Result.File = File; Result.Line = Line; Result.Column = Column; return false; } namespace llvm { namespace cl { /// \brief Command-line option parser that parses source locations. /// /// Source locations are of the form filename:line:column. template<> class parser<ParsedSourceLocation> : public basic_parser<ParsedSourceLocation> { public: bool parse(Option &O, const char *ArgName, const std::string &ArgValue, ParsedSourceLocation &Val); }; bool parser<ParsedSourceLocation>:: parse(Option &O, const char *ArgName, const std::string &ArgValue, ParsedSourceLocation &Val) { using namespace clang; const char *ExpectedFormat = "source location must be of the form filename:line:column"; std::string::size_type SecondColon = ArgValue.rfind(':'); if (SecondColon == std::string::npos) { std::fprintf(stderr, "%s\n", ExpectedFormat); return true; } char *EndPtr; long Column = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10); if (EndPtr != ArgValue.c_str() + ArgValue.size()) { std::fprintf(stderr, "%s\n", ExpectedFormat); return true; } std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1); if (SecondColon == std::string::npos) { std::fprintf(stderr, "%s\n", ExpectedFormat); return true; } long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10); if (EndPtr != ArgValue.c_str() + SecondColon) { std::fprintf(stderr, "%s\n", ExpectedFormat); return true; } Val.FileName = ArgValue.substr(0, FirstColon); Val.Line = Line; Val.Column = Column; return false; } } } //===----------------------------------------------------------------------===// // Global options. //===----------------------------------------------------------------------===// /// ClangFrontendTimer - The front-end activities should charge time to it with /// TimeRegion. The -ftime-report option controls whether this will do /// anything. llvm::Timer *ClangFrontendTimer = 0; static bool HadErrors = false; static llvm::cl::opt<bool> Verbose("v", llvm::cl::desc("Enable verbose output")); static llvm::cl::opt<bool> Stats("print-stats", llvm::cl::desc("Print performance metrics and statistics")); static llvm::cl::opt<bool> DisableFree("disable-free", llvm::cl::desc("Disable freeing of memory on exit"), llvm::cl::init(false)); enum ProgActions { RewriteObjC, // ObjC->C Rewriter. RewriteBlocks, // ObjC->C Rewriter for Blocks. RewriteMacros, // Expand macros but not #includes. RewriteTest, // Rewriter playground FixIt, // Fix-It Rewriter HTMLTest, // HTML displayer testing stuff. EmitAssembly, // Emit a .s file. EmitLLVM, // Emit a .ll file. EmitBC, // Emit a .bc file. EmitLLVMOnly, // Generate LLVM IR, but do not SerializeAST, // Emit a .ast file. EmitHTML, // Translate input source into HTML. ASTPrint, // Parse ASTs and print them. ASTDump, // Parse ASTs and dump them. ASTView, // Parse ASTs and view them in Graphviz. PrintDeclContext, // Print DeclContext and their Decls. TestSerialization, // Run experimental serialization code. ParsePrintCallbacks, // Parse and print each callback. ParseSyntaxOnly, // Parse and perform semantic analysis. ParseNoop, // Parse with noop callbacks. RunPreprocessorOnly, // Just lex, no output. PrintPreprocessedInput, // -E mode. DumpTokens, // Dump out preprocessed tokens. DumpRawTokens, // Dump out raw tokens. RunAnalysis, // Run one or more source code analyses. GeneratePTH, // Generate pre-tokenized header. GeneratePCH, // Generate pre-compiled header. InheritanceView // View C++ inheritance for a specified class. }; static llvm::cl::opt<ProgActions> ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore, llvm::cl::init(ParseSyntaxOnly), llvm::cl::values( clEnumValN(RunPreprocessorOnly, "Eonly", "Just run preprocessor, no output (for timings)"), clEnumValN(PrintPreprocessedInput, "E", "Run preprocessor, emit preprocessed file"), clEnumValN(DumpRawTokens, "dump-raw-tokens", "Lex file in raw mode and dump raw tokens"), clEnumValN(RunAnalysis, "analyze", "Run static analysis engine"), clEnumValN(DumpTokens, "dump-tokens", "Run preprocessor, dump internal rep of tokens"), clEnumValN(ParseNoop, "parse-noop", "Run parser with noop callbacks (for timings)"), clEnumValN(ParseSyntaxOnly, "fsyntax-only", "Run parser and perform semantic analysis"), clEnumValN(ParsePrintCallbacks, "parse-print-callbacks", "Run parser and print each callback invoked"), clEnumValN(EmitHTML, "emit-html", "Output input source as HTML"), clEnumValN(ASTPrint, "ast-print", "Build ASTs and then pretty-print them"), clEnumValN(ASTDump, "ast-dump", "Build ASTs and then debug dump them"), clEnumValN(ASTView, "ast-view", "Build ASTs and view them with GraphViz"), clEnumValN(PrintDeclContext, "print-decl-contexts", "Print DeclContexts and their Decls"), clEnumValN(GeneratePTH, "emit-pth", "Generate pre-tokenized header file"), clEnumValN(GeneratePCH, "emit-pch", "Generate pre-compiled header file"), clEnumValN(TestSerialization, "test-pickling", "Run prototype serialization code"), clEnumValN(EmitAssembly, "S", "Emit native assembly code"), clEnumValN(EmitLLVM, "emit-llvm", "Build ASTs then convert to LLVM, emit .ll file"), clEnumValN(EmitBC, "emit-llvm-bc", "Build ASTs then convert to LLVM, emit .bc file"), clEnumValN(EmitLLVMOnly, "emit-llvm-only", "Build ASTs and convert to LLVM, discarding output"), clEnumValN(SerializeAST, "serialize", "Build ASTs and emit .ast file"), clEnumValN(RewriteTest, "rewrite-test", "Rewriter playground"), clEnumValN(RewriteObjC, "rewrite-objc", "Rewrite ObjC into C (code rewriter example)"), clEnumValN(RewriteMacros, "rewrite-macros", "Expand macros without full preprocessing"), clEnumValN(RewriteBlocks, "rewrite-blocks", "Rewrite Blocks to C"), clEnumValN(FixIt, "fixit", "Apply fix-it advice to the input source"), clEnumValEnd)); static llvm::cl::opt<std::string> OutputFile("o", llvm::cl::value_desc("path"), llvm::cl::desc("Specify output file (for --serialize, this is a directory)")); //===----------------------------------------------------------------------===// // PTH. //===----------------------------------------------------------------------===// static llvm::cl::opt<std::string> TokenCache("token-cache", llvm::cl::value_desc("path"), llvm::cl::desc("Use specified token cache file")); //===----------------------------------------------------------------------===// // Diagnostic Options //===----------------------------------------------------------------------===// static llvm::cl::opt<bool> VerifyDiagnostics("verify", llvm::cl::desc("Verify emitted diagnostics and warnings")); static llvm::cl::opt<std::string> HTMLDiag("html-diags", llvm::cl::desc("Generate HTML to report diagnostics"), llvm::cl::value_desc("HTML directory")); static llvm::cl::opt<bool> NoShowColumn("fno-show-column", llvm::cl::desc("Do not include column number on diagnostics")); static llvm::cl::opt<bool> NoShowLocation("fno-show-source-location", llvm::cl::desc("Do not include source location information with" " diagnostics")); static llvm::cl::opt<bool> NoCaretDiagnostics("fno-caret-diagnostics", llvm::cl::desc("Do not include source line and caret with" " diagnostics")); static llvm::cl::opt<bool> PrintSourceRangeInfo("fprint-source-range-info", llvm::cl::desc("Print source range spans in numeric form")); static llvm::cl::opt<bool> PrintDiagnosticOption("fdiagnostics-show-option", llvm::cl::desc("Print diagnostic name with mappable diagnostics")); //===----------------------------------------------------------------------===// // C++ Visualization. //===----------------------------------------------------------------------===// static llvm::cl::opt<std::string> InheritanceViewCls("cxx-inheritance-view", llvm::cl::value_desc("class name"), llvm::cl::desc("View C++ inheritance for a specified class")); //===----------------------------------------------------------------------===// // Builtin Options //===----------------------------------------------------------------------===// static llvm::cl::opt<bool> TimeReport("ftime-report", llvm::cl::desc("Print the amount of time each " "phase of compilation takes")); static llvm::cl::opt<bool> Freestanding("ffreestanding", llvm::cl::desc("Assert that the compilation takes place in a " "freestanding environment")); static llvm::cl::opt<bool> AllowBuiltins("fbuiltin", llvm::cl::init(true), llvm::cl::desc("Disable implicit builtin knowledge of functions")); static llvm::cl::opt<bool> MathErrno("fmath-errno", llvm::cl::init(true), llvm::cl::desc("Require math functions to respect errno")); //===----------------------------------------------------------------------===// // Language Options //===----------------------------------------------------------------------===// enum LangKind { langkind_unspecified, langkind_c, langkind_c_cpp, langkind_asm_cpp, langkind_cxx, langkind_cxx_cpp, langkind_objc, langkind_objc_cpp, langkind_objcxx, langkind_objcxx_cpp }; static llvm::cl::opt<LangKind> BaseLang("x", llvm::cl::desc("Base language to compile"), llvm::cl::init(langkind_unspecified), llvm::cl::values(clEnumValN(langkind_c, "c", "C"), clEnumValN(langkind_cxx, "c++", "C++"), clEnumValN(langkind_objc, "objective-c", "Objective C"), clEnumValN(langkind_objcxx,"objective-c++","Objective C++"), clEnumValN(langkind_c_cpp, "cpp-output", "Preprocessed C"), clEnumValN(langkind_asm_cpp, "assembler-with-cpp", "Preprocessed asm"), clEnumValN(langkind_cxx_cpp, "c++-cpp-output", "Preprocessed C++"), clEnumValN(langkind_objc_cpp, "objective-c-cpp-output", "Preprocessed Objective C"), clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output", "Preprocessed Objective C++"), clEnumValN(langkind_c, "c-header", "C header"), clEnumValN(langkind_objc, "objective-c-header", "Objective-C header"), clEnumValN(langkind_cxx, "c++-header", "C++ header"), clEnumValN(langkind_objcxx, "objective-c++-header", "Objective-C++ header"), clEnumValEnd)); static llvm::cl::opt<bool> LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"), llvm::cl::Hidden); static llvm::cl::opt<bool> LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"), llvm::cl::Hidden); static llvm::cl::opt<bool> ObjCExclusiveGC("fobjc-gc-only", llvm::cl::desc("Use GC exclusively for Objective-C related " "memory management")); static llvm::cl::opt<bool> ObjCEnableGC("fobjc-gc", llvm::cl::desc("Enable Objective-C garbage collection")); static llvm::cl::opt<LangOptions::VisibilityMode> SymbolVisibility("fvisibility", llvm::cl::desc("Set the default symbol visibility:"), llvm::cl::init(LangOptions::Default), llvm::cl::values(clEnumValN(LangOptions::Default, "default", "Use default symbol visibility"), clEnumValN(LangOptions::Hidden, "hidden", "Use hidden symbol visibility"), clEnumValN(LangOptions::Protected,"protected", "Use protected symbol visibility"), clEnumValEnd)); static llvm::cl::opt<bool> OverflowChecking("ftrapv", llvm::cl::desc("Trap on integer overflow"), llvm::cl::init(false)); /// InitializeBaseLanguage - Handle the -x foo options. static void InitializeBaseLanguage() { if (LangObjC) BaseLang = langkind_objc; else if (LangObjCXX) BaseLang = langkind_objcxx; } static LangKind GetLanguage(const std::string &Filename) { if (BaseLang != langkind_unspecified) return BaseLang; std::string::size_type DotPos = Filename.rfind('.'); if (DotPos == std::string::npos) { BaseLang = langkind_c; // Default to C if no extension. return langkind_c; } std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end()); // C header: .h // C++ header: .hh or .H; // assembler no preprocessing: .s // assembler: .S if (Ext == "c") return langkind_c; else if (Ext == "S" || // If the compiler is run on a .s file, preprocess it as .S Ext == "s") return langkind_asm_cpp; else if (Ext == "i") return langkind_c_cpp; else if (Ext == "ii") return langkind_cxx_cpp; else if (Ext == "m") return langkind_objc; else if (Ext == "mi") return langkind_objc_cpp; else if (Ext == "mm" || Ext == "M") return langkind_objcxx; else if (Ext == "mii") return langkind_objcxx_cpp; else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" || Ext == "c++" || Ext == "cp" || Ext == "cxx") return langkind_cxx; else return langkind_c; } static void InitializeCOptions(LangOptions &Options) { // Do nothing. } static void InitializeObjCOptions(LangOptions &Options) { Options.ObjC1 = Options.ObjC2 = 1; } static void InitializeLangOptions(LangOptions &Options, LangKind LK){ // FIXME: implement -fpreprocessed mode. bool NoPreprocess = false; switch (LK) { default: assert(0 && "Unknown language kind!"); case langkind_asm_cpp: Options.AsmPreprocessor = 1; // FALLTHROUGH case langkind_c_cpp: NoPreprocess = true; // FALLTHROUGH case langkind_c: InitializeCOptions(Options); break; case langkind_cxx_cpp: NoPreprocess = true; // FALLTHROUGH case langkind_cxx: Options.CPlusPlus = 1; break; case langkind_objc_cpp: NoPreprocess = true; // FALLTHROUGH case langkind_objc: InitializeObjCOptions(Options); break; case langkind_objcxx_cpp: NoPreprocess = true; // FALLTHROUGH case langkind_objcxx: Options.ObjC1 = Options.ObjC2 = 1; Options.CPlusPlus = 1; break; } if (ObjCExclusiveGC) Options.setGCMode(LangOptions::GCOnly); else if (ObjCEnableGC) Options.setGCMode(LangOptions::HybridGC); Options.setVisibilityMode(SymbolVisibility); Options.OverflowChecking = OverflowChecking; } /// LangStds - Language standards we support. enum LangStds { lang_unspecified, lang_c89, lang_c94, lang_c99, lang_gnu_START, lang_gnu89 = lang_gnu_START, lang_gnu99, lang_cxx98, lang_gnucxx98, lang_cxx0x, lang_gnucxx0x }; static llvm::cl::opt<LangStds> LangStd("std", llvm::cl::desc("Language standard to compile for"), llvm::cl::init(lang_unspecified), llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"), clEnumValN(lang_c89, "c90", "ISO C 1990"), clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"), clEnumValN(lang_c94, "iso9899:199409", "ISO C 1990 with amendment 1"), clEnumValN(lang_c99, "c99", "ISO C 1999"), clEnumValN(lang_c99, "c9x", "ISO C 1999"), clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"), clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"), clEnumValN(lang_gnu89, "gnu89", "ISO C 1990 with GNU extensions"), clEnumValN(lang_gnu99, "gnu99", "ISO C 1999 with GNU extensions (default for C)"), clEnumValN(lang_gnu99, "gnu9x", "ISO C 1999 with GNU extensions"), clEnumValN(lang_cxx98, "c++98", "ISO C++ 1998 with amendments"), clEnumValN(lang_gnucxx98, "gnu++98", "ISO C++ 1998 with amendments and GNU " "extensions (default for C++)"), clEnumValN(lang_cxx0x, "c++0x", "Upcoming ISO C++ 200x with amendments"), clEnumValN(lang_gnucxx0x, "gnu++0x", "Upcoming ISO C++ 200x with amendments and GNU " "extensions"), clEnumValEnd)); static llvm::cl::opt<bool> NoOperatorNames("fno-operator-names", llvm::cl::desc("Do not treat C++ operator name keywords as " "synonyms for operators")); static llvm::cl::opt<bool> PascalStrings("fpascal-strings", llvm::cl::desc("Recognize and construct Pascal-style " "string literals")); static llvm::cl::opt<bool> MSExtensions("fms-extensions", llvm::cl::desc("Accept some non-standard constructs used in " "Microsoft header files ")); static llvm::cl::opt<bool> WritableStrings("fwritable-strings", llvm::cl::desc("Store string literals as writable data")); static llvm::cl::opt<bool> NoLaxVectorConversions("fno-lax-vector-conversions", llvm::cl::desc("Disallow implicit conversions between " "vectors with a different number of " "elements or different element types")); static llvm::cl::opt<bool> EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature")); static llvm::cl::opt<bool> EnableHeinousExtensions("fheinous-gnu-extensions", llvm::cl::desc("enable GNU extensions that you really really shouldn't use"), llvm::cl::ValueDisallowed, llvm::cl::Hidden); static llvm::cl::opt<bool> ObjCNonFragileABI("fobjc-nonfragile-abi", llvm::cl::desc("enable objective-c's nonfragile abi")); static llvm::cl::opt<bool> EmitAllDecls("femit-all-decls", llvm::cl::desc("Emit all declarations, even if unused")); // FIXME: This (and all GCC -f options) really come in -f... and // -fno-... forms, and additionally support automagic behavior when // they are not defined. For example, -fexceptions defaults to on or // off depending on the language. We should support this behavior in // some form (perhaps just add a facility for distinguishing when an // has its default value from when it has been set to its default // value). static llvm::cl::opt<bool> Exceptions("fexceptions", llvm::cl::desc("Enable support for exception handling.")); static llvm::cl::opt<bool> GNURuntime("fgnu-runtime", llvm::cl::desc("Generate output compatible with the standard GNU " "Objective-C runtime.")); static llvm::cl::opt<bool> NeXTRuntime("fnext-runtime", llvm::cl::desc("Generate output compatible with the NeXT " "runtime.")); static llvm::cl::opt<bool> Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences.")); static llvm::cl::list<std::string> TargetFeatures("mattr", llvm::cl::CommaSeparated, llvm::cl::desc("Target specific attributes (-mattr=help for details)")); static llvm::cl::opt<unsigned> TemplateDepth("ftemplate-depth", llvm::cl::init(99), llvm::cl::desc("Maximum depth of recursive template " "instantiation")); static llvm::cl::opt<bool> OptSize("Os", llvm::cl::desc("Optimize for size")); static llvm::cl::opt<bool> NoCommon("fno-common", llvm::cl::desc("Compile common globals like normal definitions"), llvm::cl::ValueDisallowed); static llvm::cl::opt<std::string> MainFileName("main-file-name", llvm::cl::desc("Main file name to use for debug info")); // It might be nice to add bounds to the CommandLine library directly. struct OptLevelParser : public llvm::cl::parser<unsigned> { bool parse(llvm::cl::Option &O, const char *ArgName, const std::string &Arg, unsigned &Val) { if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val)) return true; if (Val > 3) return O.error(": '" + Arg + "' invalid optimization level!"); return false; } }; static llvm::cl::opt<unsigned, false, OptLevelParser> OptLevel("O", llvm::cl::Prefix, llvm::cl::desc("Optimization level"), llvm::cl::init(0)); static llvm::cl::opt<unsigned> PICLevel("pic-level", llvm::cl::desc("Value for __PIC__")); static llvm::cl::opt<bool> StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined")); // FIXME: add: // -fdollars-in-identifiers static void InitializeLanguageStandard(LangOptions &Options, LangKind LK, TargetInfo *Target) { // Allow the target to set the default the langauge options as it sees fit. Target->getDefaultLangOptions(Options); // If there are any -mattr options, pass them to the target for validation and // processing. The driver should have already consolidated all the // target-feature settings and passed them to us in the -mattr list. The // -mattr list is treated by the code generator as a diff against the -mcpu // setting, but the driver should pass all enabled options as "+" settings. // This means that the target should only look at + settings. if (!TargetFeatures.empty()) { std::string ErrorStr; int Opt = Target->HandleTargetFeatures(&TargetFeatures[0], TargetFeatures.size(), ErrorStr); if (Opt != -1) { if (ErrorStr.empty()) fprintf(stderr, "invalid feature '%s'\n", TargetFeatures[Opt].c_str()); else fprintf(stderr, "feature '%s': %s\n", TargetFeatures[Opt].c_str(), ErrorStr.c_str()); exit(1); } } if (LangStd == lang_unspecified) { // Based on the base language, pick one. switch (LK) { case lang_unspecified: assert(0 && "Unknown base language"); case langkind_c: case langkind_asm_cpp: case langkind_c_cpp: case langkind_objc: case langkind_objc_cpp: LangStd = lang_gnu99; break; case langkind_cxx: case langkind_cxx_cpp: case langkind_objcxx: case langkind_objcxx_cpp: LangStd = lang_gnucxx98; break; } } switch (LangStd) { default: assert(0 && "Unknown language standard!"); // Fall through from newer standards to older ones. This isn't really right. // FIXME: Enable specifically the right features based on the language stds. case lang_gnucxx0x: case lang_cxx0x: Options.CPlusPlus0x = 1; // FALL THROUGH case lang_gnucxx98: case lang_cxx98: Options.CPlusPlus = 1; Options.CXXOperatorNames = !NoOperatorNames; Options.Boolean = 1; // FALL THROUGH. case lang_gnu99: case lang_c99: Options.C99 = 1; Options.HexFloats = 1; // FALL THROUGH. case lang_gnu89: Options.BCPLComment = 1; // Only for C99/C++. // FALL THROUGH. case lang_c94: Options.Digraphs = 1; // C94, C99, C++. // FALL THROUGH. case lang_c89: break; } // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc. Options.GNUMode = LangStd >= lang_gnu_START; if (Options.CPlusPlus) { Options.C99 = 0; Options.HexFloats = Options.GNUMode; } if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89) Options.ImplicitInt = 1; else Options.ImplicitInt = 0; // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs // is specified, or -std is set to a conforming mode. Options.Trigraphs = !Options.GNUMode; if (Trigraphs.getPosition()) Options.Trigraphs = Trigraphs; // Command line option wins if specified. // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off // even if they are normally on for the target. In GNU modes (e.g. // -std=gnu99) the default for blocks depends on the target settings. // However, blocks are not turned off when compiling Obj-C or Obj-C++ code. if (!Options.ObjC1 && !Options.GNUMode) Options.Blocks = 0; // Never accept '$' in identifiers when preprocessing assembler. if (LK != langkind_asm_cpp) Options.DollarIdents = 1; // FIXME: Really a target property. if (PascalStrings.getPosition()) Options.PascalStrings = PascalStrings; Options.Microsoft = MSExtensions; Options.WritableStrings = WritableStrings; if (NoLaxVectorConversions.getPosition()) Options.LaxVectorConversions = 0; Options.Exceptions = Exceptions; if (EnableBlocks.getPosition()) Options.Blocks = EnableBlocks; if (!AllowBuiltins) Options.NoBuiltin = 1; if (Freestanding) Options.Freestanding = Options.NoBuiltin = 1; if (EnableHeinousExtensions) Options.HeinousExtensions = 1; Options.MathErrno = MathErrno; Options.InstantiationDepth = TemplateDepth; // Override the default runtime if the user requested it. if (NeXTRuntime) Options.NeXTRuntime = 1; else if (GNURuntime) Options.NeXTRuntime = 0; if (ObjCNonFragileABI) Options.ObjCNonFragileABI = 1; if (EmitAllDecls) Options.EmitAllDecls = 1; // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't // support. Options.OptimizeSize = 0; // -Os implies -O2 if (OptSize || OptLevel) Options.Optimize = 1; assert(PICLevel <= 2 && "Invalid value for -pic-level"); Options.PICLevel = PICLevel; Options.GNUInline = !Options.C99; // FIXME: This is affected by other options (-fno-inline). Options.NoInline = !OptSize && !OptLevel; Options.Static = StaticDefine; if (MainFileName.getPosition()) Options.setMainFileName(MainFileName.c_str()); } //===----------------------------------------------------------------------===// // Target Triple Processing. //===----------------------------------------------------------------------===// static llvm::cl::opt<std::string> TargetTriple("triple", llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)")); static llvm::cl::opt<std::string> Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)")); static llvm::cl::opt<std::string> MacOSVersionMin("mmacosx-version-min", llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)")); // If -mmacosx-version-min=10.3.9 is specified, change the triple from being // something like powerpc-apple-darwin9 to powerpc-apple-darwin7 // FIXME: We should have the driver do this instead. static void HandleMacOSVersionMin(std::string &Triple) { std::string::size_type DarwinDashIdx = Triple.find("-darwin"); if (DarwinDashIdx == std::string::npos) { fprintf(stderr, "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n"); exit(1); } unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin"); // Remove the number. Triple.resize(DarwinNumIdx); // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9] bool MacOSVersionMinIsInvalid = false; int VersionNum = 0; if (MacOSVersionMin.size() < 4 || MacOSVersionMin.substr(0, 3) != "10." || !isdigit(MacOSVersionMin[3])) { MacOSVersionMinIsInvalid = true; } else { const char *Start = MacOSVersionMin.c_str()+3; char *End = 0; VersionNum = (int)strtol(Start, &End, 10); // The version number must be in the range 0-9. MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9; // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7. Triple += llvm::itostr(VersionNum+4); if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok. // Add the period piece (.7) to the end of the triple. This gives us // something like ...-darwin8.7 Triple += End; } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not. MacOSVersionMinIsInvalid = true; } } if (MacOSVersionMinIsInvalid) { fprintf(stderr, "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n", MacOSVersionMin.c_str()); exit(1); } else if (VersionNum <= 4 && !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) { fprintf(stderr, "-mmacosx-version-min=%s is invalid with -arch x86_64.\n", MacOSVersionMin.c_str()); exit(1); } } static llvm::cl::opt<std::string> IPhoneOSVersionMin("miphoneos-version-min", llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)")); // If -miphoneos-version-min=2.2 is specified, change the triple from being // something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use // 9 as the default major Darwin number, and encode the iPhone OS version // number in the minor version and revision. // FIXME: We should have the driver do this instead. static void HandleIPhoneOSVersionMin(std::string &Triple) { std::string::size_type DarwinDashIdx = Triple.find("-darwin"); if (DarwinDashIdx == std::string::npos) { fprintf(stderr, "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n"); exit(1); } unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin"); // Remove the number. Triple.resize(DarwinNumIdx); // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9] bool IPhoneOSVersionMinIsInvalid = false; int VersionNum = 0; if (IPhoneOSVersionMin.size() < 3 || !isdigit(IPhoneOSVersionMin[0])) { IPhoneOSVersionMinIsInvalid = true; } else { const char *Start = IPhoneOSVersionMin.c_str(); char *End = 0; VersionNum = (int)strtol(Start, &End, 10); // The version number must be in the range 0-9. IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9; // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2. Triple += "9." + llvm::itostr(VersionNum); if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok. // Add the period piece (.2) to the end of the triple. This gives us // something like ...-darwin9.2.2 Triple += End; } else if (End[0] != '\0') { // "2.2" is ok. 2x is not. IPhoneOSVersionMinIsInvalid = true; } } if (IPhoneOSVersionMinIsInvalid) { fprintf(stderr, "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n", IPhoneOSVersionMin.c_str()); exit(1); } } /// CreateTargetTriple - Process the various options that affect the target /// triple and build a final aggregate triple that we are compiling for. static std::string CreateTargetTriple() { // Initialize base triple. If a -triple option has been specified, use // that triple. Otherwise, default to the host triple. std::string Triple = TargetTriple; if (Triple.empty()) Triple = llvm::sys::getHostTriple(); // If -arch foo was specified, remove the architecture from the triple we have // so far and replace it with the specified one. // FIXME: -arch should be removed, the driver should handle this. if (!Arch.empty()) { // Decompose the base triple into "arch" and suffix. std::string::size_type FirstDashIdx = Triple.find('-'); if (FirstDashIdx == std::string::npos) { fprintf(stderr, "Malformed target triple: \"%s\" ('-' could not be found).\n", Triple.c_str()); exit(1); } // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc. if (Arch == "ppc") Arch = "powerpc"; else if (Arch == "ppc64") Arch = "powerpc64"; Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end()); } // If -mmacosx-version-min=10.3.9 is specified, change the triple from being // something like powerpc-apple-darwin9 to powerpc-apple-darwin7 if (!MacOSVersionMin.empty()) HandleMacOSVersionMin(Triple); else if (!IPhoneOSVersionMin.empty()) HandleIPhoneOSVersionMin(Triple);; return Triple; } //===----------------------------------------------------------------------===// // Preprocessor Initialization //===----------------------------------------------------------------------===// // FIXME: Preprocessor builtins to support. // -A... - Play with #assertions // -undef - Undefine all predefined macros // FIXME: -imacros static llvm::cl::list<std::string> D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix, llvm::cl::desc("Predefine the specified macro")); static llvm::cl::list<std::string> U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix, llvm::cl::desc("Undefine the specified macro")); static llvm::cl::list<std::string> ImplicitIncludes("include", llvm::cl::value_desc("file"), llvm::cl::desc("Include file before parsing")); static llvm::cl::list<std::string> ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"), llvm::cl::desc("Include macros from file before parsing")); static llvm::cl::opt<std::string> ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"), llvm::cl::desc("Include file before parsing")); static llvm::cl::opt<std::string> ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"), llvm::cl::desc("Include precompiled header file")); // Append a #define line to Buf for Macro. Macro should be of the form XXX, // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit // "#define XXX Y z W". To get a #define with no value, use "XXX=". static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro, const char *Command = "#define ") { Buf.insert(Buf.end(), Command, Command+strlen(Command)); if (const char *Equal = strchr(Macro, '=')) { // Turn the = into ' '. Buf.insert(Buf.end(), Macro, Equal); Buf.push_back(' '); // Per GCC -D semantics, the macro ends at \n if it exists. const char *End = strpbrk(Equal, "\n\r"); if (End) { fprintf(stderr, "warning: macro '%s' contains embedded newline, text " "after the newline is ignored.\n", std::string(Macro, Equal).c_str()); } else { End = Equal+strlen(Equal); } Buf.insert(Buf.end(), Equal+1, End); } else { // Push "macroname 1". Buf.insert(Buf.end(), Macro, Macro+strlen(Macro)); Buf.push_back(' '); Buf.push_back('1'); } Buf.push_back('\n'); } /// Add the quoted name of an implicit include file. static void AddQuotedIncludePath(std::vector<char> &Buf, const std::string &File) { // Implicit include paths are relative to the current working // directory; resolve them now instead of using the normal machinery // (which would look relative to the input file). llvm::sys::Path Path(File); Path.makeAbsolute(); // Escape double quotes etc. Buf.push_back('"'); std::string EscapedFile = Lexer::Stringify(Path.toString()); Buf.insert(Buf.end(), EscapedFile.begin(), EscapedFile.end()); Buf.push_back('"'); } /// AddImplicitInclude - Add an implicit #include of the specified file to the /// predefines buffer. static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File) { const char *Inc = "#include "; Buf.insert(Buf.end(), Inc, Inc+strlen(Inc)); AddQuotedIncludePath(Buf, File); Buf.push_back('\n'); } static void AddImplicitIncludeMacros(std::vector<char> &Buf, const std::string &File) { const char *Inc = "#__include_macros "; Buf.insert(Buf.end(), Inc, Inc+strlen(Inc)); AddQuotedIncludePath(Buf, File); Buf.push_back('\n'); // Marker token to stop the __include_macros fetch loop. const char *Marker = "##\n"; // ##? Buf.insert(Buf.end(), Marker, Marker+strlen(Marker)); } /// AddImplicitIncludePTH - Add an implicit #include using the original file /// used to generate a PTH cache. static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor &PP) { PTHManager *P = PP.getPTHManager(); assert(P && "No PTHManager."); const char *OriginalFile = P->getOriginalSourceFile(); if (!OriginalFile) { assert(!ImplicitIncludePTH.empty()); fprintf(stderr, "error: PTH file '%s' does not designate an original " "source header file for -include-pth\n", ImplicitIncludePTH.c_str()); exit (1); } AddImplicitInclude(Buf, OriginalFile); } /// PickFP - This is used to pick a value based on the FP semantics of the /// specified FP model. template <typename T> static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal, T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) { if (Sem == &llvm::APFloat::IEEEsingle) return IEEESingleVal; if (Sem == &llvm::APFloat::IEEEdouble) return IEEEDoubleVal; if (Sem == &llvm::APFloat::x87DoubleExtended) return X87DoubleExtendedVal; assert(Sem == &llvm::APFloat::PPCDoubleDouble); return PPCDoubleDoubleVal; } static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix, const llvm::fltSemantics *Sem) { const char *DenormMin, *Epsilon, *Max, *Min; DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324", "3.64519953188247460253e-4951L", "4.94065645841246544176568792868221e-324L"); int Digits = PickFP(Sem, 6, 15, 18, 31); Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16", "1.08420217248550443401e-19L", "4.94065645841246544176568792868221e-324L"); int HasInifinity = 1, HasQuietNaN = 1; int MantissaDigits = PickFP(Sem, 24, 53, 64, 106); int Min10Exp = PickFP(Sem, -37, -307, -4931, -291); int Max10Exp = PickFP(Sem, 38, 308, 4932, 308); int MinExp = PickFP(Sem, -125, -1021, -16381, -968); int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024); Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308", "3.36210314311209350626e-4932L", "2.00416836000897277799610805135016e-292L"); Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308", "1.18973149535723176502e+4932L", "1.79769313486231580793728971405301e+308L"); char MacroBuf[60]; sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix); DefineBuiltinMacro(Buf, MacroBuf); } /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro /// named MacroName with the max value for a type with width 'TypeWidth' a /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL). static void DefineTypeSize(const char *MacroName, unsigned TypeWidth, const char *ValSuffix, bool isSigned, std::vector<char> &Buf) { char MacroBuf[60]; long long MaxVal; if (isSigned) MaxVal = (1LL << (TypeWidth - 1)) - 1; else MaxVal = ~0LL >> (64-TypeWidth); sprintf(MacroBuf, "%s=%llu%s", MacroName, MaxVal, ValSuffix); DefineBuiltinMacro(Buf, MacroBuf); } static void DefineType(const char *MacroName, TargetInfo::IntType Ty, std::vector<char> &Buf) { char MacroBuf[60]; sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty)); DefineBuiltinMacro(Buf, MacroBuf); } static void InitializePredefinedMacros(const TargetInfo &TI, const LangOptions &LangOpts, std::vector<char> &Buf) { char MacroBuf[60]; // Compiler version introspection macros. DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend // Currently claim to be compatible with GCC 4.2.1-5621. DefineBuiltinMacro(Buf, "__APPLE_CC__=5621"); DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2"); DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1"); DefineBuiltinMacro(Buf, "__GNUC__=4"); DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002"); DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 Compatible Clang Compiler\""); // Initialize language-specific preprocessor defines. // These should all be defined in the preprocessor according to the // current language configuration. if (!LangOpts.Microsoft) DefineBuiltinMacro(Buf, "__STDC__=1"); if (LangOpts.AsmPreprocessor) DefineBuiltinMacro(Buf, "__ASSEMBLER__=1"); if (LangOpts.C99 && !LangOpts.CPlusPlus) DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L"); else if (0) // STDC94 ? DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L"); // Standard conforming mode? if (!LangOpts.GNUMode) DefineBuiltinMacro(Buf, "__STRICT_ANSI__=1"); if (LangOpts.CPlusPlus0x) DefineBuiltinMacro(Buf, "__GXX_EXPERIMENTAL_CXX0X__"); if (LangOpts.Freestanding) DefineBuiltinMacro(Buf, "__STDC_HOSTED__=0"); else DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1"); if (LangOpts.ObjC1) { DefineBuiltinMacro(Buf, "__OBJC__=1"); if (LangOpts.ObjCNonFragileABI) { DefineBuiltinMacro(Buf, "__OBJC2__=1"); DefineBuiltinMacro(Buf, "OBJC_ZEROCOST_EXCEPTIONS=1"); DefineBuiltinMacro(Buf, "__EXCEPTIONS=1"); } if (LangOpts.getGCMode() != LangOptions::NonGC) DefineBuiltinMacro(Buf, "__OBJC_GC__=1"); if (LangOpts.NeXTRuntime) DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1"); } // darwin_constant_cfstrings controls this. This is also dependent // on other things like the runtime I believe. This is set even for C code. DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1"); if (LangOpts.ObjC2) DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES"); if (LangOpts.PascalStrings) DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__"); if (LangOpts.Blocks) { DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))"); DefineBuiltinMacro(Buf, "__BLOCKS__=1"); } if (LangOpts.CPlusPlus) { DefineBuiltinMacro(Buf, "__DEPRECATED=1"); DefineBuiltinMacro(Buf, "__EXCEPTIONS=1"); DefineBuiltinMacro(Buf, "__GNUG__=4"); DefineBuiltinMacro(Buf, "__GXX_WEAK__=1"); DefineBuiltinMacro(Buf, "__cplusplus=1"); DefineBuiltinMacro(Buf, "__private_extern__=extern"); } // Filter out some microsoft extensions when trying to parse in ms-compat // mode. if (LangOpts.Microsoft) { DefineBuiltinMacro(Buf, "_cdecl=__cdecl"); DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__"); DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__"); DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__"); DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__"); } if (LangOpts.Optimize) DefineBuiltinMacro(Buf, "__OPTIMIZE__=1"); if (LangOpts.OptimizeSize) DefineBuiltinMacro(Buf, "__OPTIMIZE_SIZE__=1"); // Initialize target-specific preprocessor defines. // Define type sizing macros based on the target properties. assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far"); DefineBuiltinMacro(Buf, "__CHAR_BIT__=8"); unsigned IntMaxWidth; const char *IntMaxSuffix; if (TI.getIntMaxType() == TargetInfo::SignedLongLong) { IntMaxWidth = TI.getLongLongWidth(); IntMaxSuffix = "LL"; } else if (TI.getIntMaxType() == TargetInfo::SignedLong) { IntMaxWidth = TI.getLongWidth(); IntMaxSuffix = "L"; } else { assert(TI.getIntMaxType() == TargetInfo::SignedInt); IntMaxWidth = TI.getIntWidth(); IntMaxSuffix = ""; } DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf); DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf); DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf); DefineTypeSize("__LONG_MAX__", TI.getLongWidth(), "L", true, Buf); DefineTypeSize("__LONG_LONG_MAX__", TI.getLongLongWidth(), "LL", true, Buf); DefineTypeSize("__WCHAR_MAX__", TI.getWCharWidth(), "", true, Buf); DefineTypeSize("__INTMAX_MAX__", IntMaxWidth, IntMaxSuffix, true, Buf); DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf); DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf); DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf); DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf); DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf); DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf); // FIXME: TargetInfo hookize __WINT_TYPE__. DefineBuiltinMacro(Buf, "__WINT_TYPE__=int"); DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat()); DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat()); DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat()); // Define a __POINTER_WIDTH__ macro for stdint.h. sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0)); DefineBuiltinMacro(Buf, MacroBuf); if (!TI.isCharSigned()) DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__"); // Define fixed-sized integer types for stdint.h assert(TI.getCharWidth() == 8 && "unsupported target types"); assert(TI.getShortWidth() == 16 && "unsupported target types"); DefineBuiltinMacro(Buf, "__INT8_TYPE__=char"); DefineBuiltinMacro(Buf, "__INT16_TYPE__=short"); if (TI.getIntWidth() == 32) DefineBuiltinMacro(Buf, "__INT32_TYPE__=int"); else { assert(TI.getLongLongWidth() == 32 && "unsupported target types"); DefineBuiltinMacro(Buf, "__INT32_TYPE__=long long"); } // 16-bit targets doesn't necessarily have a 64-bit type. if (TI.getLongLongWidth() == 64) DefineBuiltinMacro(Buf, "__INT64_TYPE__=long long"); // Add __builtin_va_list typedef. { const char *VAList = TI.getVAListDeclaration(); Buf.insert(Buf.end(), VAList, VAList+strlen(VAList)); Buf.push_back('\n'); } if (const char *Prefix = TI.getUserLabelPrefix()) { sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix); DefineBuiltinMacro(Buf, MacroBuf); } // Build configuration options. FIXME: these should be controlled by // command line options or something. DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0"); if (LangOpts.Static) DefineBuiltinMacro(Buf, "__STATIC__=1"); else DefineBuiltinMacro(Buf, "__DYNAMIC__=1"); if (LangOpts.GNUInline) DefineBuiltinMacro(Buf, "__GNUC_GNU_INLINE__=1"); else DefineBuiltinMacro(Buf, "__GNUC_STDC_INLINE__=1"); if (LangOpts.NoInline) DefineBuiltinMacro(Buf, "__NO_INLINE__=1"); if (unsigned PICLevel = LangOpts.PICLevel) { sprintf(MacroBuf, "__PIC__=%d", PICLevel); DefineBuiltinMacro(Buf, MacroBuf); sprintf(MacroBuf, "__pic__=%d", PICLevel); DefineBuiltinMacro(Buf, MacroBuf); } // Macros to control C99 numerics and <float.h> DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0"); DefineBuiltinMacro(Buf, "__FLT_RADIX__=2"); sprintf(MacroBuf, "__DECIMAL_DIG__=%d", PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33)); DefineBuiltinMacro(Buf, MacroBuf); // Get other target #defines. TI.getTargetDefines(LangOpts, Buf); } static bool InitializeSourceManager(Preprocessor &PP, const std::string &InFile) { // Figure out where to get and map in the main file. SourceManager &SourceMgr = PP.getSourceManager(); FileManager &FileMgr = PP.getFileManager(); if (InFile != "-") { const FileEntry *File = FileMgr.getFile(InFile); if (File) SourceMgr.createMainFileID(File, SourceLocation()); if (SourceMgr.getMainFileID().isInvalid()) { PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading) << InFile.c_str(); return true; } } else { llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN(); // If stdin was empty, SB is null. Cons up an empty memory // buffer now. if (!SB) { const char *EmptyStr = ""; SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>"); } SourceMgr.createMainFileIDForMemBuffer(SB); if (SourceMgr.getMainFileID().isInvalid()) { PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading_stdin); return true; } } return false; } /// InitializePreprocessor - Initialize the preprocessor getting it and the /// environment ready to process a single file. This returns true on error. /// static bool InitializePreprocessor(Preprocessor &PP, const std::string &InFile) { std::vector<char> PredefineBuffer; // Install things like __POWERPC__, __GNUC__, etc into the macro table. InitializePredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(), PredefineBuffer); // Add on the predefines from the driver. Wrap in a #line directive to report // that they come from the command line. const char *LineDirective = "# 1 \"<command line>\" 1\n"; PredefineBuffer.insert(PredefineBuffer.end(), LineDirective, LineDirective+strlen(LineDirective)); // Add macros from the command line. unsigned d = 0, D = D_macros.size(); unsigned u = 0, U = U_macros.size(); while (d < D || u < U) { if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u))) DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str()); else DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef "); } // If -imacros are specified, include them now. These are processed before // any -include directives. for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i) AddImplicitIncludeMacros(PredefineBuffer, ImplicitMacroIncludes[i]); if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) { // We want to add these paths to the predefines buffer in order, make a // temporary vector to sort by their occurrence. llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths; if (!ImplicitIncludePTH.empty()) OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(), &ImplicitIncludePTH)); for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i), &ImplicitIncludes[i])); llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end()); // Now that they are ordered by position, add to the predefines buffer. for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) { std::string *Ptr = OrderedPaths[i].second; if (!ImplicitIncludes.empty() && Ptr >= &ImplicitIncludes[0] && Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) { AddImplicitInclude(PredefineBuffer, *Ptr); } else { assert(Ptr == &ImplicitIncludePTH); AddImplicitIncludePTH(PredefineBuffer, PP); } } } LineDirective = "# 2 \"<built-in>\" 2\n"; PredefineBuffer.insert(PredefineBuffer.end(), LineDirective, LineDirective+strlen(LineDirective)); // Null terminate PredefinedBuffer and add it. PredefineBuffer.push_back(0); PP.setPredefines(&PredefineBuffer[0]); // Once we've read this, we're done. return false; } //===----------------------------------------------------------------------===// // Preprocessor include path information. //===----------------------------------------------------------------------===// // This tool exports a large number of command line options to control how the // preprocessor searches for header files. At root, however, the Preprocessor // object takes a very simple interface: a list of directories to search for // // FIXME: -nostdinc,-nostdinc++ // FIXME: -imultilib // static llvm::cl::opt<bool> nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories")); // Various command line options. These four add directories to each chain. static llvm::cl::list<std::string> F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix, llvm::cl::desc("Add directory to framework include search path")); static llvm::cl::list<std::string> I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix, llvm::cl::desc("Add directory to include search path")); static llvm::cl::list<std::string> idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix, llvm::cl::desc("Add directory to AFTER include search path")); static llvm::cl::list<std::string> iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix, llvm::cl::desc("Add directory to QUOTE include search path")); static llvm::cl::list<std::string> isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix, llvm::cl::desc("Add directory to SYSTEM include search path")); // These handle -iprefix/-iwithprefix/-iwithprefixbefore. static llvm::cl::list<std::string> iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix, llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix")); static llvm::cl::list<std::string> iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix, llvm::cl::desc("Set directory to SYSTEM include search path with prefix")); static llvm::cl::list<std::string> iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"), llvm::cl::Prefix, llvm::cl::desc("Set directory to include search path with prefix")); static llvm::cl::opt<std::string> isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"), llvm::cl::desc("Set the system root directory (usually /)")); // Finally, implement the code that groks the options above. /// InitializeIncludePaths - Process the -I options and set them in the /// HeaderSearch object. void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers, FileManager &FM, const LangOptions &Lang) { InitHeaderSearch Init(Headers, Verbose, isysroot); // Handle -I... and -F... options, walking the lists in parallel. unsigned Iidx = 0, Fidx = 0; while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) { if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) { Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false); ++Iidx; } else { Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true); ++Fidx; } } // Consume what's left from whatever list was longer. for (; Iidx != I_dirs.size(); ++Iidx) Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false); for (; Fidx != F_dirs.size(); ++Fidx) Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true); // Handle -idirafter... options. for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i) Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After, false, true, false); // Handle -iquote... options. for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i) Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false); // Handle -isystem... options. for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i) Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false); // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in // parallel, processing the values in order of occurance to get the right // prefixes. { std::string Prefix = ""; // FIXME: this isn't the correct default prefix. unsigned iprefix_idx = 0; unsigned iwithprefix_idx = 0; unsigned iwithprefixbefore_idx = 0; bool iprefix_done = iprefix_vals.empty(); bool iwithprefix_done = iwithprefix_vals.empty(); bool iwithprefixbefore_done = iwithprefixbefore_vals.empty(); while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) { if (!iprefix_done && (iwithprefix_done || iprefix_vals.getPosition(iprefix_idx) < iwithprefix_vals.getPosition(iwithprefix_idx)) && (iwithprefixbefore_done || iprefix_vals.getPosition(iprefix_idx) < iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) { Prefix = iprefix_vals[iprefix_idx]; ++iprefix_idx; iprefix_done = iprefix_idx == iprefix_vals.size(); } else if (!iwithprefix_done && (iwithprefixbefore_done || iwithprefix_vals.getPosition(iwithprefix_idx) < iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) { Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx], InitHeaderSearch::System, false, false, false); ++iwithprefix_idx; iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size(); } else { Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx], InitHeaderSearch::Angled, false, false, false); ++iwithprefixbefore_idx; iwithprefixbefore_done = iwithprefixbefore_idx == iwithprefixbefore_vals.size(); } } } Init.AddDefaultEnvVarPaths(Lang); // Add the clang headers, which are relative to the clang binary. llvm::sys::Path MainExecutablePath = llvm::sys::Path::GetMainExecutable(Argv0, (void*)(intptr_t)InitializeIncludePaths); if (!MainExecutablePath.isEmpty()) { MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin // Get foo/lib/clang/1.0/include // // FIXME: Don't embed version here. MainExecutablePath.appendComponent("lib"); MainExecutablePath.appendComponent("clang"); MainExecutablePath.appendComponent("1.0"); MainExecutablePath.appendComponent("include"); // We pass true to ignore sysroot so that we *always* look for clang headers // relative to our executable, never relative to -isysroot. Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System, false, false, false, true /*ignore sysroot*/); } if (!nostdinc) Init.AddDefaultSystemIncludePaths(Lang); // Now that we have collected all of the include paths, merge them all // together and tell the preprocessor about them. Init.Realize(); } //===----------------------------------------------------------------------===// // Driver PreprocessorFactory - For lazily generating preprocessors ... //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory { const std::string &InFile; Diagnostic &Diags; const LangOptions &LangInfo; TargetInfo &Target; SourceManager &SourceMgr; HeaderSearch &HeaderInfo; public: DriverPreprocessorFactory(const std::string &infile, Diagnostic &diags, const LangOptions &opts, TargetInfo &target, SourceManager &SM, HeaderSearch &Headers) : InFile(infile), Diags(diags), LangInfo(opts), Target(target), SourceMgr(SM), HeaderInfo(Headers) {} virtual ~DriverPreprocessorFactory() {} virtual Preprocessor* CreatePreprocessor() { llvm::OwningPtr<PTHManager> PTHMgr; if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) { fprintf(stderr, "error: cannot use both -token-cache and -include-pth " "options\n"); exit(1); } // Use PTH? if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) { const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache; PTHMgr.reset(PTHManager::Create(x, &Diags, TokenCache.empty() ? Diagnostic::Error : Diagnostic::Warning)); } if (Diags.hasErrorOccurred()) exit(1); // Create the Preprocessor. llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target, SourceMgr, HeaderInfo, PTHMgr.get())); // Note that this is different then passing PTHMgr to Preprocessor's ctor. // That argument is used as the IdentifierInfoLookup argument to // IdentifierTable's ctor. if (PTHMgr) { PTHMgr->setPreprocessor(PP.get()); PP->setPTHManager(PTHMgr.take()); } if (InitializePreprocessor(*PP, InFile)) return 0; /// FIXME: PP can only handle one callback if (ProgAction != PrintPreprocessedInput) { std::string ErrStr; bool DFG = CreateDependencyFileGen(PP.get(), ErrStr); if (!DFG && !ErrStr.empty()) { fprintf(stderr, "%s", ErrStr.c_str()); return 0; } } return PP.take(); } }; } //===----------------------------------------------------------------------===// // Basic Parser driver //===----------------------------------------------------------------------===// static void ParseFile(Preprocessor &PP, MinimalAction *PA) { Parser P(PP, *PA); PP.EnterMainSourceFile(); // Parsing the specified input file. P.ParseTranslationUnit(); delete PA; } //===----------------------------------------------------------------------===// // Code generation options //===----------------------------------------------------------------------===// static llvm::cl::opt<bool> GenerateDebugInfo("g", llvm::cl::desc("Generate source level debug information")); static llvm::cl::opt<std::string> TargetCPU("mcpu", llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)")); static void InitializeCompileOptions(CompileOptions &Opts, const LangOptions &LangOpts) { Opts.OptimizeSize = OptSize; Opts.DebugInfo = GenerateDebugInfo; if (OptSize) { // -Os implies -O2 // FIXME: Diagnose conflicting options. Opts.OptimizationLevel = 2; } else { Opts.OptimizationLevel = OptLevel; } // FIXME: There are llvm-gcc options to control these selectively. Opts.InlineFunctions = (Opts.OptimizationLevel > 1); Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize); Opts.SimplifyLibCalls = !LangOpts.NoBuiltin; #ifdef NDEBUG Opts.VerifyModule = 0; #endif Opts.CPU = TargetCPU; Opts.Features.insert(Opts.Features.end(), TargetFeatures.begin(), TargetFeatures.end()); Opts.NoCommon = NoCommon | LangOpts.CPlusPlus; // Handle -ftime-report. Opts.TimePasses = TimeReport; } //===----------------------------------------------------------------------===// // Fix-It Options //===----------------------------------------------------------------------===// static llvm::cl::list<ParsedSourceLocation> FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"), llvm::cl::desc("Perform Fix-It modifications at the given source location")); //===----------------------------------------------------------------------===// // Main driver //===----------------------------------------------------------------------===// /// CreateASTConsumer - Create the ASTConsumer for the corresponding program /// action. These consumers can operate on both ASTs that are freshly /// parsed from source files as well as those deserialized from Bitcode. /// Note that PP and PPF may be null here. static ASTConsumer *CreateASTConsumer(const std::string& InFile, Diagnostic& Diag, FileManager& FileMgr, const LangOptions& LangOpts, Preprocessor *PP, PreprocessorFactory *PPF) { switch (ProgAction) { default: return NULL; case ASTPrint: return CreateASTPrinter(); case ASTDump: return CreateASTDumper(); case ASTView: return CreateASTViewer(); case PrintDeclContext: return CreateDeclContextPrinter(); case EmitHTML: return CreateHTMLPrinter(OutputFile, Diag, PP, PPF); case InheritanceView: return CreateInheritanceViewer(InheritanceViewCls); case TestSerialization: return CreateSerializationTest(Diag, FileMgr); case EmitAssembly: case EmitLLVM: case EmitBC: case EmitLLVMOnly: { BackendAction Act; if (ProgAction == EmitAssembly) Act = Backend_EmitAssembly; else if (ProgAction == EmitLLVM) Act = Backend_EmitLL; else if (ProgAction == EmitLLVMOnly) Act = Backend_EmitNothing; else Act = Backend_EmitBC; CompileOptions Opts; InitializeCompileOptions(Opts, LangOpts); return CreateBackendConsumer(Act, Diag, LangOpts, Opts, InFile, OutputFile); } case SerializeAST: // FIXME: Allow user to tailor where the file is written. return CreateASTSerializer(InFile, OutputFile, Diag); case GeneratePCH: assert(PP && "Generate PCH doesn't work from serialized file yet"); return CreatePCHGenerator(*PP, OutputFile); case RewriteObjC: return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts); case RewriteBlocks: return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts); case RunAnalysis: return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile); } } /// ProcessInputFile - Process a single input file with the specified state. /// static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF, const std::string &InFile, ProgActions PA) { llvm::OwningPtr<ASTConsumer> Consumer; bool ClearSourceMgr = false; FixItRewriter *FixItRewrite = 0; bool CompleteTranslationUnit = true; switch (PA) { default: Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(), PP.getFileManager(), PP.getLangOptions(), &PP, &PPF)); if (!Consumer) { fprintf(stderr, "Unexpected program action!\n"); HadErrors = true; return; } if (ProgAction == GeneratePCH) CompleteTranslationUnit = false; break; case DumpRawTokens: { llvm::TimeRegion Timer(ClangFrontendTimer); SourceManager &SM = PP.getSourceManager(); // Start lexing the specified input file. Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions()); RawLex.SetKeepWhitespaceMode(true); Token RawTok; RawLex.LexFromRawLexer(RawTok); while (RawTok.isNot(tok::eof)) { PP.DumpToken(RawTok, true); fprintf(stderr, "\n"); RawLex.LexFromRawLexer(RawTok); } ClearSourceMgr = true; break; } case DumpTokens: { // Token dump mode. llvm::TimeRegion Timer(ClangFrontendTimer); Token Tok; // Start preprocessing the specified input file. PP.EnterMainSourceFile(); do { PP.Lex(Tok); PP.DumpToken(Tok, true); fprintf(stderr, "\n"); } while (Tok.isNot(tok::eof)); ClearSourceMgr = true; break; } case RunPreprocessorOnly: { // Just lex as fast as we can, no output. llvm::TimeRegion Timer(ClangFrontendTimer); Token Tok; // Start parsing the specified input file. PP.EnterMainSourceFile(); do { PP.Lex(Tok); } while (Tok.isNot(tok::eof)); ClearSourceMgr = true; break; } case GeneratePTH: { llvm::TimeRegion Timer(ClangFrontendTimer); CacheTokens(PP, OutputFile); ClearSourceMgr = true; break; } case PrintPreprocessedInput: { // -E mode. llvm::TimeRegion Timer(ClangFrontendTimer); DoPrintPreprocessedInput(PP, OutputFile); ClearSourceMgr = true; break; } case ParseNoop: { // -parse-noop llvm::TimeRegion Timer(ClangFrontendTimer); ParseFile(PP, new MinimalAction(PP)); ClearSourceMgr = true; break; } case ParsePrintCallbacks: { llvm::TimeRegion Timer(ClangFrontendTimer); ParseFile(PP, CreatePrintParserActionsAction(PP)); ClearSourceMgr = true; break; } case ParseSyntaxOnly: { // -fsyntax-only llvm::TimeRegion Timer(ClangFrontendTimer); Consumer.reset(new ASTConsumer()); break; } case RewriteMacros: RewriteMacrosInInput(PP, InFile, OutputFile); ClearSourceMgr = true; break; case RewriteTest: { DoRewriteTest(PP, InFile, OutputFile); ClearSourceMgr = true; break; } case FixIt: llvm::TimeRegion Timer(ClangFrontendTimer); Consumer.reset(new ASTConsumer()); FixItRewrite = new FixItRewriter(PP.getDiagnostics(), PP.getSourceManager(), PP.getLangOptions()); break; } if (Consumer) { llvm::OwningPtr<ASTContext> ContextOwner; if (FixItAtLocations.size() > 0) { // Even without the "-fixit" flag, with may have some specific // locations where the user has requested fixes. Process those // locations now. if (!FixItRewrite) FixItRewrite = new FixItRewriter(PP.getDiagnostics(), PP.getSourceManager(), PP.getLangOptions()); bool AddedFixitLocation = false; for (unsigned Idx = 0, Last = FixItAtLocations.size(); Idx != Last; ++Idx) { RequestedSourceLocation Requested; if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(), Requested)) { fprintf(stderr, "FIX-IT could not find file \"%s\"\n", FixItAtLocations[Idx].FileName.c_str()); } else { FixItRewrite->addFixItLocation(Requested); AddedFixitLocation = true; } } if (!AddedFixitLocation) { // All of the fix-it locations were bad. Don't fix anything. delete FixItRewrite; FixItRewrite = 0; } } ContextOwner.reset(new ASTContext(PP.getLangOptions(), PP.getSourceManager(), PP.getTargetInfo(), PP.getIdentifierTable(), PP.getSelectorTable(), /* FreeMemory = */ !DisableFree)); if (!ImplicitIncludePCH.empty()) { // The user has asked us to include a precompiled header. Load // the precompiled header into the AST context. llvm::OwningPtr<PCHReader> Reader(new PCHReader(PP, *ContextOwner.get())); switch (Reader->ReadPCH(ImplicitIncludePCH)) { case PCHReader::Success: { // Attach the PCH reader to the AST context as an external AST // source, so that declarations will be deserialized from the // PCH file as needed. llvm::OwningPtr<ExternalASTSource> Source(Reader.take()); ContextOwner->setExternalSource(Source); // Clear out the predefines buffer, because all of the // predefines are already in the PCH file. PP.setPredefines(""); break; } case PCHReader::Failure: // Unrecoverable failure: don't even try to process the input // file. return; case PCHReader::IgnorePCH: // No suitable PCH file could be found. Just ignore the // -include-pch option entirely. break; } // Finish preprocessor initialization. We do this now (rather // than earlier) because this initialization creates new source // location entries in the source manager, which must come after // the source location entries for the PCH file. if (InitializeSourceManager(PP, InFile)) return; } ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats, CompleteTranslationUnit); if (FixItRewrite) FixItRewrite->WriteFixedFile(InFile, OutputFile); // If in -disable-free mode, don't deallocate these when they go out of // scope. if (DisableFree) ContextOwner.take(); } if (VerifyDiagnostics) if (CheckDiagnostics(PP)) exit(1); if (Stats) { fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str()); PP.PrintStats(); PP.getIdentifierTable().PrintStats(); PP.getHeaderSearchInfo().PrintStats(); PP.getSourceManager().PrintStats(); fprintf(stderr, "\n"); } // For a multi-file compilation, some things are ok with nuking the source // manager tables, other require stable fileid/macroid's across multiple // files. if (ClearSourceMgr) PP.getSourceManager().clearIDTables(); if (DisableFree) Consumer.take(); } static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag, FileManager& FileMgr) { if (VerifyDiagnostics) { fprintf(stderr, "-verify does not yet work with serialized ASTs.\n"); exit (1); } llvm::sys::Path Filename(InFile); if (!Filename.isValid()) { fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str()); exit (1); } llvm::OwningPtr<ASTContext> Ctx; // Create the memory buffer that contains the contents of the file. llvm::OwningPtr<llvm::MemoryBuffer> MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str())); if (MBuffer) Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr)); if (!Ctx) { fprintf(stderr, "error: file '%s' could not be deserialized\n", InFile.c_str()); exit (1); } // Observe that we use the source file name stored in the deserialized // translation unit, rather than InFile. llvm::OwningPtr<ASTConsumer> Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(), 0, 0)); if (!Consumer) { fprintf(stderr, "Unsupported program action with serialized ASTs!\n"); exit (1); } Consumer->Initialize(*Ctx); // FIXME: We need to inform Consumer about completed TagDecls as well. TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl(); for (DeclContext::decl_iterator I = TUD->decls_begin(*Ctx), E = TUD->decls_end(*Ctx); I != E; ++I) Consumer->HandleTopLevelDecl(DeclGroupRef(*I)); } static llvm::cl::list<std::string> InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>")); static bool isSerializedFile(const std::string& InFile) { if (InFile.size() < 4) return false; const char* s = InFile.c_str()+InFile.size()-4; return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't'; } int main(int argc, char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "LLVM 'Clang' Compiler: http://clang.llvm.org\n"); if (TimeReport) ClangFrontendTimer = new llvm::Timer("Clang front-end time"); // If no input was specified, read from stdin. if (InputFilenames.empty()) InputFilenames.push_back("-"); // Create the diagnostic client for reporting errors or for // implementing -verify. DiagnosticClient* TextDiagClient = 0; if (!VerifyDiagnostics) { // Print diagnostics to stderr by default. TextDiagClient = new TextDiagnosticPrinter(llvm::errs(), !NoShowColumn, !NoCaretDiagnostics, !NoShowLocation, PrintSourceRangeInfo, PrintDiagnosticOption); } else { // When checking diagnostics, just buffer them up. TextDiagClient = new TextDiagnosticBuffer(); if (InputFilenames.size() != 1) { fprintf(stderr, "-verify only works on single input files for now.\n"); return 1; } } // Configure our handling of diagnostics. llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient); Diagnostic Diags(DiagClient.get()); if (ProcessWarningOptions(Diags)) return 1; // -I- is a deprecated GCC feature, scan for it and reject it. for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) { if (I_dirs[i] == "-") { Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported); I_dirs.erase(I_dirs.begin()+i); --i; } } // Get information about the target being compiled for. std::string Triple = CreateTargetTriple(); llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple)); if (Target == 0) { Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple) << Triple.c_str(); return 1; } if (!InheritanceViewCls.empty()) // C++ visualization? ProgAction = InheritanceView; llvm::OwningPtr<SourceManager> SourceMgr; // Create a file manager object to provide access to and cache the filesystem. FileManager FileMgr; for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) { const std::string &InFile = InputFilenames[i]; if (isSerializedFile(InFile)) { Diags.setClient(TextDiagClient); ProcessSerializedFile(InFile,Diags,FileMgr); continue; } /// Create a SourceManager object. This tracks and owns all the file /// buffers allocated to a translation unit. if (!SourceMgr) SourceMgr.reset(new SourceManager()); else SourceMgr->clearIDTables(); // Initialize language options, inferring file types from input filenames. LangOptions LangInfo; if (!VerifyDiagnostics) static_cast<TextDiagnosticPrinter*>(TextDiagClient) ->SetLangOpts(LangInfo); InitializeBaseLanguage(); LangKind LK = GetLanguage(InFile); InitializeLangOptions(LangInfo, LK); InitializeLanguageStandard(LangInfo, LK, Target.get()); // Process the -I options and set them in the HeaderInfo. HeaderSearch HeaderInfo(FileMgr); InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo); // Set up the preprocessor with these options. DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target, *SourceMgr.get(), HeaderInfo); llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor()); if (!PP) continue; if (ImplicitIncludePCH.empty() && InitializeSourceManager(*PP.get(), InFile)) continue; // Create the HTMLDiagnosticsClient if we are using one. Otherwise, // always reset to using TextDiagClient. llvm::OwningPtr<DiagnosticClient> TmpClient; if (!HTMLDiag.empty()) { TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(), &PPFactory)); Diags.setClient(TmpClient.get()); } else Diags.setClient(TextDiagClient); // Process the source file. ProcessInputFile(*PP, PPFactory, InFile, ProgAction); HeaderInfo.ClearFileInfo(); } if (Verbose) fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING " hosted on " LLVM_HOSTTRIPLE "\n"); if (unsigned NumDiagnostics = Diags.getNumDiagnostics()) fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics, (NumDiagnostics == 1 ? "" : "s")); if (Stats) { FileMgr.PrintStats(); fprintf(stderr, "\n"); } // If verifying diagnostics and we reached here, all is well. if (VerifyDiagnostics) return 0; delete ClangFrontendTimer; // Managed static deconstruction. Useful for making things like // -time-passes usable. llvm::llvm_shutdown(); return HadErrors || (Diags.getNumErrors() != 0); } <file_sep>/test/FixIt/fixit.c // RUN: clang-cc -fsyntax-only -pedantic -fixit %s -o - | clang-cc -pedantic -Werror -x c - /* This is a test of the various code modification hints that are provided as part of warning or extension diagnostics. All of the warnings will be fixed by -fixit, and the resulting file should compile cleanly with -Werror -pedantic. */ #include <string.h> // FIXME: FIX-IT hint should add this for us! void f0(void) { }; struct s { int x, y;; }; _Complex cd; struct s s0 = { y: 5 }; int array0[5] = { [3] 3 }; void f1(x, y) { } int i0 = { 17 }; int f2(const char *my_string) { // FIXME: terminal output isn't so good when "my_string" is shorter return my_string == "foo"; } <file_sep>/lib/Rewrite/CMakeLists.txt set(LLVM_NO_RTTI 1) add_clang_library(clangRewrite DeltaTree.cpp HTMLRewrite.cpp Rewriter.cpp RewriteRope.cpp TokenRewriter.cpp ) <file_sep>/lib/Headers/tmmintrin.h /*===---- tmmintrin.h - SSSE3 intrinsics -----------------------------------=== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * *===-----------------------------------------------------------------------=== */ #ifndef __TMMINTRIN_H #define __TMMINTRIN_H #ifndef __SSSE3__ #error "SSSE3 instruction set not enabled" #else #include <pmmintrin.h> static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_abs_pi8(__m64 a) { return (__m64)__builtin_ia32_pabsb((__v8qi)a); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_abs_epi8(__m128i a) { return (__m128i)__builtin_ia32_pabsb128((__v16qi)a); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_abs_pi16(__m64 a) { return (__m64)__builtin_ia32_pabsw((__v4hi)a); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_abs_epi16(__m128i a) { return (__m128i)__builtin_ia32_pabsw128((__v8hi)a); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_abs_pi32(__m64 a) { return (__m64)__builtin_ia32_pabsd((__v2si)a); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_abs_epi32(__m128i a) { return (__m128i)__builtin_ia32_pabsd128((__v4si)a); } #define _mm_alignr_epi8(a, b, n) (__builtin_ia32_palignr128((a), (b), (n))) #define _mm_alignr_pi8(a, b, n) (__builtin_ia32_palignr((a), (b), (n))) static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hadd_epi16(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_phaddw128((__v8hi)a, (__v8hi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hadd_epi32(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_phaddd128((__v4si)a, (__v4si)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hadd_pi16(__m64 a, __m64 b) { return (__m64)__builtin_ia32_phaddw((__v4hi)a, (__v4hi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hadd_pi32(__m64 a, __m64 b) { return (__m64)__builtin_ia32_phaddd((__v2si)a, (__v2si)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hadds_epi16(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_phaddsw128((__v8hi)a, (__v8hi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hadds_pi16(__m64 a, __m64 b) { return (__m64)__builtin_ia32_phaddsw((__v4hi)a, (__v4hi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hsub_epi16(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_phsubw128((__v8hi)a, (__v8hi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hsub_epi32(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_psubd128((__v4si)a, (__v4si)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hsub_pi16(__m64 a, __m64 b) { return (__m64)__builtin_ia32_psubw((__v4hi)a, (__v4hi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hsub_pi32(__m64 a, __m64 b) { return (__m64)__builtin_ia32_psubd((__v2si)a, (__v2si)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_hsubs_epi16(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_phsubsw128((__v8hi)a, (__v8hi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_hsubs_pi16(__m64 a, __m64 b) { return (__m64)__builtin_ia32_phsubsw((__v4hi)a, (__v4hi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_maddubs_epi16(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_pmaddubsw128((__v16qi)a, (__v16qi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_maddubs_pi16(__m64 a, __m64 b) { return (__m64)__builtin_ia32_pmaddubsw((__v8qi)a, (__v8qi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_mulrhs_epi16(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_pmulhrsw128((__v8hi)a, (__v8hi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_mulrhs_pi16(__m64 a, __m64 b) { return (__m64)__builtin_ia32_pmulhrsw((__v4hi)a, (__v4hi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_shuffle_epi8(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_pshufb128((__v16qi)a, (__v16qi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_shuffle_pi8(__m64 a, __m64 b) { return (__m64)__builtin_ia32_pshufb((__v8qi)a, (__v8qi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_sign_epi8(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_psignb128((__v16qi)a, (__v16qi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_sign_epi16(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_psignw128((__v8hi)a, (__v8hi)b); } static inline __m128i __attribute__((__always_inline__, __nodebug__)) _mm_sign_epi32(__m128i a, __m128i b) { return (__m128i)__builtin_ia32_psignd128((__v4si)a, (__v4si)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_sign_pi8(__m64 a, __m64 b) { return (__m64)__builtin_ia32_psignb((__v8qi)a, (__v8qi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_sign_pi16(__m64 a, __m64 b) { return (__m64)__builtin_ia32_psignw((__v4hi)a, (__v4hi)b); } static inline __m64 __attribute__((__always_inline__, __nodebug__)) _mm_sign_pi32(__m64 a, __m64 b) { return (__m64)__builtin_ia32_psignd((__v2si)a, (__v2si)b); } #endif /* __SSSE3__ */ #endif /* __TMMINTRIN_H */ <file_sep>/test/Analysis/rdar-6539791.c // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify %s typedef const struct __CFAllocator * CFAllocatorRef; typedef struct __CFDictionary * CFMutableDictionaryRef; typedef signed long CFIndex; typedef CFIndex CFNumberType; typedef const void * CFTypeRef; typedef struct {} CFDictionaryKeyCallBacks, CFDictionaryValueCallBacks; typedef const struct __CFNumber * CFNumberRef; extern const CFAllocatorRef kCFAllocatorDefault; extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks; extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks; enum { kCFNumberSInt32Type = 3 }; CFMutableDictionaryRef CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks); void CFDictionaryAddValue(CFMutableDictionaryRef theDict, const void *key, const void *value); void CFRelease(CFTypeRef cf); CFTypeRef CFRetain(CFTypeRef cf); extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr); typedef const struct __CFArray * CFArrayRef; typedef struct __CFArray * CFMutableArrayRef; void CFArrayAppendValue(CFMutableArrayRef theArray, const void *value); void f(CFMutableDictionaryRef y, void* key, void* val_key) { CFMutableDictionaryRef x = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(y, key, x); CFRelease(x); // the dictionary keeps a reference, so the object isn't deallocated yet signed z = 1; CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); if (value) { CFDictionaryAddValue(x, val_key, value); // no-warning CFRelease(value); CFDictionaryAddValue(y, val_key, value); // no-warning } } // <rdar://problem/6560661> // Same issue, except with "AppendValue" functions. void f2(CFMutableArrayRef x) { signed z = 1; CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &z); // CFArrayAppendValue keeps a reference to value. CFArrayAppendValue(x, value); CFRelease(value); CFRetain(value); CFRelease(value); // no-warning } <file_sep>/test/SemaTemplate/instantiate-template-template-parm.cpp // RUN: clang-cc -fsyntax-only -verify %s template<template<typename T> class MetaFun, typename Value> struct apply { typedef typename MetaFun<Value>::type type; }; template<class T> struct add_pointer { typedef T* type; }; template<class T> struct add_reference { typedef T& type; }; int i; apply<add_pointer, int>::type ip = &i; apply<add_reference, int>::type ir = i; apply<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}} <file_sep>/lib/Driver/Arg.cpp //===--- Arg.cpp - Argument Implementations -----------------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Option.h" #include "llvm/Support/raw_ostream.h" using namespace clang::driver; Arg::Arg(ArgClass _Kind, const Option *_Opt, unsigned _Index, const Arg *_BaseArg) : Kind(_Kind), Opt(_Opt), BaseArg(_BaseArg), Index(_Index), Claimed(false) { } Arg::~Arg() { } void Arg::dump() const { llvm::errs() << "<"; switch (Kind) { default: assert(0 && "Invalid kind"); #define P(N) case N: llvm::errs() << #N; break P(FlagClass); P(PositionalClass); P(JoinedClass); P(SeparateClass); P(CommaJoinedClass); P(JoinedAndSeparateClass); #undef P } llvm::errs() << " Opt:"; Opt->dump(); llvm::errs() << " Index:" << Index; if (isa<CommaJoinedArg>(this) || isa<SeparateArg>(this)) llvm::errs() << " NumValues:" << getNumValues(); llvm::errs() << ">\n"; } std::string Arg::getAsString(const ArgList &Args) const { std::string Res; llvm::raw_string_ostream OS(Res); ArgStringList ASL; render(Args, ASL); for (ArgStringList::iterator it = ASL.begin(), ie = ASL.end(); it != ie; ++it) { if (it != ASL.begin()) OS << ' '; OS << *it; } return OS.str(); } void Arg::renderAsInput(const ArgList &Args, ArgStringList &Output) const { if (!getOption().hasNoOptAsInput()) { render(Args, Output); return; } for (unsigned i = 0, e = getNumValues(); i != e; ++i) Output.push_back(getValue(Args, i)); } FlagArg::FlagArg(const Option *Opt, unsigned Index, const Arg *BaseArg) : Arg(FlagClass, Opt, Index, BaseArg) { } void FlagArg::render(const ArgList &Args, ArgStringList &Output) const { Output.push_back(Args.getArgString(getIndex())); } const char *FlagArg::getValue(const ArgList &Args, unsigned N) const { assert(0 && "Invalid index."); return 0; } PositionalArg::PositionalArg(const Option *Opt, unsigned Index, const Arg *BaseArg) : Arg(PositionalClass, Opt, Index, BaseArg) { } void PositionalArg::render(const ArgList &Args, ArgStringList &Output) const { Output.push_back(Args.getArgString(getIndex())); } const char *PositionalArg::getValue(const ArgList &Args, unsigned N) const { assert(N < getNumValues() && "Invalid index."); return Args.getArgString(getIndex()); } JoinedArg::JoinedArg(const Option *Opt, unsigned Index, const Arg *BaseArg) : Arg(JoinedClass, Opt, Index, BaseArg) { } void JoinedArg::render(const ArgList &Args, ArgStringList &Output) const { if (getOption().hasForceSeparateRender()) { Output.push_back(getOption().getName()); Output.push_back(getValue(Args, 0)); } else { Output.push_back(Args.getArgString(getIndex())); } } const char *JoinedArg::getValue(const ArgList &Args, unsigned N) const { assert(N < getNumValues() && "Invalid index."); // FIXME: Avoid strlen. return Args.getArgString(getIndex()) + strlen(getOption().getName()); } CommaJoinedArg::CommaJoinedArg(const Option *Opt, unsigned Index, const char *Str, const Arg *BaseArg) : Arg(CommaJoinedClass, Opt, Index, BaseArg) { const char *Prev = Str; for (;; ++Str) { char c = *Str; if (!c) { if (Prev != Str) Values.push_back(std::string(Prev, Str)); break; } else if (c == ',') { if (Prev != Str) Values.push_back(std::string(Prev, Str)); Prev = Str + 1; } } } void CommaJoinedArg::render(const ArgList &Args, ArgStringList &Output) const { Output.push_back(Args.getArgString(getIndex())); } const char *CommaJoinedArg::getValue(const ArgList &Args, unsigned N) const { assert(N < getNumValues() && "Invalid index."); return Values[N].c_str(); } SeparateArg::SeparateArg(const Option *Opt, unsigned Index, unsigned _NumValues, const Arg *BaseArg) : Arg(SeparateClass, Opt, Index, BaseArg), NumValues(_NumValues) { } void SeparateArg::render(const ArgList &Args, ArgStringList &Output) const { if (getOption().hasForceJoinedRender()) { assert(getNumValues() == 1 && "Cannot force joined render with > 1 args."); // FIXME: Avoid std::string. std::string Joined(getOption().getName()); Joined += Args.getArgString(getIndex()); Output.push_back(Args.MakeArgString(Joined.c_str())); } else { Output.push_back(Args.getArgString(getIndex())); for (unsigned i = 0; i < NumValues; ++i) Output.push_back(Args.getArgString(getIndex() + 1 + i)); } } const char *SeparateArg::getValue(const ArgList &Args, unsigned N) const { assert(N < getNumValues() && "Invalid index."); return Args.getArgString(getIndex() + 1 + N); } JoinedAndSeparateArg::JoinedAndSeparateArg(const Option *Opt, unsigned Index, const Arg *BaseArg) : Arg(JoinedAndSeparateClass, Opt, Index, BaseArg) { } void JoinedAndSeparateArg::render(const ArgList &Args, ArgStringList &Output) const { Output.push_back(Args.getArgString(getIndex())); Output.push_back(Args.getArgString(getIndex() + 1)); } const char *JoinedAndSeparateArg::getValue(const ArgList &Args, unsigned N) const { assert(N < getNumValues() && "Invalid index."); if (N == 0) return Args.getArgString(getIndex()) + strlen(getOption().getName()); return Args.getArgString(getIndex() + 1); } <file_sep>/lib/Frontend/CMakeLists.txt set(LLVM_NO_RTTI 1) add_clang_library(clangFrontend FixItRewriter.cpp HTMLDiagnostics.cpp InitHeaderSearch.cpp TextDiagnosticBuffer.cpp TextDiagnosticPrinter.cpp PCHReader.cpp PCHWriter.cpp PlistDiagnostics.cpp ManagerRegistry.cpp ) <file_sep>/lib/AST/Builtins.cpp //===--- Builtins.cpp - Builtin function implementation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements various things for builtin functions. // //===----------------------------------------------------------------------===// #include "clang/AST/Builtins.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/TargetInfo.h" using namespace clang; static const Builtin::Info BuiltinInfo[] = { { "not a builtin function", 0, 0, 0, false }, #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, false }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER, false }, #include "clang/AST/Builtins.def" }; const Builtin::Info &Builtin::Context::GetRecord(unsigned ID) const { if (ID < Builtin::FirstTSBuiltin) return BuiltinInfo[ID]; assert(ID - Builtin::FirstTSBuiltin < NumTSRecords && "Invalid builtin ID!"); return TSRecords[ID - Builtin::FirstTSBuiltin]; } /// InitializeBuiltins - Mark the identifiers for all the builtins with their /// appropriate builtin ID # and mark any non-portable builtin identifiers as /// such. void Builtin::Context::InitializeBuiltins(IdentifierTable &Table, const TargetInfo &Target, bool NoBuiltins) { // Step #1: mark all target-independent builtins with their ID's. for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i) if (!BuiltinInfo[i].Suppressed && (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f'))) Table.get(BuiltinInfo[i].Name).setBuiltinID(i); // Step #2: Get target builtins. Target.getTargetBuiltins(TSRecords, NumTSRecords); // Step #3: Register target-specific builtins. for (unsigned i = 0, e = NumTSRecords; i != e; ++i) if (!TSRecords[i].Suppressed && (!NoBuiltins || (TSRecords[i].Attributes && !strchr(TSRecords[i].Attributes, 'f')))) Table.get(TSRecords[i].Name).setBuiltinID(i+Builtin::FirstTSBuiltin); } bool Builtin::Context::isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg) { const char *Printf = strpbrk(GetRecord(ID).Attributes, "pP"); if (!Printf) return false; HasVAListArg = (*Printf == 'P'); ++Printf; assert(*Printf == ':' && "p or P specifier must have be followed by a ':'"); ++Printf; assert(strchr(Printf, ':') && "printf specifier must end with a ':'"); FormatIdx = strtol(Printf, 0, 10); return true; } /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the /// pointer over the consumed characters. This returns the resultant type. static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, Builtin::Context::GetBuiltinTypeError &Error, bool AllowTypeModifiers = true) { // Modifiers. bool Long = false, LongLong = false, Signed = false, Unsigned = false; // Read the modifiers first. bool Done = false; while (!Done) { switch (*Str++) { default: Done = true; --Str; break; case 'S': assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); assert(!Signed && "Can't use 'S' modifier multiple times!"); Signed = true; break; case 'U': assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); assert(!Unsigned && "Can't use 'S' modifier multiple times!"); Unsigned = true; break; case 'L': assert(!LongLong && "Can't have LLL modifier"); if (Long) LongLong = true; else Long = true; break; } } QualType Type; // Read the base type. switch (*Str++) { default: assert(0 && "Unknown builtin type letter!"); case 'v': assert(!Long && !Signed && !Unsigned && "Bad modifiers used with 'v'!"); Type = Context.VoidTy; break; case 'f': assert(!Long && !Signed && !Unsigned && "Bad modifiers used with 'f'!"); Type = Context.FloatTy; break; case 'd': assert(!LongLong && !Signed && !Unsigned && "Bad modifiers used with 'd'!"); if (Long) Type = Context.LongDoubleTy; else Type = Context.DoubleTy; break; case 's': assert(!LongLong && "Bad modifiers used with 's'!"); if (Unsigned) Type = Context.UnsignedShortTy; else Type = Context.ShortTy; break; case 'i': if (LongLong) Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; else if (Long) Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; else if (Unsigned) Type = Context.UnsignedIntTy; else Type = Context.IntTy; // default is signed. break; case 'c': assert(!Long && !LongLong && "Bad modifiers used with 'c'!"); if (Signed) Type = Context.SignedCharTy; else if (Unsigned) Type = Context.UnsignedCharTy; else Type = Context.CharTy; break; case 'b': // boolean assert(!Long && !Signed && !Unsigned && "Bad modifiers for 'b'!"); Type = Context.BoolTy; break; case 'z': // size_t. assert(!Long && !Signed && !Unsigned && "Bad modifiers for 'z'!"); Type = Context.getSizeType(); break; case 'F': Type = Context.getCFConstantStringType(); break; case 'a': Type = Context.getBuiltinVaListType(); assert(!Type.isNull() && "builtin va list type not initialized!"); break; case 'A': // This is a "reference" to a va_list; however, what exactly // this means depends on how va_list is defined. There are two // different kinds of va_list: ones passed by value, and ones // passed by reference. An example of a by-value va_list is // x86, where va_list is a char*. An example of by-ref va_list // is x86-64, where va_list is a __va_list_tag[1]. For x86, // we want this argument to be a char*&; for x86-64, we want // it to be a __va_list_tag*. Type = Context.getBuiltinVaListType(); assert(!Type.isNull() && "builtin va list type not initialized!"); if (Type->isArrayType()) { Type = Context.getArrayDecayedType(Type); } else { Type = Context.getLValueReferenceType(Type); } break; case 'V': { char *End; unsigned NumElements = strtoul(Str, &End, 10); assert(End != Str && "Missing vector size"); Str = End; QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); Type = Context.getVectorType(ElementType, NumElements); break; } case 'P': { IdentifierInfo *II = &Context.Idents.get("FILE"); DeclContext::lookup_result Lookup = Context.getTranslationUnitDecl()->lookup(Context, II); if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) { Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first)); break; } else { Error = Builtin::Context::GE_Missing_FILE; return QualType(); } } } if (!AllowTypeModifiers) return Type; Done = false; while (!Done) { switch (*Str++) { default: Done = true; --Str; break; case '*': Type = Context.getPointerType(Type); break; case '&': Type = Context.getLValueReferenceType(Type); break; // FIXME: There's no way to have a built-in with an rvalue ref arg. case 'C': Type = Type.getQualifiedType(QualType::Const); break; } } return Type; } /// GetBuiltinType - Return the type for the specified builtin. QualType Builtin::Context::GetBuiltinType(unsigned id, ASTContext &Context, GetBuiltinTypeError &Error) const { const char *TypeStr = GetRecord(id).Type; llvm::SmallVector<QualType, 8> ArgTypes; Error = GE_None; QualType ResType = DecodeTypeFromStr(TypeStr, Context, Error); if (Error != GE_None) return QualType(); while (TypeStr[0] && TypeStr[0] != '.') { QualType Ty = DecodeTypeFromStr(TypeStr, Context, Error); if (Error != GE_None) return QualType(); // Do array -> pointer decay. The builtin should use the decayed type. if (Ty->isArrayType()) Ty = Context.getArrayDecayedType(Ty); ArgTypes.push_back(Ty); } assert((TypeStr[0] != '.' || TypeStr[1] == 0) && "'.' should only occur at end of builtin type list!"); // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);". if (ArgTypes.size() == 0 && TypeStr[0] == '.') return Context.getFunctionNoProtoType(ResType); return Context.getFunctionType(ResType, &ArgTypes[0], ArgTypes.size(), TypeStr[0] == '.', 0); } <file_sep>/test/CodeGen/builtin-count-zeros.c // RUN: clang-cc -emit-llvm %s -o - | grep 'cttz' | count 2 && // RUN: clang-cc -emit-llvm %s -o - | grep 'ctlz' | count 2 int a(int a) {return __builtin_ctz(a) + __builtin_clz(a);} <file_sep>/test/FixIt/fixit-at.c // RUN: clang-cc -fsyntax-only -fixit-at=fixit-at.c:3:1 %s -o - | clang-cc -verify -x c - _Complex cd; int i0 = { 17 }; // expected-warning{{braces}} <file_sep>/test/Sema/const-ptr-int-ptr-cast.c // RUN: clang-cc -fsyntax-only -verify %s #include <stdint.h> char *a = (void*)(uintptr_t)(void*)&a; <file_sep>/test/Preprocessor/assembler-with-cpp.c // RUN: clang-cc -x assembler-with-cpp -E %s > %t && #ifndef __ASSEMBLER__ #error "__ASSEMBLER__ not defined" #endif // Invalid token pasting is ok. // RUN: grep '1: X .' %t && #define A X ## . 1: A // Line markers are not linemarkers in .S files, they are passed through. // RUN: grep '# 321' %t && # 321 // Unknown directives are passed through. // RUN: grep '# B C' %t && # B C // Unknown directives are expanded. // RUN: grep '# BAR42' %t && #define D(x) BAR ## x # D(42) // Unmatched quotes are permitted. // RUN: grep "2: '" %t && // RUN: grep '3: "' %t && 2: ' 3: " // Empty char literals are ok. // RUN: grep "4: ''" %t && 4: '' // Portions of invalid pasting should still expand as macros. // rdar://6709206 // RUN: grep "5: expanded (" %t && #define M4 expanded #define M5() M4 ## ( 5: M5() // RUN: true <file_sep>/test/CodeGen/2008-07-29-override-alias-decl.c // RUN: clang-cc -emit-llvm -o - %s | grep -e "^@f" | count 1 int x() {} int f() __attribute__((weak, alias("x"))); /* Test that we link to the alias correctly instead of making a new forward definition. */ int f(); int h() { return f(); } <file_sep>/lib/Sema/SemaCXXScopeSpec.cpp //===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements C++ semantic analysis for scope specifiers. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/Parse/DeclSpec.h" #include "llvm/ADT/STLExtras.h" using namespace clang; /// \brief Compute the DeclContext that is associated with the given /// scope specifier. DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS) { if (!SS.isSet() || SS.isInvalid()) return 0; NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); if (NNS->isDependent()) return 0; switch (NNS->getKind()) { case NestedNameSpecifier::Identifier: assert(false && "Dependent nested-name-specifier has no DeclContext"); break; case NestedNameSpecifier::Namespace: return NNS->getAsNamespace(); case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { const TagType *Tag = NNS->getAsType()->getAsTagType(); assert(Tag && "Non-tag type in nested-name-specifier"); return Tag->getDecl(); } break; case NestedNameSpecifier::Global: return Context.getTranslationUnitDecl(); } // Required to silence a GCC warning. return 0; } bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) { if (!SS.isSet() || SS.isInvalid()) return false; NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); return NNS->isDependent(); } /// \brief Require that the context specified by SS be complete. /// /// If SS refers to a type, this routine checks whether the type is /// complete enough (or can be made complete enough) for name lookup /// into the DeclContext. A type that is not yet completed can be /// considered "complete enough" if it is a class/struct/union/enum /// that is currently being defined. Or, if we have a type that names /// a class template specialization that is not a complete type, we /// will attempt to instantiate that class template. bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) { if (!SS.isSet() || SS.isInvalid()) return false; DeclContext *DC = computeDeclContext(SS); if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) { // If we're currently defining this type, then lookup into the // type is okay: don't complain that it isn't complete yet. const TagType *TagT = Context.getTypeDeclType(Tag)->getAsTagType(); if (TagT->isBeingDefined()) return false; // The type must be complete. return RequireCompleteType(SS.getRange().getBegin(), Context.getTypeDeclType(Tag), diag::err_incomplete_nested_name_spec, SS.getRange()); } return false; } /// ActOnCXXGlobalScopeSpecifier - Return the object that represents the /// global scope ('::'). Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc) { return NestedNameSpecifier::GlobalSpecifier(Context); } /// ActOnCXXNestedNameSpecifier - Called during parsing of a /// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now /// we want to resolve "bar::". 'SS' is empty or the previously parsed /// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar', /// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'. /// Returns a CXXScopeTy* object representing the C++ scope. Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S, const CXXScopeSpec &SS, SourceLocation IdLoc, SourceLocation CCLoc, IdentifierInfo &II) { NestedNameSpecifier *Prefix = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); // If the prefix is already dependent, there is no name lookup to // perform. Just build the resulting nested-name-specifier. if (Prefix && Prefix->isDependent()) return NestedNameSpecifier::Create(Context, Prefix, &II); NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName); if (SD) { if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) return NestedNameSpecifier::Create(Context, Prefix, Namespace); if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) { // Determine whether we have a class (or, in C++0x, an enum) or // a typedef thereof. If so, build the nested-name-specifier. QualType T = Context.getTypeDeclType(Type); bool AcceptableType = false; if (T->isDependentType()) AcceptableType = true; else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) { if (TD->getUnderlyingType()->isRecordType() || (getLangOptions().CPlusPlus0x && TD->getUnderlyingType()->isEnumeralType())) AcceptableType = true; } else if (isa<RecordDecl>(Type) || (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type))) AcceptableType = true; if (AcceptableType) return NestedNameSpecifier::Create(Context, Prefix, false, T.getTypePtr()); } if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) return NestedNameSpecifier::Create(Context, Prefix, Alias->getNamespace()); // Fall through to produce an error: we found something that isn't // a class or a namespace. } // If we didn't find anything during our lookup, try again with // ordinary name lookup, which can help us produce better error // messages. if (!SD) SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName); unsigned DiagID; if (SD) DiagID = diag::err_expected_class_or_namespace; else if (SS.isSet()) DiagID = diag::err_typecheck_no_member; else DiagID = diag::err_undeclared_var_use; if (SS.isSet()) Diag(IdLoc, DiagID) << &II << SS.getRange(); else Diag(IdLoc, DiagID) << &II; return 0; } Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S, const CXXScopeSpec &SS, TypeTy *Ty, SourceRange TypeRange, SourceLocation CCLoc) { NestedNameSpecifier *Prefix = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false, QualType::getFromOpaquePtr(Ty).getTypePtr()); } /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) { assert(SS.isSet() && "Parser passed invalid CXXScopeSpec."); assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?"); PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity()); CurContext = computeDeclContext(SS); assert(CurContext && "No context?"); S->setEntity(CurContext); } /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) { assert(SS.isSet() && "Parser passed invalid CXXScopeSpec."); assert(S->getEntity() == computeDeclContext(SS) && "Context imbalance!"); S->setEntity(PreDeclaratorDC); PreDeclaratorDC = 0; // Reset CurContext to the nearest enclosing context. while (!S->getEntity() && S->getParent()) S = S->getParent(); CurContext = static_cast<DeclContext*>(S->getEntity()); assert(CurContext && "No context?"); } <file_sep>/lib/Frontend/TextDiagnosticPrinter.cpp //===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This diagnostic client prints out their diagnostic messages. // //===----------------------------------------------------------------------===// #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/Lexer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/SmallString.h" #include <algorithm> using namespace clang; void TextDiagnosticPrinter:: PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) { if (Loc.isInvalid()) return; PresumedLoc PLoc = SM.getPresumedLoc(Loc); // Print out the other include frames first. PrintIncludeStack(PLoc.getIncludeLoc(), SM); OS << "In file included from " << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n"; } /// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s) /// any characters in LineNo that intersect the SourceRange. void TextDiagnosticPrinter::HighlightRange(const SourceRange &R, const SourceManager &SM, unsigned LineNo, FileID FID, std::string &CaretLine, const std::string &SourceLine) { assert(CaretLine.size() == SourceLine.size() && "Expect a correspondence between source and caret line!"); if (!R.isValid()) return; SourceLocation Begin = SM.getInstantiationLoc(R.getBegin()); SourceLocation End = SM.getInstantiationLoc(R.getEnd()); // If the End location and the start location are the same and are a macro // location, then the range was something that came from a macro expansion // or _Pragma. If this is an object-like macro, the best we can do is to // highlight the range. If this is a function-like macro, we'd also like to // highlight the arguments. if (Begin == End && R.getEnd().isMacroID()) End = SM.getInstantiationRange(R.getEnd()).second; unsigned StartLineNo = SM.getInstantiationLineNumber(Begin); if (StartLineNo > LineNo || SM.getFileID(Begin) != FID) return; // No intersection. unsigned EndLineNo = SM.getInstantiationLineNumber(End); if (EndLineNo < LineNo || SM.getFileID(End) != FID) return; // No intersection. // Compute the column number of the start. unsigned StartColNo = 0; if (StartLineNo == LineNo) { StartColNo = SM.getInstantiationColumnNumber(Begin); if (StartColNo) --StartColNo; // Zero base the col #. } // Pick the first non-whitespace column. while (StartColNo < SourceLine.size() && (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t')) ++StartColNo; // Compute the column number of the end. unsigned EndColNo = CaretLine.size(); if (EndLineNo == LineNo) { EndColNo = SM.getInstantiationColumnNumber(End); if (EndColNo) { --EndColNo; // Zero base the col #. // Add in the length of the token, so that we cover multi-char tokens. EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts); } else { EndColNo = CaretLine.size(); } } // Pick the last non-whitespace column. if (EndColNo <= SourceLine.size()) while (EndColNo-1 && (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t')) --EndColNo; else EndColNo = SourceLine.size(); // Fill the range with ~'s. assert(StartColNo <= EndColNo && "Invalid range!"); for (unsigned i = StartColNo; i < EndColNo; ++i) CaretLine[i] = '~'; } void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc, SourceRange *Ranges, unsigned NumRanges, SourceManager &SM, const CodeModificationHint *Hints, unsigned NumHints) { assert(!Loc.isInvalid() && "must have a valid source location here"); // We always emit diagnostics about the instantiation points, not the spelling // points. This more closely correlates to what the user writes. if (!Loc.isFileID()) { SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first; EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM); // Map the location through the macro. Loc = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(Loc)); // Map the ranges. for (unsigned i = 0; i != NumRanges; ++i) { SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd(); if (S.isMacroID()) S = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(S)); if (E.isMacroID()) E = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(E)); Ranges[i] = SourceRange(S, E); } // Emit the file/line/column that this expansion came from. OS << SM.getBufferName(Loc) << ':' << SM.getInstantiationLineNumber(Loc) << ':'; if (ShowColumn) OS << SM.getInstantiationColumnNumber(Loc) << ':'; OS << " note: instantiated from:\n"; } // Decompose the location into a FID/Offset pair. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); FileID FID = LocInfo.first; unsigned FileOffset = LocInfo.second; // Get information about the buffer it points into. std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID); const char *BufStart = BufferInfo.first; unsigned ColNo = SM.getColumnNumber(FID, FileOffset); // Rewind from the current position to the start of the line. const char *TokPtr = BufStart+FileOffset; const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based. // Compute the line end. Scan forward from the error position to the end of // the line. const char *LineEnd = TokPtr; while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0') ++LineEnd; // Copy the line of code into an std::string for ease of manipulation. std::string SourceLine(LineStart, LineEnd); // Create a line for the caret that is filled with spaces that is the same // length as the line of source code. std::string CaretLine(LineEnd-LineStart, ' '); // Highlight all of the characters covered by Ranges with ~ characters. if (NumRanges) { unsigned LineNo = SM.getLineNumber(FID, FileOffset); for (unsigned i = 0, e = NumRanges; i != e; ++i) HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine); } // Next, insert the caret itself. if (ColNo-1 < CaretLine.size()) CaretLine[ColNo-1] = '^'; else CaretLine.push_back('^'); // Scan the source line, looking for tabs. If we find any, manually expand // them to 8 characters and update the CaretLine to match. for (unsigned i = 0; i != SourceLine.size(); ++i) { if (SourceLine[i] != '\t') continue; // Replace this tab with at least one space. SourceLine[i] = ' '; // Compute the number of spaces we need to insert. unsigned NumSpaces = ((i+8)&~7) - (i+1); assert(NumSpaces < 8 && "Invalid computation of space amt"); // Insert spaces into the SourceLine. SourceLine.insert(i+1, NumSpaces, ' '); // Insert spaces or ~'s into CaretLine. CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' '); } // Finally, remove any blank spaces from the end of CaretLine. while (CaretLine[CaretLine.size()-1] == ' ') CaretLine.erase(CaretLine.end()-1); // Emit what we have computed. OS << SourceLine << '\n'; OS << CaretLine << '\n'; if (NumHints) { std::string InsertionLine; for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints; Hint != LastHint; ++Hint) { if (Hint->InsertionLoc.isValid()) { // We have an insertion hint. Determine whether the inserted // code is on the same line as the caret. std::pair<FileID, unsigned> HintLocInfo = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc); if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) == SM.getLineNumber(FID, FileOffset)) { // Insert the new code into the line just below the code // that the user wrote. unsigned HintColNo = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second); unsigned LastColumnModified = HintColNo - 1 + Hint->CodeToInsert.size(); if (LastColumnModified > InsertionLine.size()) InsertionLine.resize(LastColumnModified, ' '); std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(), InsertionLine.begin() + HintColNo - 1); } } } if (!InsertionLine.empty()) OS << InsertionLine << '\n'; } } void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info) { // If the location is specified, print out a file/line/col and include trace // if enabled. if (Info.getLocation().isValid()) { const SourceManager &SM = Info.getLocation().getManager(); PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation()); unsigned LineNo = PLoc.getLine(); // First, if this diagnostic is not in the main file, print out the // "included from" lines. if (LastWarningLoc != PLoc.getIncludeLoc()) { LastWarningLoc = PLoc.getIncludeLoc(); PrintIncludeStack(LastWarningLoc, SM); } // Compute the column number. if (ShowLocation) { OS << PLoc.getFilename() << ':' << LineNo << ':'; if (ShowColumn) if (unsigned ColNo = PLoc.getColumn()) OS << ColNo << ':'; if (PrintRangeInfo && Info.getNumRanges()) { FileID CaretFileID = SM.getFileID(SM.getInstantiationLoc(Info.getLocation())); bool PrintedRange = false; for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) { SourceLocation B = Info.getRange(i).getBegin(); SourceLocation E = Info.getRange(i).getEnd(); std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B); E = SM.getInstantiationLoc(E); std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E); // If the start or end of the range is in another file, just discard // it. if (BInfo.first != CaretFileID || EInfo.first != CaretFileID) continue; // Add in the length of the token, so that we cover multi-char tokens. unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts); OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':' << SM.getColumnNumber(BInfo.first, BInfo.second) << '-' << SM.getLineNumber(EInfo.first, EInfo.second) << ':' << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}'; PrintedRange = true; } if (PrintedRange) OS << ':'; } OS << ' '; } } switch (Level) { case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type"); case Diagnostic::Note: OS << "note: "; break; case Diagnostic::Warning: OS << "warning: "; break; case Diagnostic::Error: OS << "error: "; break; case Diagnostic::Fatal: OS << "fatal error: "; break; } llvm::SmallString<100> OutStr; Info.FormatDiagnostic(OutStr); OS.write(OutStr.begin(), OutStr.size()); if (PrintDiagnosticOption) if (const char *Option = Diagnostic::getWarningOptionForDiag(Info.getID())) OS << " [-W" << Option << ']'; OS << '\n'; // If caret diagnostics are enabled and we have location, we want to // emit the caret. However, we only do this if the location moved // from the last diagnostic, if the last diagnostic was a note that // was part of a different warning or error diagnostic, or if the // diagnostic has ranges. We don't want to emit the same caret // multiple times if one loc has multiple diagnostics. if (CaretDiagnostics && Info.getLocation().isValid() && ((LastLoc != Info.getLocation()) || Info.getNumRanges() || (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) || Info.getNumCodeModificationHints())) { // Cache the LastLoc, it allows us to omit duplicate source/caret spewage. LastLoc = Info.getLocation(); LastCaretDiagnosticWasNote = (Level == Diagnostic::Note); // Get the ranges into a local array we can hack on. SourceRange Ranges[20]; unsigned NumRanges = Info.getNumRanges(); assert(NumRanges < 20 && "Out of space"); for (unsigned i = 0; i != NumRanges; ++i) Ranges[i] = Info.getRange(i); unsigned NumHints = Info.getNumCodeModificationHints(); for (unsigned idx = 0; idx < NumHints; ++idx) { const CodeModificationHint &Hint = Info.getCodeModificationHint(idx); if (Hint.RemoveRange.isValid()) { assert(NumRanges < 20 && "Out of space"); Ranges[NumRanges++] = Hint.RemoveRange; } } EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(), Info.getCodeModificationHints(), Info.getNumCodeModificationHints()); } OS.flush(); } <file_sep>/lib/Basic/Targets.cpp //===--- Targets.cpp - Implement -arch option and targets -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements construction of a TargetInfo object from a // target triple. // //===----------------------------------------------------------------------===// // FIXME: Layering violation #include "clang/AST/Builtins.h" #include "clang/AST/TargetBuiltins.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/SmallString.h" using namespace clang; //===----------------------------------------------------------------------===// // Common code shared among targets. //===----------------------------------------------------------------------===// static void Define(std::vector<char> &Buf, const char *Macro, const char *Val = "1") { const char *Def = "#define "; Buf.insert(Buf.end(), Def, Def+strlen(Def)); Buf.insert(Buf.end(), Macro, Macro+strlen(Macro)); Buf.push_back(' '); Buf.insert(Buf.end(), Val, Val+strlen(Val)); Buf.push_back('\n'); } /// DefineStd - Define a macro name and standard variants. For example if /// MacroName is "unix", then this will define "__unix", "__unix__", and "unix" /// when in GNU mode. static void DefineStd(std::vector<char> &Buf, const char *MacroName, const LangOptions &Opts) { assert(MacroName[0] != '_' && "Identifier should be in the user's namespace"); // If in GNU mode (e.g. -std=gnu99 but not -std=c99) define the raw identifier // in the user's namespace. if (Opts.GNUMode) Define(Buf, MacroName); // Define __unix. llvm::SmallString<20> TmpStr; TmpStr = "__"; TmpStr += MacroName; Define(Buf, TmpStr.c_str()); // Define __unix__. TmpStr += "__"; Define(Buf, TmpStr.c_str()); } //===----------------------------------------------------------------------===// // Defines specific to certain operating systems. //===----------------------------------------------------------------------===// static void getSolarisDefines(std::vector<char> &Defs) { Define(Defs, "__SUN__"); Define(Defs, "__SOLARIS__"); } static void getFreeBSDDefines(const LangOptions &Opts, bool is64Bit, const char *Triple, std::vector<char> &Defs) { // FreeBSD defines; list based off of gcc output const char *FreeBSD = strstr(Triple, "-freebsd"); FreeBSD += strlen("-freebsd"); char release[] = "X"; release[0] = FreeBSD[0]; char version[] = "X00001"; version[0] = FreeBSD[0]; Define(Defs, "__FreeBSD__", release); Define(Defs, "__FreeBSD_cc_version", version); Define(Defs, "__KPRINTF_ATTRIBUTE__"); DefineStd(Defs, "unix", Opts); Define(Defs, "__ELF__", "1"); if (is64Bit) { Define(Defs, "__LP64__"); } } static void getDragonFlyDefines(const LangOptions &Opts, std::vector<char> &Defs) { // DragonFly defines; list based off of gcc output Define(Defs, "__DragonFly__"); Define(Defs, "__DragonFly_cc_version", "100001"); Define(Defs, "__ELF__"); Define(Defs, "__KPRINTF_ATTRIBUTE__"); Define(Defs, "__tune_i386__"); DefineStd(Defs, "unix", Opts); } static void getLinuxDefines(const LangOptions &Opts, std::vector<char> &Defs) { // Linux defines; list based off of gcc output DefineStd(Defs, "unix", Opts); DefineStd(Defs, "linux", Opts); Define(Defs, "__gnu_linux__"); Define(Defs, "__ELF__", "1"); } /// getDarwinNumber - Parse the 'darwin number' out of the specific targe /// triple. For example, if we have darwin8.5 return 8,5,0. If any entry is /// not defined, return 0's. Return true if we have -darwin in the string or /// false otherwise. static bool getDarwinNumber(const char *Triple, unsigned &Maj, unsigned &Min, unsigned &Revision) { Maj = Min = Revision = 0; const char *Darwin = strstr(Triple, "-darwin"); if (Darwin == 0) return false; Darwin += strlen("-darwin"); if (Darwin[0] < '0' || Darwin[0] > '9') return true; Maj = Darwin[0]-'0'; ++Darwin; // Handle "darwin11". if (Maj == 1 && Darwin[0] >= '0' && Darwin[0] <= '9') { Maj = Maj*10 + (Darwin[0] - '0'); ++Darwin; } // Handle minor version: 10.4.9 -> darwin8.9 -> "1049" if (Darwin[0] != '.') return true; ++Darwin; if (Darwin[0] < '0' || Darwin[0] > '9') return true; Min = Darwin[0]-'0'; ++Darwin; // Handle 10.4.11 -> darwin8.11 if (Min == 1 && Darwin[0] >= '0' && Darwin[0] <= '9') { Min = Min*10 + (Darwin[0] - '0'); ++Darwin; } // Handle revision darwin8.9.1 if (Darwin[0] != '.') return true; ++Darwin; if (Darwin[0] < '0' || Darwin[0] > '9') return true; Revision = Darwin[0]-'0'; ++Darwin; if (Revision == 1 && Darwin[0] >= '0' && Darwin[0] <= '9') { Revision = Revision*10 + (Darwin[0] - '0'); ++Darwin; } return true; } static void getDarwinDefines(std::vector<char> &Defs, const LangOptions &Opts) { Define(Defs, "__APPLE__"); Define(Defs, "__MACH__"); Define(Defs, "OBJC_NEW_PROPERTIES"); // __weak is always defined, for use in blocks and with objc pointers. Define(Defs, "__weak", "__attribute__((objc_gc(weak)))"); // Darwin defines __strong even in C mode (just to nothing). if (!Opts.ObjC1 || Opts.getGCMode() == LangOptions::NonGC) Define(Defs, "__strong", ""); else Define(Defs, "__strong", "__attribute__((objc_gc(strong)))"); } static void getDarwinOSXDefines(std::vector<char> &Defs, const char *Triple) { // Figure out which "darwin number" the target triple is. "darwin9" -> 10.5. unsigned Maj, Min, Rev; if (getDarwinNumber(Triple, Maj, Min, Rev)) { char MacOSXStr[] = "1000"; if (Maj >= 4 && Maj <= 13) { // 10.0-10.9 // darwin7 -> 1030, darwin8 -> 1040, darwin9 -> 1050, etc. MacOSXStr[2] = '0' + Maj-4; } // Handle minor version: 10.4.9 -> darwin8.9 -> "1049" // Cap 10.4.11 -> darwin8.11 -> "1049" MacOSXStr[3] = std::min(Min, 9U)+'0'; Define(Defs, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__", MacOSXStr); } } static void getDarwinIPhoneOSDefines(std::vector<char> &Defs, const char *Triple) { // Figure out which "darwin number" the target triple is. "darwin9" -> 10.5. unsigned Maj, Min, Rev; if (getDarwinNumber(Triple, Maj, Min, Rev)) { // When targetting iPhone OS, interpret the minor version and // revision as the iPhone OS version char iPhoneOSStr[] = "10000"; if (Min >= 2 && Min <= 9) { // iPhone OS 2.0-9.0 // darwin9.2.0 -> 20000, darwin9.3.0 -> 30000, etc. iPhoneOSStr[0] = '0' + Min; } // Handle minor version: 2.2 -> darwin9.2.2 -> 20200 iPhoneOSStr[2] = std::min(Rev, 9U)+'0'; Define(Defs, "__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__", iPhoneOSStr); } } /// GetDarwinLanguageOptions - Set the default language options for darwin. static void GetDarwinLanguageOptions(LangOptions &Opts, const char *Triple) { Opts.NeXTRuntime = true; unsigned Maj, Min, Rev; if (!getDarwinNumber(Triple, Maj, Min, Rev)) return; // Blocks default to on for 10.6 (darwin10) and beyond. // As does nonfragile-abi for 64bit mode if (Maj > 9) Opts.Blocks = 1; if (Maj >= 9 && Opts.ObjC1 && !strncmp(Triple, "x86_64", 6)) Opts.ObjCNonFragileABI = 1; } //===----------------------------------------------------------------------===// // Specific target implementations. //===----------------------------------------------------------------------===// namespace { // PPC abstract base class class PPCTargetInfo : public TargetInfo { static const Builtin::Info BuiltinInfo[]; static const char * const GCCRegNames[]; static const TargetInfo::GCCRegAlias GCCRegAliases[]; public: PPCTargetInfo(const std::string& triple) : TargetInfo(triple) { CharIsSigned = false; } virtual void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const { Records = BuiltinInfo; NumRecords = clang::PPC::LastTSBuiltin-Builtin::FirstTSBuiltin; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const; virtual const char *getVAListDeclaration() const { return "typedef char* __builtin_va_list;"; // This is the right definition for ABI/V4: System V.4/eabi. /*return "typedef struct __va_list_tag {" " unsigned char gpr;" " unsigned char fpr;" " unsigned short reserved;" " void* overflow_arg_area;" " void* reg_save_area;" "} __builtin_va_list[1];";*/ } virtual const char *getTargetPrefix() const { return "ppc"; } virtual void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const; virtual void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const; virtual bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const { switch (*Name) { default: return false; case 'O': // Zero return true; case 'b': // Base register case 'f': // Floating point register info = (TargetInfo::ConstraintInfo)(info|TargetInfo::CI_AllowsRegister); return true; } } virtual const char *getClobbers() const { return ""; } }; const Builtin::Info PPCTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, false }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER, false }, #include "clang/AST/PPCBuiltins.def" }; /// PPCTargetInfo::getTargetDefines - Return a set of the PowerPC-specific /// #defines that are not tied to a specific subtarget. void PPCTargetInfo::getTargetDefines(const LangOptions &Opts, std::vector<char> &Defs) const { // Target identification. Define(Defs, "__ppc__"); Define(Defs, "_ARCH_PPC"); Define(Defs, "__POWERPC__"); if (PointerWidth == 64) { Define(Defs, "_ARCH_PPC64"); Define(Defs, "_LP64"); Define(Defs, "__LP64__"); Define(Defs, "__ppc64__"); } else { Define(Defs, "__ppc__"); } // Target properties. Define(Defs, "_BIG_ENDIAN"); Define(Defs, "__BIG_ENDIAN__"); // Subtarget options. Define(Defs, "__NATURAL_ALIGNMENT__"); Define(Defs, "__REGISTER_PREFIX__", ""); // FIXME: Should be controlled by command line option. Define(Defs, "__LONG_DOUBLE_128__"); } const char * const PPCTargetInfo::GCCRegNames[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "mq", "lr", "ctr", "ap", "0", "1", "2", "3", "4", "5", "6", "7", "xer", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "vrsave", "vscr", "spe_acc", "spefscr", "sfp" }; void PPCTargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } const TargetInfo::GCCRegAlias PPCTargetInfo::GCCRegAliases[] = { // While some of these aliases do map to different registers // they still share the same register name. { { "cc", "cr0", "fr0", "r0", "v0"}, "0" }, { { "cr1", "fr1", "r1", "sp", "v1"}, "1" }, { { "cr2", "fr2", "r2", "toc", "v2"}, "2" }, { { "cr3", "fr3", "r3", "v3"}, "3" }, { { "cr4", "fr4", "r4", "v4"}, "4" }, { { "cr5", "fr5", "r5", "v5"}, "5" }, { { "cr6", "fr6", "r6", "v6"}, "6" }, { { "cr7", "fr7", "r7", "v7"}, "7" }, { { "fr8", "r8", "v8"}, "8" }, { { "fr9", "r9", "v9"}, "9" }, { { "fr10", "r10", "v10"}, "10" }, { { "fr11", "r11", "v11"}, "11" }, { { "fr12", "r12", "v12"}, "12" }, { { "fr13", "r13", "v13"}, "13" }, { { "fr14", "r14", "v14"}, "14" }, { { "fr15", "r15", "v15"}, "15" }, { { "fr16", "r16", "v16"}, "16" }, { { "fr17", "r17", "v17"}, "17" }, { { "fr18", "r18", "v18"}, "18" }, { { "fr19", "r19", "v19"}, "19" }, { { "fr20", "r20", "v20"}, "20" }, { { "fr21", "r21", "v21"}, "21" }, { { "fr22", "r22", "v22"}, "22" }, { { "fr23", "r23", "v23"}, "23" }, { { "fr24", "r24", "v24"}, "24" }, { { "fr25", "r25", "v25"}, "25" }, { { "fr26", "r26", "v26"}, "26" }, { { "fr27", "r27", "v27"}, "27" }, { { "fr28", "r28", "v28"}, "28" }, { { "fr29", "r29", "v29"}, "29" }, { { "fr30", "r30", "v30"}, "30" }, { { "fr31", "r31", "v31"}, "31" }, }; void PPCTargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } } // end anonymous namespace. namespace { class PPC32TargetInfo : public PPCTargetInfo { public: PPC32TargetInfo(const std::string& triple) : PPCTargetInfo(triple) { DescriptionString = "E-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-v128:128:128"; } }; } // end anonymous namespace. namespace { class PPC64TargetInfo : public PPCTargetInfo { public: PPC64TargetInfo(const std::string& triple) : PPCTargetInfo(triple) { LongWidth = LongAlign = PointerWidth = PointerAlign = 64; DescriptionString = "E-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-v128:128:128"; } }; } // end anonymous namespace. namespace { class DarwinPPCTargetInfo : public PPC32TargetInfo { public: DarwinPPCTargetInfo(const std::string& triple) : PPC32TargetInfo(triple) {} virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { PPC32TargetInfo::getTargetDefines(Opts, Defines); getDarwinDefines(Defines, Opts); getDarwinOSXDefines(Defines, getTargetTriple()); } /// getDefaultLangOptions - Allow the target to specify default settings for /// various language options. These may be overridden by command line /// options. virtual void getDefaultLangOptions(LangOptions &Opts) { GetDarwinLanguageOptions(Opts, getTargetTriple()); } }; } // end anonymous namespace. namespace { class DarwinPPC64TargetInfo : public PPC64TargetInfo { public: DarwinPPC64TargetInfo(const std::string& triple) : PPC64TargetInfo(triple) {} virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { PPC64TargetInfo::getTargetDefines(Opts, Defines); getDarwinDefines(Defines, Opts); getDarwinOSXDefines(Defines, getTargetTriple()); } /// getDefaultLangOptions - Allow the target to specify default settings for /// various language options. These may be overridden by command line /// options. virtual void getDefaultLangOptions(LangOptions &Opts) { GetDarwinLanguageOptions(Opts, getTargetTriple()); } }; } // end anonymous namespace. namespace { // Namespace for x86 abstract base class const Builtin::Info BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, false }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER, false }, #include "clang/AST/X86Builtins.def" }; const char *GCCRegNames[] = { "ax", "dx", "cx", "bx", "si", "di", "bp", "sp", "st", "st(1)", "st(2)", "st(3)", "st(4)", "st(5)", "st(6)", "st(7)", "argp", "flags", "fspr", "dirflag", "frame", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }; const TargetInfo::GCCRegAlias GCCRegAliases[] = { { { "al", "ah", "eax", "rax" }, "ax" }, { { "bl", "bh", "ebx", "rbx" }, "bx" }, { { "cl", "ch", "ecx", "rcx" }, "cx" }, { { "dl", "dh", "edx", "rdx" }, "dx" }, { { "esi", "rsi" }, "si" }, { { "edi", "rdi" }, "di" }, { { "esp", "rsp" }, "sp" }, { { "ebp", "rbp" }, "bp" }, }; // X86 target abstract base class; x86-32 and x86-64 are very close, so // most of the implementation can be shared. class X86TargetInfo : public TargetInfo { enum X86SSEEnum { NoMMXSSE, MMX, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42 } SSELevel; public: X86TargetInfo(const std::string& triple) : TargetInfo(triple), // FIXME: hard coding to SSE2 for now. This should change to NoMMXSSE so // that the driver controls this. SSELevel(SSE2) { LongDoubleFormat = &llvm::APFloat::x87DoubleExtended; } virtual void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const { Records = BuiltinInfo; NumRecords = clang::X86::LastTSBuiltin-Builtin::FirstTSBuiltin; } virtual const char *getTargetPrefix() const { return "x86"; } virtual void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } virtual void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } virtual bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const; virtual std::string convertConstraint(const char Constraint) const; virtual const char *getClobbers() const { return "~{dirflag},~{fpsr},~{flags}"; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const; virtual int HandleTargetFeatures(std::string *StrArray, unsigned NumStrs, std::string &ErrorReason); }; /// HandleTargetOptions - Handle target-specific options like -msse2 and /// friends. An array of arguments is passed in: if they are all valid, this /// should handle them and return -1. If there is an error, the index of the /// invalid argument should be returned along with an optional error string. int X86TargetInfo::HandleTargetFeatures(std::string *StrArray, unsigned NumStrs, std::string &ErrorReason) { for (unsigned i = 0; i != NumStrs; ++i) { const std::string &Feature = StrArray[i]; if (Feature.size() < 2) return i; // Ignore explicitly disabled features. if (Feature[0] == '-') continue; // Feature strings are of the form "+feature". if (Feature[0] != '+') return i; // The set of supported subtarget features is defined in // lib/Target/X86/X86.td. Here we recognize and map onto our internal // state. if (Feature == "+mmx") SSELevel = std::max(SSELevel, MMX); else if (Feature == "+sse") SSELevel = std::max(SSELevel, SSE1); else if (Feature == "+sse2") SSELevel = std::max(SSELevel, SSE2); else if (Feature == "+sse3") SSELevel = std::max(SSELevel, SSE3); else if (Feature == "+ssse3") SSELevel = std::max(SSELevel, SSSE3); else if (Feature == "+sse41") SSELevel = std::max(SSELevel, SSE41); else if (Feature == "+sse42") SSELevel = std::max(SSELevel, SSE42); else if (Feature == "+64bit" || Feature == "+slow-bt-mem") // Ignore these features. continue; else return i; } return -1; } /// X86TargetInfo::getTargetDefines - Return a set of the X86-specific #defines /// that are not tied to a specific subtarget. void X86TargetInfo::getTargetDefines(const LangOptions &Opts, std::vector<char> &Defs) const { // Target identification. if (PointerWidth == 64) { Define(Defs, "_LP64"); Define(Defs, "__LP64__"); Define(Defs, "__amd64__"); Define(Defs, "__amd64"); Define(Defs, "__x86_64"); Define(Defs, "__x86_64__"); Define(Defs, "__SSE3__"); } else { DefineStd(Defs, "i386", Opts); } // Target properties. Define(Defs, "__LITTLE_ENDIAN__"); // Subtarget options. Define(Defs, "__nocona"); Define(Defs, "__nocona__"); Define(Defs, "__tune_nocona__"); Define(Defs, "__REGISTER_PREFIX__", ""); // Each case falls through to the previous one here. switch (SSELevel) { case SSE42: Define(Defs, "__SSE4_2__"); case SSE41: Define(Defs, "__SSE4_1__"); case SSSE3: Define(Defs, "__SSSE3__"); case SSE3: Define(Defs, "__SSE3__"); case SSE2: Define(Defs, "__SSE2__"); Define(Defs, "__SSE2_MATH__"); // -mfp-math=sse always implied. case SSE1: Define(Defs, "__SSE__"); Define(Defs, "__SSE_MATH__"); // -mfp-math=sse always implied. case MMX: Define(Defs, "__MMX__"); case NoMMXSSE: break; } } bool X86TargetInfo::validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const { switch (*Name) { default: return false; case 'a': // eax. case 'b': // ebx. case 'c': // ecx. case 'd': // edx. case 'S': // esi. case 'D': // edi. case 'A': // edx:eax. case 't': // top of floating point stack. case 'u': // second from top of floating point stack. case 'q': // Any register accessible as [r]l: a, b, c, and d. case 'y': // Any MMX register. case 'x': // Any SSE register. case 'Q': // Any register accessible as [r]h: a, b, c, and d. case 'e': // 32-bit signed integer constant for use with zero-extending // x86_64 instructions. case 'Z': // 32-bit unsigned integer constant for use with zero-extending // x86_64 instructions. case 'N': // unsigned 8-bit integer constant for use with in and out // instructions. info = (TargetInfo::ConstraintInfo)(info|TargetInfo::CI_AllowsRegister); return true; } } std::string X86TargetInfo::convertConstraint(const char Constraint) const { switch (Constraint) { case 'a': return std::string("{ax}"); case 'b': return std::string("{bx}"); case 'c': return std::string("{cx}"); case 'd': return std::string("{dx}"); case 'S': return std::string("{si}"); case 'D': return std::string("{di}"); case 't': // top of floating point stack. return std::string("{st}"); case 'u': // second from top of floating point stack. return std::string("{st(1)}"); // second from top of floating point stack. default: return std::string(1, Constraint); } } } // end anonymous namespace namespace { // X86-32 generic target class X86_32TargetInfo : public X86TargetInfo { public: X86_32TargetInfo(const std::string& triple) : X86TargetInfo(triple) { DoubleAlign = LongLongAlign = 32; LongDoubleWidth = 96; LongDoubleAlign = 32; DescriptionString = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-" "a0:0:64-f80:32:32"; SizeType = UnsignedInt; PtrDiffType = SignedInt; IntPtrType = SignedInt; RegParmMax = 3; } virtual const char *getVAListDeclaration() const { return "typedef char* __builtin_va_list;"; } }; } // end anonymous namespace namespace { // x86-32 Darwin (OS X) target class DarwinI386TargetInfo : public X86_32TargetInfo { public: DarwinI386TargetInfo(const std::string& triple) : X86_32TargetInfo(triple) { LongDoubleWidth = 128; LongDoubleAlign = 128; SizeType = UnsignedLong; IntPtrType = SignedLong; DescriptionString = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-" "a0:0:64-f80:128:128"; } virtual const char *getStringSymbolPrefix(bool IsConstant) const { return IsConstant ? "\01LC" : "\01lC"; } virtual const char *getUnicodeStringSymbolPrefix() const { return "__utf16_string_"; } virtual const char *getUnicodeStringSection() const { return "__TEXT,__ustring"; } virtual const char *getCFStringSymbolPrefix() const { return "\01LC"; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { X86_32TargetInfo::getTargetDefines(Opts, Defines); getDarwinDefines(Defines, Opts); getDarwinOSXDefines(Defines, getTargetTriple()); } /// getDefaultLangOptions - Allow the target to specify default settings for /// various language options. These may be overridden by command line /// options. virtual void getDefaultLangOptions(LangOptions &Opts) { GetDarwinLanguageOptions(Opts, getTargetTriple()); } }; } // end anonymous namespace namespace { // x86-32 FreeBSD target class FreeBSDX86_32TargetInfo : public X86_32TargetInfo { public: FreeBSDX86_32TargetInfo(const std::string& triple) : X86_32TargetInfo(triple) { } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { X86_32TargetInfo::getTargetDefines(Opts, Defines); getFreeBSDDefines(Opts, 0, getTargetTriple(), Defines); } }; } // end anonymous namespace namespace { // x86-32 DragonFly target class DragonFlyX86_32TargetInfo : public X86_32TargetInfo { public: DragonFlyX86_32TargetInfo(const std::string& triple) : X86_32TargetInfo(triple) { } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { X86_32TargetInfo::getTargetDefines(Opts, Defines); getDragonFlyDefines(Opts, Defines); } }; } // end anonymous namespace namespace { // x86-32 Linux target class LinuxX86_32TargetInfo : public X86_32TargetInfo { public: LinuxX86_32TargetInfo(const std::string& triple) : X86_32TargetInfo(triple) { UserLabelPrefix = ""; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { X86_32TargetInfo::getTargetDefines(Opts, Defines); getLinuxDefines(Opts, Defines); } }; } // end anonymous namespace namespace { // x86-32 Windows target class WindowsX86_32TargetInfo : public X86_32TargetInfo { public: WindowsX86_32TargetInfo(const std::string& triple) : X86_32TargetInfo(triple) { // FIXME: Fix wchar_t. // FIXME: We should probably enable -fms-extensions by default for // this target. } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { X86_32TargetInfo::getTargetDefines(Opts, Defines); // This list is based off of the the list of things MingW defines Define(Defines, "_WIN32"); DefineStd(Defines, "WIN32", Opts); DefineStd(Defines, "WINNT", Opts); Define(Defines, "_X86_"); Define(Defines, "__MSVCRT__"); } }; } // end anonymous namespace namespace { // x86-64 generic target class X86_64TargetInfo : public X86TargetInfo { public: X86_64TargetInfo(const std::string &triple) : X86TargetInfo(triple) { LongWidth = LongAlign = PointerWidth = PointerAlign = 64; DoubleAlign = LongLongAlign = 64; LongDoubleWidth = 128; LongDoubleAlign = 128; IntMaxType = SignedLong; UIntMaxType = UnsignedLong; RegParmMax = 6; DescriptionString = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-" "a0:0:64-f80:128:128"; } virtual const char *getVAListDeclaration() const { return "typedef struct __va_list_tag {" " unsigned gp_offset;" " unsigned fp_offset;" " void* overflow_arg_area;" " void* reg_save_area;" "} __builtin_va_list[1];"; } }; } // end anonymous namespace namespace { // x86-64 FreeBSD target class FreeBSDX86_64TargetInfo : public X86_64TargetInfo { public: FreeBSDX86_64TargetInfo(const std::string &triple) : X86_64TargetInfo(triple) {} virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { X86_64TargetInfo::getTargetDefines(Opts, Defines); getFreeBSDDefines(Opts, 1, getTargetTriple(), Defines); } }; } // end anonymous namespace namespace { // x86-64 Linux target class LinuxX86_64TargetInfo : public X86_64TargetInfo { public: LinuxX86_64TargetInfo(const std::string& triple) : X86_64TargetInfo(triple) { UserLabelPrefix = ""; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { X86_64TargetInfo::getTargetDefines(Opts, Defines); getLinuxDefines(Opts, Defines); } }; } // end anonymous namespace namespace { // x86-64 Darwin (OS X) target class DarwinX86_64TargetInfo : public X86_64TargetInfo { public: DarwinX86_64TargetInfo(const std::string& triple) : X86_64TargetInfo(triple) {} virtual const char *getStringSymbolPrefix(bool IsConstant) const { return IsConstant ? "\01LC" : "\01lC"; } virtual const char *getUnicodeStringSymbolPrefix() const { return "__utf16_string_"; } virtual const char *getUnicodeStringSection() const { return "__TEXT,__ustring"; } virtual const char *getCFStringSymbolPrefix() const { return "\01L_unnamed_cfstring_"; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { X86_64TargetInfo::getTargetDefines(Opts, Defines); getDarwinDefines(Defines, Opts); getDarwinOSXDefines(Defines, getTargetTriple()); } /// getDefaultLangOptions - Allow the target to specify default settings for /// various language options. These may be overridden by command line /// options. virtual void getDefaultLangOptions(LangOptions &Opts) { GetDarwinLanguageOptions(Opts, getTargetTriple()); } }; } // end anonymous namespace. namespace { class ARMTargetInfo : public TargetInfo { enum { Armv4t, Armv5, Armv6, XScale } ArmArch; public: ARMTargetInfo(const std::string& triple) : TargetInfo(triple) { // FIXME: Are the defaults correct for ARM? DescriptionString = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:64:64"; if (triple.find("arm-") || triple.find("armv6-")) ArmArch = Armv6; else if (triple.find("armv5-")) ArmArch = Armv5; else if (triple.find("armv4t-")) ArmArch = Armv4t; else if (triple.find("xscale-")) ArmArch = XScale; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defs) const { // Target identification. Define(Defs, "__arm"); Define(Defs, "__arm__"); // Target properties. Define(Defs, "__LITTLE_ENDIAN__"); // Subtarget options. if (ArmArch == Armv6) { Define(Defs, "__ARM_ARCH_6K__"); Define(Defs, "__THUMB_INTERWORK__"); } else if (ArmArch == Armv5) { Define(Defs, "__ARM_ARCH_5TEJ__"); Define(Defs, "__THUMB_INTERWORK__"); Define(Defs, "__SOFTFP__"); } else if (ArmArch == Armv4t) { Define(Defs, "__ARM_ARCH_4T__"); Define(Defs, "__SOFTFP__"); } else if (ArmArch == XScale) { Define(Defs, "__ARM_ARCH_5TE__"); Define(Defs, "__XSCALE__"); Define(Defs, "__SOFTFP__"); } Define(Defs, "__ARMEL__"); } virtual void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const { // FIXME: Implement. Records = 0; NumRecords = 0; } virtual const char *getVAListDeclaration() const { return "typedef char* __builtin_va_list;"; } virtual const char *getTargetPrefix() const { return "arm"; } virtual void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { // FIXME: Implement. Names = 0; NumNames = 0; } virtual void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { // FIXME: Implement. Aliases = 0; NumAliases = 0; } virtual bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const { // FIXME: Check if this is complete switch (*Name) { default: case 'l': // r0-r7 case 'h': // r8-r15 case 'w': // VFP Floating point register single precision case 'P': // VFP Floating point register double precision info = (TargetInfo::ConstraintInfo)(info|TargetInfo::CI_AllowsRegister); return true; } return false; } virtual const char *getClobbers() const { // FIXME: Is this really right? return ""; } }; } // end anonymous namespace. namespace { class DarwinARMTargetInfo : public ARMTargetInfo { public: DarwinARMTargetInfo(const std::string& triple) : ARMTargetInfo(triple) {} virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { ARMTargetInfo::getTargetDefines(Opts, Defines); getDarwinDefines(Defines, Opts); getDarwinIPhoneOSDefines(Defines, getTargetTriple()); } }; } // end anonymous namespace. namespace { // arm FreeBSD target class FreeBSDARMTargetInfo : public ARMTargetInfo { public: FreeBSDARMTargetInfo(const std::string& triple) : ARMTargetInfo(triple) {} virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { ARMTargetInfo::getTargetDefines(Opts, Defines); getFreeBSDDefines(Opts, 0, getTargetTriple(), Defines); } }; } // end anonymous namespace namespace { class SparcV8TargetInfo : public TargetInfo { static const TargetInfo::GCCRegAlias GCCRegAliases[]; static const char * const GCCRegNames[]; public: SparcV8TargetInfo(const std::string& triple) : TargetInfo(triple) { // FIXME: Support Sparc quad-precision long double? DescriptionString = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-v64:64:64"; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { // FIXME: This is missing a lot of important defines; some of the // missing stuff is likely to break system headers. Define(Defines, "__sparc"); Define(Defines, "__sparc__"); Define(Defines, "__sparcv8"); } virtual void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const { // FIXME: Implement! } virtual const char *getVAListDeclaration() const { return "typedef void* __builtin_va_list;"; } virtual const char *getTargetPrefix() const { return "sparc"; } virtual void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const; virtual void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const; virtual bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const { // FIXME: Implement! return false; } virtual const char *getClobbers() const { // FIXME: Implement! return ""; } }; const char * const SparcV8TargetInfo::GCCRegNames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31" }; void SparcV8TargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } const TargetInfo::GCCRegAlias SparcV8TargetInfo::GCCRegAliases[] = { { { "g0" }, "r0" }, { { "g1" }, "r1" }, { { "g2" }, "r2" }, { { "g3" }, "r3" }, { { "g4" }, "r4" }, { { "g5" }, "r5" }, { { "g6" }, "r6" }, { { "g7" }, "r7" }, { { "o0" }, "r8" }, { { "o1" }, "r9" }, { { "o2" }, "r10" }, { { "o3" }, "r11" }, { { "o4" }, "r12" }, { { "o5" }, "r13" }, { { "o6", "sp" }, "r14" }, { { "o7" }, "r15" }, { { "l0" }, "r16" }, { { "l1" }, "r17" }, { { "l2" }, "r18" }, { { "l3" }, "r19" }, { { "l4" }, "r20" }, { { "l5" }, "r21" }, { { "l6" }, "r22" }, { { "l7" }, "r23" }, { { "i0" }, "r24" }, { { "i1" }, "r25" }, { { "i2" }, "r26" }, { { "i3" }, "r27" }, { { "i4" }, "r28" }, { { "i5" }, "r29" }, { { "i6", "fp" }, "r30" }, { { "i7" }, "r31" }, }; void SparcV8TargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } } // end anonymous namespace. namespace { class SolarisSparcV8TargetInfo : public SparcV8TargetInfo { public: SolarisSparcV8TargetInfo(const std::string& triple) : SparcV8TargetInfo(triple) { SizeType = UnsignedInt; PtrDiffType = SignedInt; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { SparcV8TargetInfo::getTargetDefines(Opts, Defines); getSolarisDefines(Defines); } }; } // end anonymous namespace. namespace { class PIC16TargetInfo : public TargetInfo{ public: PIC16TargetInfo(const std::string& triple) : TargetInfo(triple) { IntWidth = 16; LongWidth = LongLongWidth = 32; PointerWidth = 16; IntAlign = 8; LongAlign = LongLongAlign = 8; PointerAlign = 8; SizeType = UnsignedInt; IntMaxType = SignedLong; UIntMaxType = UnsignedLong; IntPtrType = SignedShort; PtrDiffType = SignedInt; DescriptionString = "e-p:16:8:8-i8:8:8-i16:8:8-i32:8:8"; } virtual uint64_t getPointerWidthV(unsigned AddrSpace) const { return 16; } virtual uint64_t getPointerAlignV(unsigned AddrSpace) const { return 8; } virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &Defines) const { Define(Defines, "__pic16"); } virtual void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const {} virtual const char *getVAListDeclaration() const { return "";} virtual const char *getClobbers() const {return "";} virtual const char *getTargetPrefix() const {return "";} virtual void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const {} virtual bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const { return true; } virtual void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const {} virtual bool useGlobalsForAutomaticVariables() const {return true;} }; } //===----------------------------------------------------------------------===// // Driver code //===----------------------------------------------------------------------===// static inline bool IsX86(const std::string& TT) { return (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' && TT[4] == '-' && TT[1] - '3' < 6); } /// CreateTargetInfo - Return the target info object for the specified target /// triple. TargetInfo* TargetInfo::CreateTargetInfo(const std::string &T) { // OS detection; this isn't really anywhere near complete. // Additions and corrections are welcome. bool isDarwin = T.find("-darwin") != std::string::npos; bool isDragonFly = T.find("-dragonfly") != std::string::npos; bool isFreeBSD = T.find("-freebsd") != std::string::npos; bool isSolaris = T.find("-solaris") != std::string::npos; bool isLinux = T.find("-linux") != std::string::npos; bool isWindows = T.find("-windows") != std::string::npos || T.find("-win32") != std::string::npos || T.find("-mingw") != std::string::npos; if (T.find("ppc-") == 0 || T.find("powerpc-") == 0) { if (isDarwin) return new DarwinPPCTargetInfo(T); return new PPC32TargetInfo(T); } if (T.find("ppc64-") == 0 || T.find("powerpc64-") == 0) { if (isDarwin) return new DarwinPPC64TargetInfo(T); return new PPC64TargetInfo(T); } if (T.find("armv6-") == 0 || T.find("arm-") == 0 || T.find("armv4t") == 0 || T.find("armv5-") == 0 || T.find("xscale") == 0) { if (isDarwin) return new DarwinARMTargetInfo(T); if (isFreeBSD) return new FreeBSDARMTargetInfo(T); return new ARMTargetInfo(T); } if (T.find("sparc-") == 0) { if (isSolaris) return new SolarisSparcV8TargetInfo(T); return new SparcV8TargetInfo(T); } if (T.find("x86_64-") == 0 || T.find("amd64-") == 0) { if (isDarwin) return new DarwinX86_64TargetInfo(T); if (isLinux) return new LinuxX86_64TargetInfo(T); if (isFreeBSD) return new FreeBSDX86_64TargetInfo(T); return new X86_64TargetInfo(T); } if (T.find("pic16-") == 0) return new PIC16TargetInfo(T); if (IsX86(T)) { if (isDarwin) return new DarwinI386TargetInfo(T); if (isLinux) return new LinuxX86_32TargetInfo(T); if (isDragonFly) return new DragonFlyX86_32TargetInfo(T); if (isFreeBSD) return new FreeBSDX86_32TargetInfo(T); if (isWindows) return new WindowsX86_32TargetInfo(T); return new X86_32TargetInfo(T); } return NULL; } <file_sep>/include/clang/Analysis/PathSensitive/ConstraintManager.h //== ConstraintManager.h - Constraints on symbolic values.-------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defined the interface to manage constraints on symbolic values. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_CONSTRAINT_MANAGER_H #define LLVM_CLANG_ANALYSIS_CONSTRAINT_MANAGER_H // FIXME: Typedef LiveSymbolsTy/DeadSymbolsTy at a more appropriate place. #include "clang/Analysis/PathSensitive/Store.h" namespace llvm { class APSInt; } namespace clang { class GRState; class GRStateManager; class SVal; class ConstraintManager { public: virtual ~ConstraintManager(); virtual const GRState* Assume(const GRState* St, SVal Cond, bool Assumption, bool& isFeasible) = 0; virtual const GRState* AssumeInBound(const GRState* St, SVal Idx, SVal UpperBound, bool Assumption, bool& isFeasible) = 0; virtual const llvm::APSInt* getSymVal(const GRState* St, SymbolRef sym) const = 0; virtual bool isEqual(const GRState* St, SymbolRef sym, const llvm::APSInt& V) const = 0; virtual const GRState* RemoveDeadBindings(const GRState* St, SymbolReaper& SymReaper) = 0; virtual void print(const GRState* St, std::ostream& Out, const char* nl, const char *sep) = 0; virtual void EndPath(const GRState* St) {} /// canReasonAbout - Not all ConstraintManagers can accurately reason about /// all SVal values. This method returns true if the ConstraintManager can /// reasonably handle a given SVal value. This is typically queried by /// GRExprEngine to determine if the value should be replaced with a /// conjured symbolic value in order to recover some precision. virtual bool canReasonAbout(SVal X) const = 0; }; ConstraintManager* CreateBasicConstraintManager(GRStateManager& statemgr); ConstraintManager* CreateRangeConstraintManager(GRStateManager& statemgr); } // end clang namespace #endif <file_sep>/include/clang/AST/ExprObjC.h //===--- ExprObjC.h - Classes for representing ObjC expressions -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ExprObjC interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_EXPROBJC_H #define LLVM_CLANG_AST_EXPROBJC_H #include "clang/AST/Expr.h" #include "clang/Basic/IdentifierTable.h" namespace clang { class IdentifierInfo; class ASTContext; class ObjCMethodDecl; class ObjCPropertyDecl; /// ObjCStringLiteral, used for Objective-C string literals /// i.e. @"foo". class ObjCStringLiteral : public Expr { Stmt *String; SourceLocation AtLoc; public: ObjCStringLiteral(StringLiteral *SL, QualType T, SourceLocation L) : Expr(ObjCStringLiteralClass, T), String(SL), AtLoc(L) {} StringLiteral* getString() { return cast<StringLiteral>(String); } const StringLiteral* getString() const { return cast<StringLiteral>(String); } SourceLocation getAtLoc() const { return AtLoc; } virtual SourceRange getSourceRange() const { return SourceRange(AtLoc, String->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCStringLiteralClass; } static bool classof(const ObjCStringLiteral *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCStringLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCEncodeExpr, used for @encode in Objective-C. @encode has the same type /// and behavior as StringLiteral except that the string initializer is obtained /// from ASTContext with the encoding type as an argument. class ObjCEncodeExpr : public Expr { QualType EncType; SourceLocation AtLoc, RParenLoc; public: ObjCEncodeExpr(QualType T, QualType ET, SourceLocation at, SourceLocation rp) : Expr(ObjCEncodeExprClass, T), EncType(ET), AtLoc(at), RParenLoc(rp) {} SourceLocation getAtLoc() const { return AtLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } virtual SourceRange getSourceRange() const { return SourceRange(AtLoc, RParenLoc); } QualType getEncodedType() const { return EncType; } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCEncodeExprClass; } static bool classof(const ObjCEncodeExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCEncodeExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCSelectorExpr used for @selector in Objective-C. class ObjCSelectorExpr : public Expr { Selector SelName; SourceLocation AtLoc, RParenLoc; public: ObjCSelectorExpr(QualType T, Selector selInfo, SourceLocation at, SourceLocation rp) : Expr(ObjCSelectorExprClass, T), SelName(selInfo), AtLoc(at), RParenLoc(rp) {} Selector getSelector() const { return SelName; } SourceLocation getAtLoc() const { return AtLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } virtual SourceRange getSourceRange() const { return SourceRange(AtLoc, RParenLoc); } /// getNumArgs - Return the number of actual arguments to this call. unsigned getNumArgs() const { return SelName.getNumArgs(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCSelectorExprClass; } static bool classof(const ObjCSelectorExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCSelectorExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCProtocolExpr used for protocol in Objective-C. class ObjCProtocolExpr : public Expr { ObjCProtocolDecl *Protocol; SourceLocation AtLoc, RParenLoc; public: ObjCProtocolExpr(QualType T, ObjCProtocolDecl *protocol, SourceLocation at, SourceLocation rp) : Expr(ObjCProtocolExprClass, T), Protocol(protocol), AtLoc(at), RParenLoc(rp) {} ObjCProtocolDecl *getProtocol() const { return Protocol; } SourceLocation getAtLoc() const { return AtLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } virtual SourceRange getSourceRange() const { return SourceRange(AtLoc, RParenLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCProtocolExprClass; } static bool classof(const ObjCProtocolExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCProtocolExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCIvarRefExpr - A reference to an ObjC instance variable. class ObjCIvarRefExpr : public Expr { class ObjCIvarDecl *D; SourceLocation Loc; Stmt *Base; bool IsArrow:1; // True if this is "X->F", false if this is "X.F". bool IsFreeIvar:1; // True if ivar reference has no base (self assumed). public: ObjCIvarRefExpr(ObjCIvarDecl *d, QualType t, SourceLocation l, Expr *base=0, bool arrow = false, bool freeIvar = false) : Expr(ObjCIvarRefExprClass, t), D(d), Loc(l), Base(base), IsArrow(arrow), IsFreeIvar(freeIvar) {} ObjCIvarDecl *getDecl() { return D; } const ObjCIvarDecl *getDecl() const { return D; } virtual SourceRange getSourceRange() const { return isFreeIvar() ? SourceRange(Loc) : SourceRange(getBase()->getLocStart(), Loc); } const Expr *getBase() const { return cast<Expr>(Base); } Expr *getBase() { return cast<Expr>(Base); } void setBase(Expr * base) { Base = base; } bool isArrow() const { return IsArrow; } bool isFreeIvar() const { return IsFreeIvar; } SourceLocation getLocation() const { return Loc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCIvarRefExprClass; } static bool classof(const ObjCIvarRefExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCIvarRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC /// property. /// class ObjCPropertyRefExpr : public Expr { private: ObjCPropertyDecl *AsProperty; SourceLocation IdLoc; Stmt *Base; public: ObjCPropertyRefExpr(ObjCPropertyDecl *PD, QualType t, SourceLocation l, Expr *base) : Expr(ObjCPropertyRefExprClass, t), AsProperty(PD), IdLoc(l), Base(base) { } ObjCPropertyDecl *getProperty() const { return AsProperty; } virtual SourceRange getSourceRange() const { return SourceRange(getBase()->getLocStart(), IdLoc); } const Expr *getBase() const { return cast<Expr>(Base); } Expr *getBase() { return cast<Expr>(Base); } void setBase(Expr * base) { Base = base; } SourceLocation getLocation() const { return IdLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCPropertyRefExprClass; } static bool classof(const ObjCPropertyRefExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCPropertyRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCKVCRefExpr - A dot-syntax expression to access "implicit" properties /// (i.e. methods following the property naming convention). KVC stands for /// Key Value Encoding, a generic concept for accessing or setting a 'Key' /// value for an object. /// class ObjCKVCRefExpr : public Expr { private: ObjCMethodDecl *Setter; ObjCMethodDecl *Getter; SourceLocation Loc; // FIXME: Swizzle these into a single pointer. Stmt *Base; ObjCInterfaceDecl *ClassProp; SourceLocation ClassLoc; public: ObjCKVCRefExpr(ObjCMethodDecl *getter, QualType t, ObjCMethodDecl *setter, SourceLocation l, Expr *base) : Expr(ObjCKVCRefExprClass, t), Setter(setter), Getter(getter), Loc(l), Base(base), ClassProp(0), ClassLoc(SourceLocation()) { } ObjCKVCRefExpr(ObjCMethodDecl *getter, QualType t, ObjCMethodDecl *setter, SourceLocation l, ObjCInterfaceDecl *C, SourceLocation CL) : Expr(ObjCKVCRefExprClass, t), Setter(setter), Getter(getter), Loc(l), Base(0), ClassProp(C), ClassLoc(CL) { } ObjCMethodDecl *getGetterMethod() const { return Getter; } ObjCMethodDecl *getSetterMethod() const { return Setter; } ObjCInterfaceDecl *getClassProp() const { return ClassProp; } virtual SourceRange getSourceRange() const { if (Base) return SourceRange(getBase()->getLocStart(), Loc); return SourceRange(ClassLoc, Loc); } const Expr *getBase() const { return cast<Expr>(Base); } Expr *getBase() { return cast<Expr>(Base); } void setBase(Expr * base) { Base = base; } SourceLocation getLocation() const { return Loc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCKVCRefExprClass; } static bool classof(const ObjCKVCRefExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCKVCRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; class ObjCMessageExpr : public Expr { // SubExprs - The receiver and arguments of the message expression. Stmt **SubExprs; // NumArgs - The number of arguments (not including the receiver) to the // message expression. unsigned NumArgs; // A unigue name for this message. Selector SelName; // A method prototype for this message (optional). // FIXME: Since method decls contain the selector, and most messages have a // prototype, consider devising a scheme for unifying SelName/MethodProto. ObjCMethodDecl *MethodProto; SourceLocation LBracloc, RBracloc; // Constants for indexing into SubExprs. enum { RECEIVER=0, ARGS_START=1 }; // Bit-swizziling flags. enum { IsInstMeth=0, IsClsMethDeclUnknown, IsClsMethDeclKnown, Flags=0x3 }; unsigned getFlag() const { return (uintptr_t) SubExprs[RECEIVER] & Flags; } // constructor used during deserialization ObjCMessageExpr(Selector selInfo, QualType retType, SourceLocation LBrac, SourceLocation RBrac, Stmt **subexprs, unsigned nargs) : Expr(ObjCMessageExprClass, retType), SubExprs(subexprs), NumArgs(nargs), SelName(selInfo), MethodProto(NULL), LBracloc(LBrac), RBracloc(RBrac) {} public: /// This constructor is used to represent class messages where the /// ObjCInterfaceDecl* of the receiver is not known. ObjCMessageExpr(IdentifierInfo *clsName, Selector selInfo, QualType retType, ObjCMethodDecl *methDecl, SourceLocation LBrac, SourceLocation RBrac, Expr **ArgExprs, unsigned NumArgs); /// This constructor is used to represent class messages where the /// ObjCInterfaceDecl* of the receiver is known. // FIXME: clsName should be typed to ObjCInterfaceType ObjCMessageExpr(ObjCInterfaceDecl *cls, Selector selInfo, QualType retType, ObjCMethodDecl *methDecl, SourceLocation LBrac, SourceLocation RBrac, Expr **ArgExprs, unsigned NumArgs); // constructor for instance messages. ObjCMessageExpr(Expr *receiver, Selector selInfo, QualType retType, ObjCMethodDecl *methDecl, SourceLocation LBrac, SourceLocation RBrac, Expr **ArgExprs, unsigned NumArgs); ~ObjCMessageExpr() { delete [] SubExprs; } /// getReceiver - Returns the receiver of the message expression. /// This can be NULL if the message is for class methods. For /// class methods, use getClassName. /// FIXME: need to handle/detect 'super' usage within a class method. Expr *getReceiver() { uintptr_t x = (uintptr_t) SubExprs[RECEIVER]; return (x & Flags) == IsInstMeth ? (Expr*) x : 0; } const Expr *getReceiver() const { return const_cast<ObjCMessageExpr*>(this)->getReceiver(); } Selector getSelector() const { return SelName; } const ObjCMethodDecl *getMethodDecl() const { return MethodProto; } ObjCMethodDecl *getMethodDecl() { return MethodProto; } typedef std::pair<ObjCInterfaceDecl*, IdentifierInfo*> ClassInfo; /// getClassInfo - For class methods, this returns both the ObjCInterfaceDecl* /// and IdentifierInfo* of the invoked class. Both can be NULL if this /// is an instance message, and the ObjCInterfaceDecl* can be NULL if none /// was available when this ObjCMessageExpr object was constructed. ClassInfo getClassInfo() const; /// getClassName - For class methods, this returns the invoked class, /// and returns NULL otherwise. For instance methods, use getReceiver. IdentifierInfo *getClassName() const { return getClassInfo().second; } /// getNumArgs - Return the number of actual arguments to this call. unsigned getNumArgs() const { return NumArgs; } /// getArg - Return the specified argument. Expr *getArg(unsigned Arg) { assert(Arg < NumArgs && "Arg access out of range!"); return cast<Expr>(SubExprs[Arg+ARGS_START]); } const Expr *getArg(unsigned Arg) const { assert(Arg < NumArgs && "Arg access out of range!"); return cast<Expr>(SubExprs[Arg+ARGS_START]); } /// setArg - Set the specified argument. void setArg(unsigned Arg, Expr *ArgExpr) { assert(Arg < NumArgs && "Arg access out of range!"); SubExprs[Arg+ARGS_START] = ArgExpr; } virtual SourceRange getSourceRange() const { return SourceRange(LBracloc, RBracloc); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCMessageExprClass; } static bool classof(const ObjCMessageExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); typedef ExprIterator arg_iterator; typedef ConstExprIterator const_arg_iterator; arg_iterator arg_begin() { return &SubExprs[ARGS_START]; } arg_iterator arg_end() { return &SubExprs[ARGS_START] + NumArgs; } const_arg_iterator arg_begin() const { return &SubExprs[ARGS_START]; } const_arg_iterator arg_end() const { return &SubExprs[ARGS_START] + NumArgs; } // Serialization. virtual void EmitImpl(llvm::Serializer& S) const; static ObjCMessageExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCSuperExpr - Represents the "super" expression in Objective-C, /// which refers to the object on which the current method is executing. class ObjCSuperExpr : public Expr { SourceLocation Loc; public: ObjCSuperExpr(SourceLocation L, QualType Type) : Expr(ObjCSuperExprClass, Type), Loc(L) { } virtual SourceRange getSourceRange() const { return SourceRange(Loc); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCSuperExprClass; } static bool classof(const ObjCSuperExpr *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCSuperExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; } // end namespace clang #endif <file_sep>/include/clang/AST/Stmt.h //===--- Stmt.h - Classes for representing statements -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Stmt interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMT_H #define LLVM_CLANG_AST_STMT_H #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include "clang/Basic/SourceLocation.h" #include "clang/AST/StmtIterator.h" #include "clang/AST/DeclGroup.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/iterator.h" #include "llvm/Bitcode/SerializationFwd.h" #include "clang/AST/ASTContext.h" #include <string> using llvm::dyn_cast_or_null; namespace clang { class ASTContext; class Expr; class Decl; class ParmVarDecl; class QualType; class IdentifierInfo; class SourceManager; class StringLiteral; class SwitchStmt; class PrinterHelper; //===----------------------------------------------------------------------===// // ExprIterator - Iterators for iterating over Stmt* arrays that contain // only Expr*. This is needed because AST nodes use Stmt* arrays to store // references to children (to be compatible with StmtIterator). //===----------------------------------------------------------------------===// class Stmt; class Expr; class ExprIterator { Stmt** I; public: ExprIterator(Stmt** i) : I(i) {} ExprIterator() : I(0) {} ExprIterator& operator++() { ++I; return *this; } ExprIterator operator-(size_t i) { return I-i; } ExprIterator operator+(size_t i) { return I+i; } Expr* operator[](size_t idx); // FIXME: Verify that this will correctly return a signed distance. signed operator-(const ExprIterator& R) const { return I - R.I; } Expr* operator*() const; Expr* operator->() const; bool operator==(const ExprIterator& R) const { return I == R.I; } bool operator!=(const ExprIterator& R) const { return I != R.I; } bool operator>(const ExprIterator& R) const { return I > R.I; } bool operator>=(const ExprIterator& R) const { return I >= R.I; } }; class ConstExprIterator { Stmt* const * I; public: ConstExprIterator(Stmt* const* i) : I(i) {} ConstExprIterator() : I(0) {} ConstExprIterator& operator++() { ++I; return *this; } ConstExprIterator operator+(size_t i) { return I+i; } ConstExprIterator operator-(size_t i) { return I-i; } const Expr * operator[](size_t idx) const; signed operator-(const ConstExprIterator& R) const { return I - R.I; } const Expr * operator*() const; const Expr * operator->() const; bool operator==(const ConstExprIterator& R) const { return I == R.I; } bool operator!=(const ConstExprIterator& R) const { return I != R.I; } bool operator>(const ConstExprIterator& R) const { return I > R.I; } bool operator>=(const ConstExprIterator& R) const { return I >= R.I; } }; //===----------------------------------------------------------------------===// // AST classes for statements. //===----------------------------------------------------------------------===// /// Stmt - This represents one statement. /// class Stmt { public: enum StmtClass { NoStmtClass = 0, #define STMT(CLASS, PARENT) CLASS##Class, #define FIRST_STMT(CLASS) firstStmtConstant = CLASS##Class, #define LAST_STMT(CLASS) lastStmtConstant = CLASS##Class, #define FIRST_EXPR(CLASS) firstExprConstant = CLASS##Class, #define LAST_EXPR(CLASS) lastExprConstant = CLASS##Class #include "clang/AST/StmtNodes.def" }; private: const StmtClass sClass; // Make vanilla 'new' and 'delete' illegal for Stmts. protected: void* operator new(size_t bytes) throw() { assert(0 && "Stmts cannot be allocated with regular 'new'."); return 0; } void operator delete(void* data) throw() { assert(0 && "Stmts cannot be released with regular 'delete'."); } public: // Only allow allocation of Stmts using the allocator in ASTContext // or by doing a placement new. void* operator new(size_t bytes, ASTContext& C, unsigned alignment = 16) throw() { return ::operator new(bytes, C, alignment); } void* operator new(size_t bytes, ASTContext* C, unsigned alignment = 16) throw() { return ::operator new(bytes, *C, alignment); } void* operator new(size_t bytes, void* mem) throw() { return mem; } void operator delete(void*, ASTContext&, unsigned) throw() { } void operator delete(void*, ASTContext*, unsigned) throw() { } void operator delete(void*, std::size_t) throw() { } void operator delete(void*, void*) throw() { } protected: /// DestroyChildren - Invoked by destructors of subclasses of Stmt to /// recursively release child AST nodes. void DestroyChildren(ASTContext& Ctx); public: Stmt(StmtClass SC) : sClass(SC) { if (Stmt::CollectingStats()) Stmt::addStmtClass(SC); } virtual ~Stmt() {} virtual void Destroy(ASTContext &Ctx); StmtClass getStmtClass() const { return sClass; } const char *getStmtClassName() const; /// SourceLocation tokens are not useful in isolation - they are low level /// value objects created/interpreted by SourceManager. We assume AST /// clients will have a pointer to the respective SourceManager. virtual SourceRange getSourceRange() const = 0; SourceLocation getLocStart() const { return getSourceRange().getBegin(); } SourceLocation getLocEnd() const { return getSourceRange().getEnd(); } // global temp stats (until we have a per-module visitor) static void addStmtClass(const StmtClass s); static bool CollectingStats(bool enable=false); static void PrintStats(); /// dump - This does a local dump of the specified AST fragment. It dumps the /// specified node and a few nodes underneath it, but not the whole subtree. /// This is useful in a debugger. void dump() const; void dump(SourceManager &SM) const; /// dumpAll - This does a dump of the specified AST fragment and all subtrees. void dumpAll() const; void dumpAll(SourceManager &SM) const; /// dumpPretty/printPretty - These two methods do a "pretty print" of the AST /// back to its original source language syntax. void dumpPretty() const; void printPretty(llvm::raw_ostream &OS, PrinterHelper* = NULL, unsigned = 0, bool NoIndent=false) const; /// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only /// works on systems with GraphViz (Mac OS X) or dot+gv installed. void viewAST() const; // Implement isa<T> support. static bool classof(const Stmt *) { return true; } /// hasImplicitControlFlow - Some statements (e.g. short circuited operations) /// contain implicit control-flow in the order their subexpressions /// are evaluated. This predicate returns true if this statement has /// such implicit control-flow. Such statements are also specially handled /// within CFGs. bool hasImplicitControlFlow() const; /// Child Iterators: All subclasses must implement child_begin and child_end /// to permit easy iteration over the substatements/subexpessions of an /// AST node. This permits easy iteration over all nodes in the AST. typedef StmtIterator child_iterator; typedef ConstStmtIterator const_child_iterator; virtual child_iterator child_begin() = 0; virtual child_iterator child_end() = 0; const_child_iterator child_begin() const { return const_child_iterator(const_cast<Stmt*>(this)->child_begin()); } const_child_iterator child_end() const { return const_child_iterator(const_cast<Stmt*>(this)->child_end()); } /// \brief A placeholder type used to construct an empty shell of a /// type, that will be filled in later (e.g., by some /// de-serialization). struct EmptyShell { }; void Emit(llvm::Serializer& S) const; static Stmt* Create(llvm::Deserializer& D, ASTContext& C); virtual void EmitImpl(llvm::Serializer& S) const { // This method will eventually be a pure-virtual function. assert (false && "Not implemented."); } }; /// DeclStmt - Adaptor class for mixing declarations with statements and /// expressions. For example, CompoundStmt mixes statements, expressions /// and declarations (variables, types). Another example is ForStmt, where /// the first statement can be an expression or a declaration. /// class DeclStmt : public Stmt { DeclGroupRef DG; SourceLocation StartLoc, EndLoc; public: DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc) : Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {} virtual void Destroy(ASTContext& Ctx); /// isSingleDecl - This method returns true if this DeclStmt refers /// to a single Decl. bool isSingleDecl() const { return DG.isSingleDecl(); } const Decl *getSingleDecl() const { return DG.getSingleDecl(); } Decl *getSingleDecl() { return DG.getSingleDecl(); } const DeclGroupRef getDeclGroup() const { return DG; } DeclGroupRef getDeclGroup() { return DG; } SourceLocation getStartLoc() const { return StartLoc; } SourceLocation getEndLoc() const { return EndLoc; } SourceRange getSourceRange() const { return SourceRange(StartLoc, EndLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == DeclStmtClass; } static bool classof(const DeclStmt *) { return true; } // Iterators over subexpressions. virtual child_iterator child_begin(); virtual child_iterator child_end(); typedef DeclGroupRef::iterator decl_iterator; typedef DeclGroupRef::const_iterator const_decl_iterator; decl_iterator decl_begin() { return DG.begin(); } decl_iterator decl_end() { return DG.end(); } const_decl_iterator decl_begin() const { return DG.begin(); } const_decl_iterator decl_end() const { return DG.end(); } // Serialization. virtual void EmitImpl(llvm::Serializer& S) const; static DeclStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// NullStmt - This is the null statement ";": C99 6.8.3p3. /// class NullStmt : public Stmt { SourceLocation SemiLoc; public: NullStmt(SourceLocation L) : Stmt(NullStmtClass), SemiLoc(L) {} SourceLocation getSemiLoc() const { return SemiLoc; } virtual SourceRange getSourceRange() const { return SourceRange(SemiLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == NullStmtClass; } static bool classof(const NullStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static NullStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// CompoundStmt - This represents a group of statements like { stmt stmt }. /// class CompoundStmt : public Stmt { Stmt** Body; unsigned NumStmts; SourceLocation LBracLoc, RBracLoc; public: CompoundStmt(ASTContext& C, Stmt **StmtStart, unsigned numStmts, SourceLocation LB, SourceLocation RB) : Stmt(CompoundStmtClass), NumStmts(numStmts), LBracLoc(LB), RBracLoc(RB) { if (NumStmts == 0) { Body = 0; return; } Body = new (C) Stmt*[NumStmts]; memcpy(Body, StmtStart, numStmts * sizeof(*Body)); } bool body_empty() const { return NumStmts == 0; } typedef Stmt** body_iterator; body_iterator body_begin() { return Body; } body_iterator body_end() { return Body + NumStmts; } Stmt *body_back() { return NumStmts ? Body[NumStmts-1] : 0; } typedef Stmt* const * const_body_iterator; const_body_iterator body_begin() const { return Body; } const_body_iterator body_end() const { return Body + NumStmts; } const Stmt *body_back() const { return NumStmts ? Body[NumStmts-1] : 0; } typedef std::reverse_iterator<body_iterator> reverse_body_iterator; reverse_body_iterator body_rbegin() { return reverse_body_iterator(body_end()); } reverse_body_iterator body_rend() { return reverse_body_iterator(body_begin()); } typedef std::reverse_iterator<const_body_iterator> const_reverse_body_iterator; const_reverse_body_iterator body_rbegin() const { return const_reverse_body_iterator(body_end()); } const_reverse_body_iterator body_rend() const { return const_reverse_body_iterator(body_begin()); } virtual SourceRange getSourceRange() const { return SourceRange(LBracLoc, RBracLoc); } SourceLocation getLBracLoc() const { return LBracLoc; } SourceLocation getRBracLoc() const { return RBracLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == CompoundStmtClass; } static bool classof(const CompoundStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static CompoundStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; // SwitchCase is the base class for CaseStmt and DefaultStmt, class SwitchCase : public Stmt { protected: // A pointer to the following CaseStmt or DefaultStmt class, // used by SwitchStmt. SwitchCase *NextSwitchCase; SwitchCase(StmtClass SC) : Stmt(SC), NextSwitchCase(0) {} public: const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; } SwitchCase *getNextSwitchCase() { return NextSwitchCase; } void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; } Stmt *getSubStmt() { return v_getSubStmt(); } virtual SourceRange getSourceRange() const { return SourceRange(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass || T->getStmtClass() == DefaultStmtClass; } static bool classof(const SwitchCase *) { return true; } protected: virtual Stmt* v_getSubStmt() = 0; }; class CaseStmt : public SwitchCase { enum { SUBSTMT, LHS, RHS, END_EXPR }; Stmt* SubExprs[END_EXPR]; // The expression for the RHS is Non-null for // GNU "case 1 ... 4" extension SourceLocation CaseLoc; virtual Stmt* v_getSubStmt() { return getSubStmt(); } public: CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc) : SwitchCase(CaseStmtClass) { SubExprs[SUBSTMT] = 0; SubExprs[LHS] = reinterpret_cast<Stmt*>(lhs); SubExprs[RHS] = reinterpret_cast<Stmt*>(rhs); CaseLoc = caseLoc; } SourceLocation getCaseLoc() const { return CaseLoc; } Expr *getLHS() { return reinterpret_cast<Expr*>(SubExprs[LHS]); } Expr *getRHS() { return reinterpret_cast<Expr*>(SubExprs[RHS]); } Stmt *getSubStmt() { return SubExprs[SUBSTMT]; } const Expr *getLHS() const { return reinterpret_cast<const Expr*>(SubExprs[LHS]); } const Expr *getRHS() const { return reinterpret_cast<const Expr*>(SubExprs[RHS]); } const Stmt *getSubStmt() const { return SubExprs[SUBSTMT]; } void setSubStmt(Stmt *S) { SubExprs[SUBSTMT] = S; } void setLHS(Expr *Val) { SubExprs[LHS] = reinterpret_cast<Stmt*>(Val); } void setRHS(Expr *Val) { SubExprs[RHS] = reinterpret_cast<Stmt*>(Val); } virtual SourceRange getSourceRange() const { // Handle deeply nested case statements with iteration instead of recursion. const CaseStmt *CS = this; while (const CaseStmt *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt())) CS = CS2; return SourceRange(CaseLoc, CS->getSubStmt()->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == CaseStmtClass; } static bool classof(const CaseStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static CaseStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; class DefaultStmt : public SwitchCase { Stmt* SubStmt; SourceLocation DefaultLoc; virtual Stmt* v_getSubStmt() { return getSubStmt(); } public: DefaultStmt(SourceLocation DL, Stmt *substmt) : SwitchCase(DefaultStmtClass), SubStmt(substmt), DefaultLoc(DL) {} Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } SourceLocation getDefaultLoc() const { return DefaultLoc; } virtual SourceRange getSourceRange() const { return SourceRange(DefaultLoc, SubStmt->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == DefaultStmtClass; } static bool classof(const DefaultStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static DefaultStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; class LabelStmt : public Stmt { IdentifierInfo *Label; Stmt *SubStmt; SourceLocation IdentLoc; public: LabelStmt(SourceLocation IL, IdentifierInfo *label, Stmt *substmt) : Stmt(LabelStmtClass), Label(label), SubStmt(substmt), IdentLoc(IL) {} SourceLocation getIdentLoc() const { return IdentLoc; } IdentifierInfo *getID() const { return Label; } const char *getName() const; Stmt *getSubStmt() { return SubStmt; } const Stmt *getSubStmt() const { return SubStmt; } void setIdentLoc(SourceLocation L) { IdentLoc = L; } void setSubStmt(Stmt *SS) { SubStmt = SS; } virtual SourceRange getSourceRange() const { return SourceRange(IdentLoc, SubStmt->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == LabelStmtClass; } static bool classof(const LabelStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static LabelStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// IfStmt - This represents an if/then/else. /// class IfStmt : public Stmt { enum { COND, THEN, ELSE, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation IfLoc; public: IfStmt(SourceLocation IL, Expr *cond, Stmt *then, Stmt *elsev = 0) : Stmt(IfStmtClass) { SubExprs[COND] = reinterpret_cast<Stmt*>(cond); SubExprs[THEN] = then; SubExprs[ELSE] = elsev; IfLoc = IL; } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Stmt *getThen() const { return SubExprs[THEN]; } const Stmt *getElse() const { return SubExprs[ELSE]; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Stmt *getThen() { return SubExprs[THEN]; } Stmt *getElse() { return SubExprs[ELSE]; } virtual SourceRange getSourceRange() const { if (SubExprs[ELSE]) return SourceRange(IfLoc, SubExprs[ELSE]->getLocEnd()); else return SourceRange(IfLoc, SubExprs[THEN]->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == IfStmtClass; } static bool classof(const IfStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static IfStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// SwitchStmt - This represents a 'switch' stmt. /// class SwitchStmt : public Stmt { enum { COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // This points to a linked list of case and default statements. SwitchCase *FirstCase; SourceLocation SwitchLoc; public: SwitchStmt(Expr *cond) : Stmt(SwitchStmtClass), FirstCase(0) { SubExprs[COND] = reinterpret_cast<Stmt*>(cond); SubExprs[BODY] = NULL; } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Stmt *getBody() const { return SubExprs[BODY]; } const SwitchCase *getSwitchCaseList() const { return FirstCase; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]);} Stmt *getBody() { return SubExprs[BODY]; } SwitchCase *getSwitchCaseList() { return FirstCase; } void setBody(Stmt *S, SourceLocation SL) { SubExprs[BODY] = S; SwitchLoc = SL; } void addSwitchCase(SwitchCase *SC) { assert(!SC->getNextSwitchCase() && "case/default already added to a switch"); SC->setNextSwitchCase(FirstCase); FirstCase = SC; } virtual SourceRange getSourceRange() const { return SourceRange(SwitchLoc, SubExprs[BODY]->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == SwitchStmtClass; } static bool classof(const SwitchStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static SwitchStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// WhileStmt - This represents a 'while' stmt. /// class WhileStmt : public Stmt { enum { COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation WhileLoc; public: WhileStmt(Expr *cond, Stmt *body, SourceLocation WL) : Stmt(WhileStmtClass) { SubExprs[COND] = reinterpret_cast<Stmt*>(cond); SubExprs[BODY] = body; WhileLoc = WL; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } virtual SourceRange getSourceRange() const { return SourceRange(WhileLoc, SubExprs[BODY]->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == WhileStmtClass; } static bool classof(const WhileStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static WhileStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// DoStmt - This represents a 'do/while' stmt. /// class DoStmt : public Stmt { enum { COND, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; SourceLocation DoLoc; public: DoStmt(Stmt *body, Expr *cond, SourceLocation DL) : Stmt(DoStmtClass), DoLoc(DL) { SubExprs[COND] = reinterpret_cast<Stmt*>(cond); SubExprs[BODY] = body; DoLoc = DL; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getBody() const { return SubExprs[BODY]; } virtual SourceRange getSourceRange() const { return SourceRange(DoLoc, SubExprs[BODY]->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == DoStmtClass; } static bool classof(const DoStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static DoStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ForStmt - This represents a 'for (init;cond;inc)' stmt. Note that any of /// the init/cond/inc parts of the ForStmt will be null if they were not /// specified in the source. /// class ForStmt : public Stmt { enum { INIT, COND, INC, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt. SourceLocation ForLoc; public: ForStmt(Stmt *Init, Expr *Cond, Expr *Inc, Stmt *Body, SourceLocation FL) : Stmt(ForStmtClass) { SubExprs[INIT] = Init; SubExprs[COND] = reinterpret_cast<Stmt*>(Cond); SubExprs[INC] = reinterpret_cast<Stmt*>(Inc); SubExprs[BODY] = Body; ForLoc = FL; } Stmt *getInit() { return SubExprs[INIT]; } Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); } Expr *getInc() { return reinterpret_cast<Expr*>(SubExprs[INC]); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getInit() const { return SubExprs[INIT]; } const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);} const Expr *getInc() const { return reinterpret_cast<Expr*>(SubExprs[INC]); } const Stmt *getBody() const { return SubExprs[BODY]; } virtual SourceRange getSourceRange() const { return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == ForStmtClass; } static bool classof(const ForStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ForStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// GotoStmt - This represents a direct goto. /// class GotoStmt : public Stmt { LabelStmt *Label; SourceLocation GotoLoc; SourceLocation LabelLoc; public: GotoStmt(LabelStmt *label, SourceLocation GL, SourceLocation LL) : Stmt(GotoStmtClass), Label(label), GotoLoc(GL), LabelLoc(LL) {} LabelStmt *getLabel() const { return Label; } virtual SourceRange getSourceRange() const { return SourceRange(GotoLoc, LabelLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == GotoStmtClass; } static bool classof(const GotoStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static GotoStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// IndirectGotoStmt - This represents an indirect goto. /// class IndirectGotoStmt : public Stmt { Stmt *Target; // FIXME: Add location information (e.g. SourceLocation objects). // When doing so, update the serialization routines. public: IndirectGotoStmt(Expr *target) : Stmt(IndirectGotoStmtClass), Target((Stmt*)target){} Expr *getTarget(); const Expr *getTarget() const; virtual SourceRange getSourceRange() const { return SourceRange(); } static bool classof(const Stmt *T) { return T->getStmtClass() == IndirectGotoStmtClass; } static bool classof(const IndirectGotoStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static IndirectGotoStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ContinueStmt - This represents a continue. /// class ContinueStmt : public Stmt { SourceLocation ContinueLoc; public: ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass), ContinueLoc(CL) {} virtual SourceRange getSourceRange() const { return SourceRange(ContinueLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == ContinueStmtClass; } static bool classof(const ContinueStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ContinueStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// BreakStmt - This represents a break. /// class BreakStmt : public Stmt { SourceLocation BreakLoc; public: BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass), BreakLoc(BL) {} virtual SourceRange getSourceRange() const { return SourceRange(BreakLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == BreakStmtClass; } static bool classof(const BreakStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static BreakStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ReturnStmt - This represents a return, optionally of an expression: /// return; /// return 4; /// /// Note that GCC allows return with no argument in a function declared to /// return a value, and it allows returning a value in functions declared to /// return void. We explicitly model this in the AST, which means you can't /// depend on the return type of the function and the presence of an argument. /// class ReturnStmt : public Stmt { Stmt *RetExpr; SourceLocation RetLoc; public: ReturnStmt(SourceLocation RL, Expr *E = 0) : Stmt(ReturnStmtClass), RetExpr((Stmt*) E), RetLoc(RL) {} const Expr *getRetValue() const; Expr *getRetValue(); virtual SourceRange getSourceRange() const; static bool classof(const Stmt *T) { return T->getStmtClass() == ReturnStmtClass; } static bool classof(const ReturnStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ReturnStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// AsmStmt - This represents a GNU inline-assembly statement extension. /// class AsmStmt : public Stmt { SourceLocation AsmLoc, RParenLoc; StringLiteral *AsmStr; bool IsSimple; bool IsVolatile; unsigned NumOutputs; unsigned NumInputs; llvm::SmallVector<std::string, 4> Names; llvm::SmallVector<StringLiteral*, 4> Constraints; llvm::SmallVector<Stmt*, 4> Exprs; llvm::SmallVector<StringLiteral*, 4> Clobbers; public: AsmStmt(SourceLocation asmloc, bool issimple, bool isvolatile, unsigned numoutputs, unsigned numinputs, std::string *names, StringLiteral **constraints, Expr **exprs, StringLiteral *asmstr, unsigned numclobbers, StringLiteral **clobbers, SourceLocation rparenloc); bool isVolatile() const { return IsVolatile; } bool isSimple() const { return IsSimple; } //===--- Asm String Analysis ---===// const StringLiteral *getAsmString() const { return AsmStr; } StringLiteral *getAsmString() { return AsmStr; } /// AsmStringPiece - this is part of a decomposed asm string specification /// (for use with the AnalyzeAsmString function below). An asm string is /// considered to be a concatenation of these parts. class AsmStringPiece { public: enum Kind { String, // String in .ll asm string form, "$" -> "$$" and "%%" -> "%". Operand // Operand reference, with optional modifier %c4. }; private: Kind MyKind; std::string Str; unsigned OperandNo; public: AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {} AsmStringPiece(unsigned OpNo, char Modifier) : MyKind(Operand), Str(), OperandNo(OpNo) { Str += Modifier; } bool isString() const { return MyKind == String; } bool isOperand() const { return MyKind == Operand; } const std::string &getString() const { assert(isString()); return Str; } unsigned getOperandNo() const { assert(isOperand()); return OperandNo; } /// getModifier - Get the modifier for this operand, if present. This /// returns '\0' if there was no modifier. char getModifier() const { assert(isOperand()); return Str[0]; } }; /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing /// it into pieces. If the asm string is erroneous, emit errors and return /// true, otherwise return false. This handles canonicalization and /// translation of strings from GCC syntax to LLVM IR syntax, and handles //// flattening of named references like %[foo] to Operand AsmStringPiece's. unsigned AnalyzeAsmString(llvm::SmallVectorImpl<AsmStringPiece> &Pieces, ASTContext &C, unsigned &DiagOffs) const; //===--- Output operands ---===// unsigned getNumOutputs() const { return NumOutputs; } const std::string &getOutputName(unsigned i) const { return Names[i]; } /// getOutputConstraint - Return the constraint string for the specified /// output operand. All output constraints are known to be non-empty (either /// '=' or '+'). std::string getOutputConstraint(unsigned i) const; const StringLiteral *getOutputConstraintLiteral(unsigned i) const { return Constraints[i]; } StringLiteral *getOutputConstraintLiteral(unsigned i) { return Constraints[i]; } Expr *getOutputExpr(unsigned i); const Expr *getOutputExpr(unsigned i) const { return const_cast<AsmStmt*>(this)->getOutputExpr(i); } /// isOutputPlusConstraint - Return true if the specified output constraint /// is a "+" constraint (which is both an input and an output) or false if it /// is an "=" constraint (just an output). bool isOutputPlusConstraint(unsigned i) const { return getOutputConstraint(i)[0] == '+'; } /// getNumPlusOperands - Return the number of output operands that have a "+" /// constraint. unsigned getNumPlusOperands() const; //===--- Input operands ---===// unsigned getNumInputs() const { return NumInputs; } const std::string &getInputName(unsigned i) const { return Names[i + NumOutputs]; } /// getInputConstraint - Return the specified input constraint. Unlike output /// constraints, these can be empty. std::string getInputConstraint(unsigned i) const; const StringLiteral *getInputConstraintLiteral(unsigned i) const { return Constraints[i + NumOutputs]; } StringLiteral *getInputConstraintLiteral(unsigned i) { return Constraints[i + NumOutputs]; } Expr *getInputExpr(unsigned i); const Expr *getInputExpr(unsigned i) const { return const_cast<AsmStmt*>(this)->getInputExpr(i); } //===--- Other ---===// /// getNamedOperand - Given a symbolic operand reference like %[foo], /// translate this into a numeric value needed to reference the same operand. /// This returns -1 if the operand name is invalid. int getNamedOperand(const std::string &SymbolicName) const; unsigned getNumClobbers() const { return Clobbers.size(); } StringLiteral *getClobber(unsigned i) { return Clobbers[i]; } const StringLiteral *getClobber(unsigned i) const { return Clobbers[i]; } virtual SourceRange getSourceRange() const { return SourceRange(AsmLoc, RParenLoc); } static bool classof(const Stmt *T) {return T->getStmtClass() == AsmStmtClass;} static bool classof(const AsmStmt *) { return true; } // Input expr iterators. typedef ExprIterator inputs_iterator; typedef ConstExprIterator const_inputs_iterator; inputs_iterator begin_inputs() { return &Exprs[0] + NumOutputs; } inputs_iterator end_inputs() { return &Exprs[0] + NumOutputs + NumInputs; } const_inputs_iterator begin_inputs() const { return &Exprs[0] + NumOutputs; } const_inputs_iterator end_inputs() const { return &Exprs[0] + NumOutputs + NumInputs;} // Output expr iterators. typedef ExprIterator outputs_iterator; typedef ConstExprIterator const_outputs_iterator; outputs_iterator begin_outputs() { return &Exprs[0]; } outputs_iterator end_outputs() { return &Exprs[0] + NumOutputs; } const_outputs_iterator begin_outputs() const { return &Exprs[0]; } const_outputs_iterator end_outputs() const { return &Exprs[0] + NumOutputs; } // Input name iterator. const std::string *begin_output_names() const { return &Names[0]; } const std::string *end_output_names() const { return &Names[0] + NumOutputs; } // Child iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static AsmStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCForCollectionStmt - This represents Objective-c's collection statement; /// represented as 'for (element 'in' collection-expression)' stmt. /// class ObjCForCollectionStmt : public Stmt { enum { ELEM, COLLECTION, BODY, END_EXPR }; Stmt* SubExprs[END_EXPR]; // SubExprs[ELEM] is an expression or declstmt. SourceLocation ForLoc; SourceLocation RParenLoc; public: ObjCForCollectionStmt(Stmt *Elem, Expr *Collect, Stmt *Body, SourceLocation FCL, SourceLocation RPL); Stmt *getElement() { return SubExprs[ELEM]; } Expr *getCollection() { return reinterpret_cast<Expr*>(SubExprs[COLLECTION]); } Stmt *getBody() { return SubExprs[BODY]; } const Stmt *getElement() const { return SubExprs[ELEM]; } const Expr *getCollection() const { return reinterpret_cast<Expr*>(SubExprs[COLLECTION]); } const Stmt *getBody() const { return SubExprs[BODY]; } SourceLocation getRParenLoc() const { return RParenLoc; } virtual SourceRange getSourceRange() const { return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCForCollectionStmtClass; } static bool classof(const ObjCForCollectionStmt *) { return true; } // Iterators virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCForCollectionStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCAtCatchStmt - This represents objective-c's @catch statement. class ObjCAtCatchStmt : public Stmt { private: enum { BODY, NEXT_CATCH, END_EXPR }; ParmVarDecl *ExceptionDecl; Stmt *SubExprs[END_EXPR]; SourceLocation AtCatchLoc, RParenLoc; // Used by deserialization. ObjCAtCatchStmt(SourceLocation atCatchLoc, SourceLocation rparenloc) : Stmt(ObjCAtCatchStmtClass), AtCatchLoc(atCatchLoc), RParenLoc(rparenloc) {} public: ObjCAtCatchStmt(SourceLocation atCatchLoc, SourceLocation rparenloc, ParmVarDecl *catchVarDecl, Stmt *atCatchStmt, Stmt *atCatchList); const Stmt *getCatchBody() const { return SubExprs[BODY]; } Stmt *getCatchBody() { return SubExprs[BODY]; } const ObjCAtCatchStmt *getNextCatchStmt() const { return static_cast<const ObjCAtCatchStmt*>(SubExprs[NEXT_CATCH]); } ObjCAtCatchStmt *getNextCatchStmt() { return static_cast<ObjCAtCatchStmt*>(SubExprs[NEXT_CATCH]); } const ParmVarDecl *getCatchParamDecl() const { return ExceptionDecl; } ParmVarDecl *getCatchParamDecl() { return ExceptionDecl; } SourceLocation getRParenLoc() const { return RParenLoc; } virtual SourceRange getSourceRange() const { return SourceRange(AtCatchLoc, SubExprs[BODY]->getLocEnd()); } bool hasEllipsis() const { return getCatchParamDecl() == 0; } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtCatchStmtClass; } static bool classof(const ObjCAtCatchStmt *) { return true; } virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCAtCatchStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCAtFinallyStmt - This represent objective-c's @finally Statement class ObjCAtFinallyStmt : public Stmt { Stmt *AtFinallyStmt; SourceLocation AtFinallyLoc; public: ObjCAtFinallyStmt(SourceLocation atFinallyLoc, Stmt *atFinallyStmt) : Stmt(ObjCAtFinallyStmtClass), AtFinallyStmt(atFinallyStmt), AtFinallyLoc(atFinallyLoc) {} const Stmt *getFinallyBody () const { return AtFinallyStmt; } Stmt *getFinallyBody () { return AtFinallyStmt; } virtual SourceRange getSourceRange() const { return SourceRange(AtFinallyLoc, AtFinallyStmt->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtFinallyStmtClass; } static bool classof(const ObjCAtFinallyStmt *) { return true; } virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCAtFinallyStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCAtTryStmt - This represent objective-c's over-all /// @try ... @catch ... @finally statement. class ObjCAtTryStmt : public Stmt { private: enum { TRY, CATCH, FINALLY, END_EXPR }; Stmt* SubStmts[END_EXPR]; SourceLocation AtTryLoc; public: ObjCAtTryStmt(SourceLocation atTryLoc, Stmt *atTryStmt, Stmt *atCatchStmt, Stmt *atFinallyStmt) : Stmt(ObjCAtTryStmtClass) { SubStmts[TRY] = atTryStmt; SubStmts[CATCH] = atCatchStmt; SubStmts[FINALLY] = atFinallyStmt; AtTryLoc = atTryLoc; } const Stmt *getTryBody() const { return SubStmts[TRY]; } Stmt *getTryBody() { return SubStmts[TRY]; } const ObjCAtCatchStmt *getCatchStmts() const { return dyn_cast_or_null<ObjCAtCatchStmt>(SubStmts[CATCH]); } ObjCAtCatchStmt *getCatchStmts() { return dyn_cast_or_null<ObjCAtCatchStmt>(SubStmts[CATCH]); } const ObjCAtFinallyStmt *getFinallyStmt() const { return dyn_cast_or_null<ObjCAtFinallyStmt>(SubStmts[FINALLY]); } ObjCAtFinallyStmt *getFinallyStmt() { return dyn_cast_or_null<ObjCAtFinallyStmt>(SubStmts[FINALLY]); } virtual SourceRange getSourceRange() const { return SourceRange(AtTryLoc, SubStmts[TRY]->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtTryStmtClass; } static bool classof(const ObjCAtTryStmt *) { return true; } virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCAtTryStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCAtSynchronizedStmt - This is for objective-c's @synchronized statement. /// Example: @synchronized (sem) { /// do-something; /// } /// class ObjCAtSynchronizedStmt : public Stmt { private: enum { SYNC_EXPR, SYNC_BODY, END_EXPR }; Stmt* SubStmts[END_EXPR]; SourceLocation AtSynchronizedLoc; public: ObjCAtSynchronizedStmt(SourceLocation atSynchronizedLoc, Stmt *synchExpr, Stmt *synchBody) : Stmt(ObjCAtSynchronizedStmtClass) { SubStmts[SYNC_EXPR] = synchExpr; SubStmts[SYNC_BODY] = synchBody; AtSynchronizedLoc = atSynchronizedLoc; } const CompoundStmt *getSynchBody() const { return reinterpret_cast<CompoundStmt*>(SubStmts[SYNC_BODY]); } CompoundStmt *getSynchBody() { return reinterpret_cast<CompoundStmt*>(SubStmts[SYNC_BODY]); } const Expr *getSynchExpr() const { return reinterpret_cast<Expr*>(SubStmts[SYNC_EXPR]); } Expr *getSynchExpr() { return reinterpret_cast<Expr*>(SubStmts[SYNC_EXPR]); } virtual SourceRange getSourceRange() const { return SourceRange(AtSynchronizedLoc, getSynchBody()->getLocEnd()); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtSynchronizedStmtClass; } static bool classof(const ObjCAtSynchronizedStmt *) { return true; } virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCAtSynchronizedStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// ObjCAtThrowStmt - This represents objective-c's @throw statement. class ObjCAtThrowStmt : public Stmt { Stmt *Throw; SourceLocation AtThrowLoc; public: ObjCAtThrowStmt(SourceLocation atThrowLoc, Stmt *throwExpr) : Stmt(ObjCAtThrowStmtClass), Throw(throwExpr) { AtThrowLoc = atThrowLoc; } const Expr *getThrowExpr() const { return reinterpret_cast<Expr*>(Throw); } Expr *getThrowExpr() { return reinterpret_cast<Expr*>(Throw); } virtual SourceRange getSourceRange() const { if (Throw) return SourceRange(AtThrowLoc, Throw->getLocEnd()); else return SourceRange(AtThrowLoc); } static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCAtThrowStmtClass; } static bool classof(const ObjCAtThrowStmt *) { return true; } virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static ObjCAtThrowStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// CXXCatchStmt - This represents a C++ catch block. class CXXCatchStmt : public Stmt { SourceLocation CatchLoc; /// The exception-declaration of the type. Decl *ExceptionDecl; /// The handler block. Stmt *HandlerBlock; public: CXXCatchStmt(SourceLocation catchLoc, Decl *exDecl, Stmt *handlerBlock) : Stmt(CXXCatchStmtClass), CatchLoc(catchLoc), ExceptionDecl(exDecl), HandlerBlock(handlerBlock) {} virtual void Destroy(ASTContext& Ctx); virtual SourceRange getSourceRange() const { return SourceRange(CatchLoc, HandlerBlock->getLocEnd()); } Decl *getExceptionDecl() { return ExceptionDecl; } QualType getCaughtType(); Stmt *getHandlerBlock() { return HandlerBlock; } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXCatchStmtClass; } static bool classof(const CXXCatchStmt *) { return true; } virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static CXXCatchStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// CXXTryStmt - A C++ try block, including all handlers. class CXXTryStmt : public Stmt { SourceLocation TryLoc; // First place is the guarded CompoundStatement. Subsequent are the handlers. // More than three handlers should be rare. llvm::SmallVector<Stmt*, 4> Stmts; public: CXXTryStmt(SourceLocation tryLoc, Stmt *tryBlock, Stmt **handlers, unsigned numHandlers); virtual SourceRange getSourceRange() const { return SourceRange(TryLoc, Stmts.back()->getLocEnd()); } CompoundStmt *getTryBlock() { return llvm::cast<CompoundStmt>(Stmts[0]); } const CompoundStmt *getTryBlock() const { return llvm::cast<CompoundStmt>(Stmts[0]); } unsigned getNumHandlers() const { return Stmts.size() - 1; } CXXCatchStmt *getHandler(unsigned i) { return llvm::cast<CXXCatchStmt>(Stmts[i + 1]); } const CXXCatchStmt *getHandler(unsigned i) const { return llvm::cast<CXXCatchStmt>(Stmts[i + 1]); } static bool classof(const Stmt *T) { return T->getStmtClass() == CXXTryStmtClass; } static bool classof(const CXXTryStmt *) { return true; } virtual child_iterator child_begin(); virtual child_iterator child_end(); virtual void EmitImpl(llvm::Serializer& S) const; static CXXTryStmt* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; } // end namespace clang #endif <file_sep>/lib/Sema/SemaInit.cpp //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for initializers. The main entry // point is Sema::CheckInitList(), but all of the work is performed // within the InitListChecker class. // // This file also implements Sema::CheckInitializerTypes. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/Parse/Designator.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ExprObjC.h" #include <map> using namespace clang; //===----------------------------------------------------------------------===// // Sema Initialization Checking //===----------------------------------------------------------------------===// static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) { const ArrayType *AT = Context.getAsArrayType(DeclType); if (!AT) return 0; // See if this is a string literal or @encode. Init = Init->IgnoreParens(); // Handle @encode, which is a narrow string. if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) return Init; // Otherwise we can only handle string literals. StringLiteral *SL = dyn_cast<StringLiteral>(Init); if (SL == 0) return 0; // char array can be initialized with a narrow string. // Only allow char x[] = "foo"; not char x[] = L"foo"; if (!SL->isWide()) return AT->getElementType()->isCharType() ? Init : 0; // wchar_t array can be initialized with a wide string: C99 6.7.8p15: // "An array with element type compatible with wchar_t may be initialized by a // wide string literal, optionally enclosed in braces." if (Context.typesAreCompatible(Context.getWCharType(), AT->getElementType())) // Only allow wchar_t x[] = L"foo"; not wchar_t x[] = "foo"; return Init; return 0; } static bool CheckSingleInitializer(Expr *&Init, QualType DeclType, bool DirectInit, Sema &S) { // Get the type before calling CheckSingleAssignmentConstraints(), since // it can promote the expression. QualType InitType = Init->getType(); if (S.getLangOptions().CPlusPlus) { // FIXME: I dislike this error message. A lot. if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit)) return S.Diag(Init->getSourceRange().getBegin(), diag::err_typecheck_convert_incompatible) << DeclType << Init->getType() << "initializing" << Init->getSourceRange(); return false; } Sema::AssignConvertType ConvTy = S.CheckSingleAssignmentConstraints(DeclType, Init); return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, InitType, Init, "initializing"); } static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) { // Get the length of the string as parsed. uint64_t StrLength = cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); const ArrayType *AT = S.Context.getAsArrayType(DeclT); if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { // C99 6.7.8p14. We have an array of character type with unknown size // being initialized to a string literal. llvm::APSInt ConstVal(32); ConstVal = StrLength; // Return a new array type (C99 6.7.8p22). DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal, ArrayType::Normal, 0); return; } const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); // C99 6.7.8p14. We have an array of character type with known size. However, // the size may be smaller or larger than the string we are initializing. // FIXME: Avoid truncation for 64-bit length strings. if (StrLength-1 > CAT->getSize().getZExtValue()) S.Diag(Str->getSourceRange().getBegin(), diag::warn_initializer_string_for_char_array_too_long) << Str->getSourceRange(); // Set the type to the actual size that we are initializing. If we have // something like: // char x[1] = "foo"; // then this will set the string literal's type to char[1]. Str->setType(DeclT); } bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType, SourceLocation InitLoc, DeclarationName InitEntity, bool DirectInit) { if (DeclType->isDependentType() || Init->isTypeDependent()) return false; // C++ [dcl.init.ref]p1: // A variable declared to be a T& or T&&, that is "reference to type T" // (8.3.2), shall be initialized by an object, or function, of // type T or by an object that can be converted into a T. if (DeclType->isReferenceType()) return CheckReferenceInit(Init, DeclType, 0, false, DirectInit); // C99 6.7.8p3: The type of the entity to be initialized shall be an array // of unknown size ("[]") or an object type that is not a variable array type. if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) return Diag(InitLoc, diag::err_variable_object_no_init) << VAT->getSizeExpr()->getSourceRange(); InitListExpr *InitList = dyn_cast<InitListExpr>(Init); if (!InitList) { // FIXME: Handle wide strings if (Expr *Str = IsStringInit(Init, DeclType, Context)) { CheckStringInit(Str, DeclType, *this); return false; } // C++ [dcl.init]p14: // -- If the destination type is a (possibly cv-qualified) class // type: if (getLangOptions().CPlusPlus && DeclType->isRecordType()) { QualType DeclTypeC = Context.getCanonicalType(DeclType); QualType InitTypeC = Context.getCanonicalType(Init->getType()); // -- If the initialization is direct-initialization, or if it is // copy-initialization where the cv-unqualified version of the // source type is the same class as, or a derived class of, the // class of the destination, constructors are considered. if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) || IsDerivedFrom(InitTypeC, DeclTypeC)) { CXXConstructorDecl *Constructor = PerformInitializationByConstructor(DeclType, &Init, 1, InitLoc, Init->getSourceRange(), InitEntity, DirectInit? IK_Direct : IK_Copy); return Constructor == 0; } // -- Otherwise (i.e., for the remaining copy-initialization // cases), user-defined conversion sequences that can // convert from the source type to the destination type or // (when a conversion function is used) to a derived class // thereof are enumerated as described in 13.3.1.4, and the // best one is chosen through overload resolution // (13.3). If the conversion cannot be done or is // ambiguous, the initialization is ill-formed. The // function selected is called with the initializer // expression as its argument; if the function is a // constructor, the call initializes a temporary of the // destination type. // FIXME: We're pretending to do copy elision here; return to // this when we have ASTs for such things. if (!PerformImplicitConversion(Init, DeclType, "initializing")) return false; if (InitEntity) return Diag(InitLoc, diag::err_cannot_initialize_decl) << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid) << Init->getType() << Init->getSourceRange(); else return Diag(InitLoc, diag::err_cannot_initialize_decl_noname) << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid) << Init->getType() << Init->getSourceRange(); } // C99 6.7.8p16. if (DeclType->isArrayType()) return Diag(Init->getLocStart(), diag::err_array_init_list_required) << Init->getSourceRange(); return CheckSingleInitializer(Init, DeclType, DirectInit, *this); } bool hadError = CheckInitList(InitList, DeclType); Init = InitList; return hadError; } //===----------------------------------------------------------------------===// // Semantic checking for initializer lists. //===----------------------------------------------------------------------===// /// @brief Semantic checking for initializer lists. /// /// The InitListChecker class contains a set of routines that each /// handle the initialization of a certain kind of entity, e.g., /// arrays, vectors, struct/union types, scalars, etc. The /// InitListChecker itself performs a recursive walk of the subobject /// structure of the type to be initialized, while stepping through /// the initializer list one element at a time. The IList and Index /// parameters to each of the Check* routines contain the active /// (syntactic) initializer list and the index into that initializer /// list that represents the current initializer. Each routine is /// responsible for moving that Index forward as it consumes elements. /// /// Each Check* routine also has a StructuredList/StructuredIndex /// arguments, which contains the current the "structured" (semantic) /// initializer list and the index into that initializer list where we /// are copying initializers as we map them over to the semantic /// list. Once we have completed our recursive walk of the subobject /// structure, we will have constructed a full semantic initializer /// list. /// /// C99 designators cause changes in the initializer list traversal, /// because they make the initialization "jump" into a specific /// subobject and then continue the initialization from that /// point. CheckDesignatedInitializer() recursively steps into the /// designated subobject and manages backing out the recursion to /// initialize the subobjects after the one designated. namespace { class InitListChecker { Sema &SemaRef; bool hadError; std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic; InitListExpr *FullyStructuredList; void CheckImplicitInitList(InitListExpr *ParentIList, QualType T, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject = false); void CheckExplicitInitList(InitListExpr *IList, QualType &T, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject = false); void CheckListElementTypes(InitListExpr *IList, QualType &DeclType, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject = false); void CheckSubElementType(InitListExpr *IList, QualType ElemType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckScalarType(InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckReferenceType(InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType, RecordDecl::field_iterator Field, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject = false); void CheckArrayType(InitListExpr *IList, QualType &DeclType, llvm::APSInt elementIndex, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE, unsigned DesigIdx, QualType &CurrentObjectType, RecordDecl::field_iterator *NextField, llvm::APSInt *NextElementIndex, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool FinishSubobjectInit, bool TopLevelObject); InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, QualType CurrentObjectType, InitListExpr *StructuredList, unsigned StructuredIndex, SourceRange InitRange); void UpdateStructuredListElement(InitListExpr *StructuredList, unsigned &StructuredIndex, Expr *expr); int numArrayElements(QualType DeclType); int numStructUnionElements(QualType DeclType); void FillInValueInitializations(InitListExpr *ILE); public: InitListChecker(Sema &S, InitListExpr *IL, QualType &T); bool HadError() { return hadError; } // @brief Retrieves the fully-structured initializer list used for // semantic analysis and code generation. InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } }; } // end anonymous namespace /// Recursively replaces NULL values within the given initializer list /// with expressions that perform value-initialization of the /// appropriate type. void InitListChecker::FillInValueInitializations(InitListExpr *ILE) { assert((ILE->getType() != SemaRef.Context.VoidTy) && "Should not have void type"); SourceLocation Loc = ILE->getSourceRange().getBegin(); if (ILE->getSyntacticForm()) Loc = ILE->getSyntacticForm()->getSourceRange().getBegin(); if (const RecordType *RType = ILE->getType()->getAsRecordType()) { unsigned Init = 0, NumInits = ILE->getNumInits(); for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(SemaRef.Context), FieldEnd = RType->getDecl()->field_end(SemaRef.Context); Field != FieldEnd; ++Field) { if (Field->isUnnamedBitfield()) continue; if (Init >= NumInits || !ILE->getInit(Init)) { if (Field->getType()->isReferenceType()) { // C++ [dcl.init.aggr]p9: // If an incomplete or empty initializer-list leaves a // member of reference type uninitialized, the program is // ill-formed. SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) << Field->getType() << ILE->getSyntacticForm()->getSourceRange(); SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member); hadError = true; return; } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) { hadError = true; return; } // FIXME: If value-initialization involves calling a // constructor, should we make that call explicit in the // representation (even when it means extending the // initializer list)? if (Init < NumInits && !hadError) ILE->setInit(Init, new (SemaRef.Context) ImplicitValueInitExpr(Field->getType())); } else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init))) FillInValueInitializations(InnerILE); ++Init; // Only look at the first initialization of a union. if (RType->getDecl()->isUnion()) break; } return; } QualType ElementType; unsigned NumInits = ILE->getNumInits(); unsigned NumElements = NumInits; if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { ElementType = AType->getElementType(); if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) NumElements = CAType->getSize().getZExtValue(); } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) { ElementType = VType->getElementType(); NumElements = VType->getNumElements(); } else ElementType = ILE->getType(); for (unsigned Init = 0; Init != NumElements; ++Init) { if (Init >= NumInits || !ILE->getInit(Init)) { if (SemaRef.CheckValueInitialization(ElementType, Loc)) { hadError = true; return; } // FIXME: If value-initialization involves calling a // constructor, should we make that call explicit in the // representation (even when it means extending the // initializer list)? if (Init < NumInits && !hadError) ILE->setInit(Init, new (SemaRef.Context) ImplicitValueInitExpr(ElementType)); } else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init))) FillInValueInitializations(InnerILE); } } InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T) : SemaRef(S) { hadError = false; unsigned newIndex = 0; unsigned newStructuredIndex = 0; FullyStructuredList = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex, /*TopLevelObject=*/true); if (!hadError) FillInValueInitializations(FullyStructuredList); } int InitListChecker::numArrayElements(QualType DeclType) { // FIXME: use a proper constant int maxElements = 0x7FFFFFFF; if (const ConstantArrayType *CAT = SemaRef.Context.getAsConstantArrayType(DeclType)) { maxElements = static_cast<int>(CAT->getSize().getZExtValue()); } return maxElements; } int InitListChecker::numStructUnionElements(QualType DeclType) { RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl(); int InitializableMembers = 0; for (RecordDecl::field_iterator Field = structDecl->field_begin(SemaRef.Context), FieldEnd = structDecl->field_end(SemaRef.Context); Field != FieldEnd; ++Field) { if ((*Field)->getIdentifier() || !(*Field)->isBitField()) ++InitializableMembers; } if (structDecl->isUnion()) return std::min(InitializableMembers, 1); return InitializableMembers - structDecl->hasFlexibleArrayMember(); } void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList, QualType T, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject) { int maxElements = 0; if (T->isArrayType()) maxElements = numArrayElements(T); else if (T->isStructureType() || T->isUnionType()) maxElements = numStructUnionElements(T); else if (T->isVectorType()) maxElements = T->getAsVectorType()->getNumElements(); else assert(0 && "CheckImplicitInitList(): Illegal type"); if (maxElements == 0) { SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), diag::err_implicit_empty_initializer); ++Index; hadError = true; return; } // Build a structured initializer list corresponding to this subobject. InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, StructuredIndex, SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(), ParentIList->getSourceRange().getEnd())); unsigned StructuredSubobjectInitIndex = 0; // Check the element types and build the structural subobject. unsigned StartIndex = Index; CheckListElementTypes(ParentIList, T, false, Index, StructuredSubobjectInitList, StructuredSubobjectInitIndex, TopLevelObject); unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); StructuredSubobjectInitList->setType(T); // Update the structured sub-object initializer so that it's ending // range corresponds with the end of the last initializer it used. if (EndIndex < ParentIList->getNumInits()) { SourceLocation EndLoc = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); StructuredSubobjectInitList->setRBraceLoc(EndLoc); } } void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject) { assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); SyntacticToSemantic[IList] = StructuredList; StructuredList->setSyntacticForm(IList); CheckListElementTypes(IList, T, true, Index, StructuredList, StructuredIndex, TopLevelObject); IList->setType(T); StructuredList->setType(T); if (hadError) return; if (Index < IList->getNumInits()) { // We have leftover initializers if (IList->getNumInits() > 0 && IsStringInit(IList->getInit(Index), T, SemaRef.Context)) { unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; if (SemaRef.getLangOptions().CPlusPlus) DK = diag::err_excess_initializers_in_char_array_initializer; // Special-case SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) << IList->getInit(Index)->getSourceRange(); hadError = true; } else if (!T->isIncompleteType()) { // Don't complain for incomplete types, since we'll get an error // elsewhere QualType CurrentObjectType = StructuredList->getType(); int initKind = CurrentObjectType->isArrayType()? 0 : CurrentObjectType->isVectorType()? 1 : CurrentObjectType->isScalarType()? 2 : CurrentObjectType->isUnionType()? 3 : 4; unsigned DK = diag::warn_excess_initializers; if (SemaRef.getLangOptions().CPlusPlus) DK = diag::err_excess_initializers; SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) << initKind << IList->getInit(Index)->getSourceRange(); } } if (T->isScalarType()) SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) << IList->getSourceRange() << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart())) << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd())); } void InitListChecker::CheckListElementTypes(InitListExpr *IList, QualType &DeclType, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject) { if (DeclType->isScalarType()) { CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex); } else if (DeclType->isVectorType()) { CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex); } else if (DeclType->isAggregateType()) { if (DeclType->isRecordType()) { RecordDecl *RD = DeclType->getAsRecordType()->getDecl(); CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context), SubobjectIsDesignatorContext, Index, StructuredList, StructuredIndex, TopLevelObject); } else if (DeclType->isArrayType()) { llvm::APSInt Zero( SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), false); CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index, StructuredList, StructuredIndex); } else assert(0 && "Aggregate that isn't a structure or array?!"); } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { // This type is invalid, issue a diagnostic. ++Index; SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) << DeclType; hadError = true; } else if (DeclType->isRecordType()) { // C++ [dcl.init]p14: // [...] If the class is an aggregate (8.5.1), and the initializer // is a brace-enclosed list, see 8.5.1. // // Note: 8.5.1 is handled below; here, we diagnose the case where // we have an initializer list and a destination type that is not // an aggregate. // FIXME: In C++0x, this is yet another form of initialization. SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) << DeclType << IList->getSourceRange(); hadError = true; } else if (DeclType->isReferenceType()) { CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex); } else { // In C, all types are either scalars or aggregates, but // additional handling is needed here for C++ (and possibly others?). assert(0 && "Unsupported initializer type"); } } void InitListChecker::CheckSubElementType(InitListExpr *IList, QualType ElemType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { Expr *expr = IList->getInit(Index); if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { unsigned newIndex = 0; unsigned newStructuredIndex = 0; InitListExpr *newStructuredList = getStructuredSubobjectInit(IList, Index, ElemType, StructuredList, StructuredIndex, SubInitList->getSourceRange()); CheckExplicitInitList(SubInitList, ElemType, newIndex, newStructuredList, newStructuredIndex); ++StructuredIndex; ++Index; } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) { CheckStringInit(Str, ElemType, SemaRef); UpdateStructuredListElement(StructuredList, StructuredIndex, Str); ++Index; } else if (ElemType->isScalarType()) { CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex); } else if (ElemType->isReferenceType()) { CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex); } else { if (SemaRef.getLangOptions().CPlusPlus) { // C++ [dcl.init.aggr]p12: // All implicit type conversions (clause 4) are considered when // initializing the aggregate member with an ini- tializer from // an initializer-list. If the initializer can initialize a // member, the member is initialized. [...] ImplicitConversionSequence ICS = SemaRef.TryCopyInitialization(expr, ElemType); if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) { if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS, "initializing")) hadError = true; UpdateStructuredListElement(StructuredList, StructuredIndex, expr); ++Index; return; } // Fall through for subaggregate initialization } else { // C99 6.7.8p13: // // The initializer for a structure or union object that has // automatic storage duration shall be either an initializer // list as described below, or a single expression that has // compatible structure or union type. In the latter case, the // initial value of the object, including unnamed members, is // that of the expression. QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType()); QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType); if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(), ElemTypeCanon.getUnqualifiedType())) { UpdateStructuredListElement(StructuredList, StructuredIndex, expr); ++Index; return; } // Fall through for subaggregate initialization } // C++ [dcl.init.aggr]p12: // // [...] Otherwise, if the member is itself a non-empty // subaggregate, brace elision is assumed and the initializer is // considered for the initialization of the first member of // the subaggregate. if (ElemType->isAggregateType() || ElemType->isVectorType()) { CheckImplicitInitList(IList, ElemType, Index, StructuredList, StructuredIndex); ++StructuredIndex; } else { // We cannot initialize this element, so let // PerformCopyInitialization produce the appropriate diagnostic. SemaRef.PerformCopyInitialization(expr, ElemType, "initializing"); hadError = true; ++Index; ++StructuredIndex; } } } void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { if (Index < IList->getNumInits()) { Expr *expr = IList->getInit(Index); if (isa<InitListExpr>(expr)) { SemaRef.Diag(IList->getLocStart(), diag::err_many_braces_around_scalar_init) << IList->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } else if (isa<DesignatedInitExpr>(expr)) { SemaRef.Diag(expr->getSourceRange().getBegin(), diag::err_designator_for_scalar_init) << DeclType << expr->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. if (CheckSingleInitializer(expr, DeclType, false, SemaRef)) hadError = true; // types weren't compatible. else if (savExpr != expr) { // The type was promoted, update initializer list. IList->setInit(Index, expr); } if (hadError) ++StructuredIndex; else UpdateStructuredListElement(StructuredList, StructuredIndex, expr); ++Index; } else { SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer) << IList->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } } void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { if (Index < IList->getNumInits()) { Expr *expr = IList->getInit(Index); if (isa<InitListExpr>(expr)) { SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) << DeclType << IList->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. if (SemaRef.CheckReferenceInit(expr, DeclType)) hadError = true; else if (savExpr != expr) { // The type was promoted, update initializer list. IList->setInit(Index, expr); } if (hadError) ++StructuredIndex; else UpdateStructuredListElement(StructuredList, StructuredIndex, expr); ++Index; } else { // FIXME: It would be wonderful if we could point at the actual // member. In general, it would be useful to pass location // information down the stack, so that we know the location (or // decl) of the "current object" being initialized. SemaRef.Diag(IList->getLocStart(), diag::err_init_reference_member_uninitialized) << DeclType << IList->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } } void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { if (Index < IList->getNumInits()) { const VectorType *VT = DeclType->getAsVectorType(); int maxElements = VT->getNumElements(); QualType elementType = VT->getElementType(); for (int i = 0; i < maxElements; ++i) { // Don't attempt to go past the end of the init list if (Index >= IList->getNumInits()) break; CheckSubElementType(IList, elementType, Index, StructuredList, StructuredIndex); } } } void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType, llvm::APSInt elementIndex, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { // Check for the special-case of initializing an array with a string. if (Index < IList->getNumInits()) { if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType, SemaRef.Context)) { CheckStringInit(Str, DeclType, SemaRef); // We place the string literal directly into the resulting // initializer list. This is the only place where the structure // of the structured initializer list doesn't match exactly, // because doing so would involve allocating one character // constant for each string. UpdateStructuredListElement(StructuredList, StructuredIndex, Str); StructuredList->resizeInits(SemaRef.Context, StructuredIndex); ++Index; return; } } if (const VariableArrayType *VAT = SemaRef.Context.getAsVariableArrayType(DeclType)) { // Check for VLAs; in standard C it would be possible to check this // earlier, but I don't know where clang accepts VLAs (gcc accepts // them in all sorts of strange places). SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), diag::err_variable_object_no_init) << VAT->getSizeExpr()->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } // We might know the maximum number of elements in advance. llvm::APSInt maxElements(elementIndex.getBitWidth(), elementIndex.isUnsigned()); bool maxElementsKnown = false; if (const ConstantArrayType *CAT = SemaRef.Context.getAsConstantArrayType(DeclType)) { maxElements = CAT->getSize(); elementIndex.extOrTrunc(maxElements.getBitWidth()); elementIndex.setIsUnsigned(maxElements.isUnsigned()); maxElementsKnown = true; } QualType elementType = SemaRef.Context.getAsArrayType(DeclType) ->getElementType(); while (Index < IList->getNumInits()) { Expr *Init = IList->getInit(Index); if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { // If we're not the subobject that matches up with the '{' for // the designator, we shouldn't be handling the // designator. Return immediately. if (!SubobjectIsDesignatorContext) return; // Handle this designated initializer. elementIndex will be // updated to be the next array element we'll initialize. if (CheckDesignatedInitializer(IList, DIE, 0, DeclType, 0, &elementIndex, Index, StructuredList, StructuredIndex, true, false)) { hadError = true; continue; } if (elementIndex.getBitWidth() > maxElements.getBitWidth()) maxElements.extend(elementIndex.getBitWidth()); else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) elementIndex.extend(maxElements.getBitWidth()); elementIndex.setIsUnsigned(maxElements.isUnsigned()); // If the array is of incomplete type, keep track of the number of // elements in the initializer. if (!maxElementsKnown && elementIndex > maxElements) maxElements = elementIndex; continue; } // If we know the maximum number of elements, and we've already // hit it, stop consuming elements in the initializer list. if (maxElementsKnown && elementIndex == maxElements) break; // Check this element. CheckSubElementType(IList, elementType, Index, StructuredList, StructuredIndex); ++elementIndex; // If the array is of incomplete type, keep track of the number of // elements in the initializer. if (!maxElementsKnown && elementIndex > maxElements) maxElements = elementIndex; } if (DeclType->isIncompleteArrayType()) { // If this is an incomplete array type, the actual type needs to // be calculated here. llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); if (maxElements == Zero) { // Sizing an array implicitly to zero is not allowed by ISO C, // but is supported by GNU. SemaRef.Diag(IList->getLocStart(), diag::ext_typecheck_zero_array_size); } DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, ArrayType::Normal, 0); } } void InitListChecker::CheckStructUnionTypes(InitListExpr *IList, QualType DeclType, RecordDecl::field_iterator Field, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject) { RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl(); // If the record is invalid, some of it's members are invalid. To avoid // confusion, we forgo checking the intializer for the entire record. if (structDecl->isInvalidDecl()) { hadError = true; return; } if (DeclType->isUnionType() && IList->getNumInits() == 0) { // Value-initialize the first named member of the union. RecordDecl *RD = DeclType->getAsRecordType()->getDecl(); for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context); Field != FieldEnd; ++Field) { if (Field->getDeclName()) { StructuredList->setInitializedFieldInUnion(*Field); break; } } return; } // If structDecl is a forward declaration, this loop won't do // anything except look at designated initializers; That's okay, // because an error should get printed out elsewhere. It might be // worthwhile to skip over the rest of the initializer, though. RecordDecl *RD = DeclType->getAsRecordType()->getDecl(); RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context); bool InitializedSomething = false; while (Index < IList->getNumInits()) { Expr *Init = IList->getInit(Index); if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { // If we're not the subobject that matches up with the '{' for // the designator, we shouldn't be handling the // designator. Return immediately. if (!SubobjectIsDesignatorContext) return; // Handle this designated initializer. Field will be updated to // the next field that we'll be initializing. if (CheckDesignatedInitializer(IList, DIE, 0, DeclType, &Field, 0, Index, StructuredList, StructuredIndex, true, TopLevelObject)) hadError = true; InitializedSomething = true; continue; } if (Field == FieldEnd) { // We've run out of fields. We're done. break; } // We've already initialized a member of a union. We're done. if (InitializedSomething && DeclType->isUnionType()) break; // If we've hit the flexible array member at the end, we're done. if (Field->getType()->isIncompleteArrayType()) break; if (Field->isUnnamedBitfield()) { // Don't initialize unnamed bitfields, e.g. "int : 20;" ++Field; continue; } CheckSubElementType(IList, Field->getType(), Index, StructuredList, StructuredIndex); InitializedSomething = true; if (DeclType->isUnionType()) { // Initialize the first field within the union. StructuredList->setInitializedFieldInUnion(*Field); } ++Field; } if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || Index >= IList->getNumInits()) return; // Handle GNU flexible array initializers. if (!TopLevelObject && (!isa<InitListExpr>(IList->getInit(Index)) || cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) { SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), diag::err_flexible_array_init_nonempty) << IList->getInit(Index)->getSourceRange().getBegin(); SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) << *Field; hadError = true; ++Index; return; } else { SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), diag::ext_flexible_array_init) << IList->getInit(Index)->getSourceRange().getBegin(); SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) << *Field; } if (isa<InitListExpr>(IList->getInit(Index))) CheckSubElementType(IList, Field->getType(), Index, StructuredList, StructuredIndex); else CheckImplicitInitList(IList, Field->getType(), Index, StructuredList, StructuredIndex); } /// \brief Expand a field designator that refers to a member of an /// anonymous struct or union into a series of field designators that /// refers to the field within the appropriate subobject. /// /// Field/FieldIndex will be updated to point to the (new) /// currently-designated field. static void ExpandAnonymousFieldDesignator(Sema &SemaRef, DesignatedInitExpr *DIE, unsigned DesigIdx, FieldDecl *Field, RecordDecl::field_iterator &FieldIter, unsigned &FieldIndex) { typedef DesignatedInitExpr::Designator Designator; // Build the path from the current object to the member of the // anonymous struct/union (backwards). llvm::SmallVector<FieldDecl *, 4> Path; SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path); // Build the replacement designators. llvm::SmallVector<Designator, 4> Replacements; for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator FI = Path.rbegin(), FIEnd = Path.rend(); FI != FIEnd; ++FI) { if (FI + 1 == FIEnd) Replacements.push_back(Designator((IdentifierInfo *)0, DIE->getDesignator(DesigIdx)->getDotLoc(), DIE->getDesignator(DesigIdx)->getFieldLoc())); else Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), SourceLocation())); Replacements.back().setField(*FI); } // Expand the current designator into the set of replacement // designators, so we have a full subobject path down to where the // member of the anonymous struct/union is actually stored. DIE->ExpandDesignator(DesigIdx, &Replacements[0], &Replacements[0] + Replacements.size()); // Update FieldIter/FieldIndex; RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext()); FieldIter = Record->field_begin(SemaRef.Context); FieldIndex = 0; for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context); FieldIter != FEnd; ++FieldIter) { if (FieldIter->isUnnamedBitfield()) continue; if (*FieldIter == Path.back()) return; ++FieldIndex; } assert(false && "Unable to find anonymous struct/union field"); } /// @brief Check the well-formedness of a C99 designated initializer. /// /// Determines whether the designated initializer @p DIE, which /// resides at the given @p Index within the initializer list @p /// IList, is well-formed for a current object of type @p DeclType /// (C99 6.7.8). The actual subobject that this designator refers to /// within the current subobject is returned in either /// @p NextField or @p NextElementIndex (whichever is appropriate). /// /// @param IList The initializer list in which this designated /// initializer occurs. /// /// @param DIE The designated initializer expression. /// /// @param DesigIdx The index of the current designator. /// /// @param DeclType The type of the "current object" (C99 6.7.8p17), /// into which the designation in @p DIE should refer. /// /// @param NextField If non-NULL and the first designator in @p DIE is /// a field, this will be set to the field declaration corresponding /// to the field named by the designator. /// /// @param NextElementIndex If non-NULL and the first designator in @p /// DIE is an array designator or GNU array-range designator, this /// will be set to the last index initialized by this designator. /// /// @param Index Index into @p IList where the designated initializer /// @p DIE occurs. /// /// @param StructuredList The initializer list expression that /// describes all of the subobject initializers in the order they'll /// actually be initialized. /// /// @returns true if there was an error, false otherwise. bool InitListChecker::CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE, unsigned DesigIdx, QualType &CurrentObjectType, RecordDecl::field_iterator *NextField, llvm::APSInt *NextElementIndex, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool FinishSubobjectInit, bool TopLevelObject) { if (DesigIdx == DIE->size()) { // Check the actual initialization for the designated object type. bool prevHadError = hadError; // Temporarily remove the designator expression from the // initializer list that the child calls see, so that we don't try // to re-process the designator. unsigned OldIndex = Index; IList->setInit(OldIndex, DIE->getInit()); CheckSubElementType(IList, CurrentObjectType, Index, StructuredList, StructuredIndex); // Restore the designated initializer expression in the syntactic // form of the initializer list. if (IList->getInit(OldIndex) != DIE->getInit()) DIE->setInit(IList->getInit(OldIndex)); IList->setInit(OldIndex, DIE); return hadError && !prevHadError; } bool IsFirstDesignator = (DesigIdx == 0); assert((IsFirstDesignator || StructuredList) && "Need a non-designated initializer list to start from"); DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); // Determine the structural initializer list that corresponds to the // current subobject. StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList, StructuredIndex, SourceRange(D->getStartLocation(), DIE->getSourceRange().getEnd())); assert(StructuredList && "Expected a structured initializer list"); if (D->isFieldDesignator()) { // C99 6.7.8p7: // // If a designator has the form // // . identifier // // then the current object (defined below) shall have // structure or union type and the identifier shall be the // name of a member of that type. const RecordType *RT = CurrentObjectType->getAsRecordType(); if (!RT) { SourceLocation Loc = D->getDotLoc(); if (Loc.isInvalid()) Loc = D->getFieldLoc(); SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; ++Index; return true; } // Note: we perform a linear search of the fields here, despite // the fact that we have a faster lookup method, because we always // need to compute the field's index. FieldDecl *KnownField = D->getField(); IdentifierInfo *FieldName = D->getFieldName(); unsigned FieldIndex = 0; RecordDecl::field_iterator Field = RT->getDecl()->field_begin(SemaRef.Context), FieldEnd = RT->getDecl()->field_end(SemaRef.Context); for (; Field != FieldEnd; ++Field) { if (Field->isUnnamedBitfield()) continue; if (KnownField == *Field || Field->getIdentifier() == FieldName) break; ++FieldIndex; } if (Field == FieldEnd) { // There was no normal field in the struct with the designated // name. Perform another lookup for this name, which may find // something that we can't designate (e.g., a member function), // may find nothing, or may find a member of an anonymous // struct/union. DeclContext::lookup_result Lookup = RT->getDecl()->lookup(SemaRef.Context, FieldName); if (Lookup.first == Lookup.second) { // Name lookup didn't find anything. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) << FieldName << CurrentObjectType; ++Index; return true; } else if (!KnownField && isa<FieldDecl>(*Lookup.first) && cast<RecordDecl>((*Lookup.first)->getDeclContext()) ->isAnonymousStructOrUnion()) { // Handle an field designator that refers to a member of an // anonymous struct or union. ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, cast<FieldDecl>(*Lookup.first), Field, FieldIndex); } else { // Name lookup found something, but it wasn't a field. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) << FieldName; SemaRef.Diag((*Lookup.first)->getLocation(), diag::note_field_designator_found); ++Index; return true; } } else if (!KnownField && cast<RecordDecl>((*Field)->getDeclContext()) ->isAnonymousStructOrUnion()) { ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field, Field, FieldIndex); D = DIE->getDesignator(DesigIdx); } // All of the fields of a union are located at the same place in // the initializer list. if (RT->getDecl()->isUnion()) { FieldIndex = 0; StructuredList->setInitializedFieldInUnion(*Field); } // Update the designator with the field declaration. D->setField(*Field); // Make sure that our non-designated initializer list has space // for a subobject corresponding to this field. if (FieldIndex >= StructuredList->getNumInits()) StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); // This designator names a flexible array member. if (Field->getType()->isIncompleteArrayType()) { bool Invalid = false; if ((DesigIdx + 1) != DIE->size()) { // We can't designate an object within the flexible array // member (because GCC doesn't allow it). DesignatedInitExpr::Designator *NextD = DIE->getDesignator(DesigIdx + 1); SemaRef.Diag(NextD->getStartLocation(), diag::err_designator_into_flexible_array_member) << SourceRange(NextD->getStartLocation(), DIE->getSourceRange().getEnd()); SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) << *Field; Invalid = true; } if (!hadError && !isa<InitListExpr>(DIE->getInit())) { // The initializer is not an initializer list. SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), diag::err_flexible_array_init_needs_braces) << DIE->getInit()->getSourceRange(); SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) << *Field; Invalid = true; } // Handle GNU flexible array initializers. if (!Invalid && !TopLevelObject && cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) { SemaRef.Diag(DIE->getSourceRange().getBegin(), diag::err_flexible_array_init_nonempty) << DIE->getSourceRange().getBegin(); SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) << *Field; Invalid = true; } if (Invalid) { ++Index; return true; } // Initialize the array. bool prevHadError = hadError; unsigned newStructuredIndex = FieldIndex; unsigned OldIndex = Index; IList->setInit(Index, DIE->getInit()); CheckSubElementType(IList, Field->getType(), Index, StructuredList, newStructuredIndex); IList->setInit(OldIndex, DIE); if (hadError && !prevHadError) { ++Field; ++FieldIndex; if (NextField) *NextField = Field; StructuredIndex = FieldIndex; return true; } } else { // Recurse to check later designated subobjects. QualType FieldType = (*Field)->getType(); unsigned newStructuredIndex = FieldIndex; if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0, Index, StructuredList, newStructuredIndex, true, false)) return true; } // Find the position of the next field to be initialized in this // subobject. ++Field; ++FieldIndex; // If this the first designator, our caller will continue checking // the rest of this struct/class/union subobject. if (IsFirstDesignator) { if (NextField) *NextField = Field; StructuredIndex = FieldIndex; return false; } if (!FinishSubobjectInit) return false; // We've already initialized something in the union; we're done. if (RT->getDecl()->isUnion()) return hadError; // Check the remaining fields within this class/struct/union subobject. bool prevHadError = hadError; CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index, StructuredList, FieldIndex); return hadError && !prevHadError; } // C99 6.7.8p6: // // If a designator has the form // // [ constant-expression ] // // then the current object (defined below) shall have array // type and the expression shall be an integer constant // expression. If the array is of unknown size, any // nonnegative value is valid. // // Additionally, cope with the GNU extension that permits // designators of the form // // [ constant-expression ... constant-expression ] const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); if (!AT) { SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) << CurrentObjectType; ++Index; return true; } Expr *IndexExpr = 0; llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; if (D->isArrayDesignator()) { IndexExpr = DIE->getArrayIndex(*D); bool ConstExpr = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef.Context); assert(ConstExpr && "Expression must be constant"); (void)ConstExpr; DesignatedEndIndex = DesignatedStartIndex; } else { assert(D->isArrayRangeDesignator() && "Need array-range designator"); bool StartConstExpr = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex, SemaRef.Context); assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr; bool EndConstExpr = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex, SemaRef.Context); assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr; IndexExpr = DIE->getArrayRangeEnd(*D); if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue()) FullyStructuredList->sawArrayRangeDesignator(); } if (isa<ConstantArrayType>(AT)) { llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); if (DesignatedEndIndex >= MaxElements) { SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), diag::err_array_designator_too_large) << DesignatedEndIndex.toString(10) << MaxElements.toString(10) << IndexExpr->getSourceRange(); ++Index; return true; } } else { // Make sure the bit-widths and signedness match. if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth()) DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); DesignatedStartIndex.setIsUnsigned(true); DesignatedEndIndex.setIsUnsigned(true); } // Make sure that our non-designated initializer list has space // for a subobject corresponding to this array element. if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) StructuredList->resizeInits(SemaRef.Context, DesignatedEndIndex.getZExtValue() + 1); // Repeatedly perform subobject initializations in the range // [DesignatedStartIndex, DesignatedEndIndex]. // Move to the next designator unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); unsigned OldIndex = Index; while (DesignatedStartIndex <= DesignatedEndIndex) { // Recurse to check later designated subobjects. QualType ElementType = AT->getElementType(); Index = OldIndex; if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0, Index, StructuredList, ElementIndex, (DesignatedStartIndex == DesignatedEndIndex), false)) return true; // Move to the next index in the array that we'll be initializing. ++DesignatedStartIndex; ElementIndex = DesignatedStartIndex.getZExtValue(); } // If this the first designator, our caller will continue checking // the rest of this array subobject. if (IsFirstDesignator) { if (NextElementIndex) *NextElementIndex = DesignatedStartIndex; StructuredIndex = ElementIndex; return false; } if (!FinishSubobjectInit) return false; // Check the remaining elements within this array subobject. bool prevHadError = hadError; CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index, StructuredList, ElementIndex); return hadError && !prevHadError; } // Get the structured initializer list for a subobject of type // @p CurrentObjectType. InitListExpr * InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, QualType CurrentObjectType, InitListExpr *StructuredList, unsigned StructuredIndex, SourceRange InitRange) { Expr *ExistingInit = 0; if (!StructuredList) ExistingInit = SyntacticToSemantic[IList]; else if (StructuredIndex < StructuredList->getNumInits()) ExistingInit = StructuredList->getInit(StructuredIndex); if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) return Result; if (ExistingInit) { // We are creating an initializer list that initializes the // subobjects of the current object, but there was already an // initialization that completely initialized the current // subobject, e.g., by a compound literal: // // struct X { int a, b; }; // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; // // Here, xs[0].a == 0 and xs[0].b == 3, since the second, // designated initializer re-initializes the whole // subobject [0], overwriting previous initializers. SemaRef.Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides) << InitRange; SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), diag::note_previous_initializer) << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange(); } InitListExpr *Result = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0, InitRange.getEnd()); Result->setType(CurrentObjectType); // Pre-allocate storage for the structured initializer list. unsigned NumElements = 0; unsigned NumInits = 0; if (!StructuredList) NumInits = IList->getNumInits(); else if (Index < IList->getNumInits()) { if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) NumInits = SubList->getNumInits(); } if (const ArrayType *AType = SemaRef.Context.getAsArrayType(CurrentObjectType)) { if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { NumElements = CAType->getSize().getZExtValue(); // Simple heuristic so that we don't allocate a very large // initializer with many empty entries at the end. if (NumInits && NumElements > NumInits) NumElements = 0; } } else if (const VectorType *VType = CurrentObjectType->getAsVectorType()) NumElements = VType->getNumElements(); else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) { RecordDecl *RDecl = RType->getDecl(); if (RDecl->isUnion()) NumElements = 1; else NumElements = std::distance(RDecl->field_begin(SemaRef.Context), RDecl->field_end(SemaRef.Context)); } if (NumElements < NumInits) NumElements = IList->getNumInits(); Result->reserveInits(NumElements); // Link this new initializer list into the structured initializer // lists. if (StructuredList) StructuredList->updateInit(StructuredIndex, Result); else { Result->setSyntacticForm(IList); SyntacticToSemantic[IList] = Result; } return Result; } /// Update the initializer at index @p StructuredIndex within the /// structured initializer list to the value @p expr. void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, unsigned &StructuredIndex, Expr *expr) { // No structured initializer list to update if (!StructuredList) return; if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) { // This initializer overwrites a previous initializer. Warn. SemaRef.Diag(expr->getSourceRange().getBegin(), diag::warn_initializer_overrides) << expr->getSourceRange(); SemaRef.Diag(PrevInit->getSourceRange().getBegin(), diag::note_previous_initializer) << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange(); } ++StructuredIndex; } /// Check that the given Index expression is a valid array designator /// value. This is essentailly just a wrapper around /// Expr::isIntegerConstantExpr that also checks for negative values /// and produces a reasonable diagnostic if there is a /// failure. Returns true if there was an error, false otherwise. If /// everything went okay, Value will receive the value of the constant /// expression. static bool CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) { SourceLocation Loc = Index->getSourceRange().getBegin(); // Make sure this is an integer constant expression. if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc)) return Self.Diag(Loc, diag::err_array_designator_nonconstant) << Index->getSourceRange(); // Make sure this constant expression is non-negative. llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()), Value.isUnsigned()); if (Value < Zero) return Self.Diag(Loc, diag::err_array_designator_negative) << Value.toString(10) << Index->getSourceRange(); Value.setIsUnsigned(true); return false; } Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, SourceLocation Loc, bool GNUSyntax, OwningExprResult Init) { typedef DesignatedInitExpr::Designator ASTDesignator; bool Invalid = false; llvm::SmallVector<ASTDesignator, 32> Designators; llvm::SmallVector<Expr *, 32> InitExpressions; // Build designators and check array designator expressions. for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { const Designator &D = Desig.getDesignator(Idx); switch (D.getKind()) { case Designator::FieldDesignator: Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), D.getFieldLoc())); break; case Designator::ArrayDesignator: { Expr *Index = static_cast<Expr *>(D.getArrayIndex()); llvm::APSInt IndexValue; if (CheckArrayDesignatorExpr(*this, Index, IndexValue)) Invalid = true; else { Designators.push_back(ASTDesignator(InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc())); InitExpressions.push_back(Index); } break; } case Designator::ArrayRangeDesignator: { Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); llvm::APSInt StartValue; llvm::APSInt EndValue; if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) || CheckArrayDesignatorExpr(*this, EndIndex, EndValue)) Invalid = true; else { // Make sure we're comparing values with the same bit width. if (StartValue.getBitWidth() > EndValue.getBitWidth()) EndValue.extend(StartValue.getBitWidth()); else if (StartValue.getBitWidth() < EndValue.getBitWidth()) StartValue.extend(EndValue.getBitWidth()); if (EndValue < StartValue) { Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) << StartValue.toString(10) << EndValue.toString(10) << StartIndex->getSourceRange() << EndIndex->getSourceRange(); Invalid = true; } else { Designators.push_back(ASTDesignator(InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(), D.getRBracketLoc())); InitExpressions.push_back(StartIndex); InitExpressions.push_back(EndIndex); } } break; } } } if (Invalid || Init.isInvalid()) return ExprError(); // Clear out the expressions within the designation. Desig.ClearExprs(*this); DesignatedInitExpr *DIE = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(), &InitExpressions[0], InitExpressions.size(), Loc, GNUSyntax, static_cast<Expr *>(Init.release())); return Owned(DIE); } bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) { InitListChecker CheckInitList(*this, InitList, DeclType); if (!CheckInitList.HadError()) InitList = CheckInitList.getFullyStructuredList(); return CheckInitList.HadError(); } /// \brief Diagnose any semantic errors with value-initialization of /// the given type. /// /// Value-initialization effectively zero-initializes any types /// without user-declared constructors, and calls the default /// constructor for a for any type that has a user-declared /// constructor (C++ [dcl.init]p5). Value-initialization can fail when /// a type with a user-declared constructor does not have an /// accessible, non-deleted default constructor. In C, everything can /// be value-initialized, which corresponds to C's notion of /// initializing objects with static storage duration when no /// initializer is provided for that object. /// /// \returns true if there was an error, false otherwise. bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) { // C++ [dcl.init]p5: // // To value-initialize an object of type T means: // -- if T is an array type, then each element is value-initialized; if (const ArrayType *AT = Context.getAsArrayType(Type)) return CheckValueInitialization(AT->getElementType(), Loc); if (const RecordType *RT = Type->getAsRecordType()) { if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { // -- if T is a class type (clause 9) with a user-declared // constructor (12.1), then the default constructor for T is // called (and the initialization is ill-formed if T has no // accessible default constructor); if (ClassDecl->hasUserDeclaredConstructor()) // FIXME: Eventually, we'll need to put the constructor decl // into the AST. return PerformInitializationByConstructor(Type, 0, 0, Loc, SourceRange(Loc), DeclarationName(), IK_Direct); } } if (Type->isReferenceType()) { // C++ [dcl.init]p5: // [...] A program that calls for default-initialization or // value-initialization of an entity of reference type is // ill-formed. [...] // FIXME: Once we have code that goes through this path, add an // actual diagnostic :) } return false; } <file_sep>/lib/CodeGen/CGCall.cpp //===----- CGCall.h - Encapsulate calling convention details ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These classes wrap the information about a call or function // definition used to handle ABI compliancy. // //===----------------------------------------------------------------------===// #include "CGCall.h" #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "clang/Basic/TargetInfo.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/RecordLayout.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Attributes.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetData.h" #include "ABIInfo.h" using namespace clang; using namespace CodeGen; /***/ // FIXME: Use iterator and sidestep silly type array creation. const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionNoProtoType *FTNP) { return getFunctionInfo(FTNP->getResultType(), llvm::SmallVector<QualType, 16>()); } const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionProtoType *FTP) { llvm::SmallVector<QualType, 16> ArgTys; // FIXME: Kill copy. for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) ArgTys.push_back(FTP->getArgType(i)); return getFunctionInfo(FTP->getResultType(), ArgTys); } const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) { llvm::SmallVector<QualType, 16> ArgTys; // Add the 'this' pointer. ArgTys.push_back(MD->getThisType(Context)); const FunctionProtoType *FTP = MD->getType()->getAsFunctionProtoType(); for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) ArgTys.push_back(FTP->getArgType(i)); return getFunctionInfo(FTP->getResultType(), ArgTys); } const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) { if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { if (MD->isInstance()) return getFunctionInfo(MD); } const FunctionType *FTy = FD->getType()->getAsFunctionType(); if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FTy)) return getFunctionInfo(FTP); return getFunctionInfo(cast<FunctionNoProtoType>(FTy)); } const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) { llvm::SmallVector<QualType, 16> ArgTys; ArgTys.push_back(MD->getSelfDecl()->getType()); ArgTys.push_back(Context.getObjCSelType()); // FIXME: Kill copy? for (ObjCMethodDecl::param_iterator i = MD->param_begin(), e = MD->param_end(); i != e; ++i) ArgTys.push_back((*i)->getType()); return getFunctionInfo(MD->getResultType(), ArgTys); } const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, const CallArgList &Args) { // FIXME: Kill copy. llvm::SmallVector<QualType, 16> ArgTys; for (CallArgList::const_iterator i = Args.begin(), e = Args.end(); i != e; ++i) ArgTys.push_back(i->second); return getFunctionInfo(ResTy, ArgTys); } const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, const FunctionArgList &Args) { // FIXME: Kill copy. llvm::SmallVector<QualType, 16> ArgTys; for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); i != e; ++i) ArgTys.push_back(i->second); return getFunctionInfo(ResTy, ArgTys); } const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy, const llvm::SmallVector<QualType, 16> &ArgTys) { // Lookup or create unique function info. llvm::FoldingSetNodeID ID; CGFunctionInfo::Profile(ID, ResTy, ArgTys.begin(), ArgTys.end()); void *InsertPos = 0; CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos); if (FI) return *FI; // Construct the function info. FI = new CGFunctionInfo(ResTy, ArgTys); FunctionInfos.InsertNode(FI, InsertPos); // Compute ABI information. getABIInfo().computeInfo(*FI, getContext()); return *FI; } /***/ ABIInfo::~ABIInfo() {} void ABIArgInfo::dump() const { fprintf(stderr, "(ABIArgInfo Kind="); switch (TheKind) { case Direct: fprintf(stderr, "Direct"); break; case Ignore: fprintf(stderr, "Ignore"); break; case Coerce: fprintf(stderr, "Coerce Type="); getCoerceToType()->print(llvm::errs()); break; case Indirect: fprintf(stderr, "Indirect Align=%d", getIndirectAlign()); break; case Expand: fprintf(stderr, "Expand"); break; } fprintf(stderr, ")\n"); } /***/ /// isEmptyRecord - Return true iff a structure has no non-empty /// members. Note that a structure with a flexible array member is not /// considered empty. static bool isEmptyRecord(ASTContext &Context, QualType T) { const RecordType *RT = T->getAsRecordType(); if (!RT) return 0; const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return false; for (RecordDecl::field_iterator i = RD->field_begin(Context), e = RD->field_end(Context); i != e; ++i) { const FieldDecl *FD = *i; if (!isEmptyRecord(Context, FD->getType())) return false; } return true; } /// isSingleElementStruct - Determine if a structure is a "single /// element struct", i.e. it has exactly one non-empty field or /// exactly one field which is itself a single element /// struct. Structures with flexible array members are never /// considered single element structs. /// /// \return The field declaration for the single non-empty field, if /// it exists. static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { const RecordType *RT = T->getAsStructureType(); if (!RT) return 0; const RecordDecl *RD = RT->getDecl(); if (RD->hasFlexibleArrayMember()) return 0; const Type *Found = 0; for (RecordDecl::field_iterator i = RD->field_begin(Context), e = RD->field_end(Context); i != e; ++i) { const FieldDecl *FD = *i; QualType FT = FD->getType(); // Treat single element arrays as the element if (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) if (AT->getSize().getZExtValue() == 1) FT = AT->getElementType(); if (isEmptyRecord(Context, FT)) { // Ignore } else if (Found) { return 0; } else if (!CodeGenFunction::hasAggregateLLVMType(FT)) { Found = FT.getTypePtr(); } else { Found = isSingleElementStruct(FT, Context); if (!Found) return 0; } } return Found; } static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { if (!Ty->getAsBuiltinType() && !Ty->isPointerType()) return false; uint64_t Size = Context.getTypeSize(Ty); return Size == 32 || Size == 64; } static bool areAllFields32Or64BitBasicType(const RecordDecl *RD, ASTContext &Context) { for (RecordDecl::field_iterator i = RD->field_begin(Context), e = RD->field_end(Context); i != e; ++i) { const FieldDecl *FD = *i; if (!is32Or64BitBasicType(FD->getType(), Context)) return false; // FIXME: Reject bitfields wholesale; there are two problems, we // don't know how to expand them yet, and the predicate for // telling if a bitfield still counts as "basic" is more // complicated than what we were doing previously. if (FD->isBitField()) return false; } return true; } namespace { /// DefaultABIInfo - The default implementation for ABI specific /// details. This implementation provides information which results in /// self-consistent and sensible LLVM IR generation, but does not /// conform to any particular ABI. class DefaultABIInfo : public ABIInfo { ABIArgInfo classifyReturnType(QualType RetTy, ASTContext &Context) const; ABIArgInfo classifyArgumentType(QualType RetTy, ASTContext &Context) const; virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const { FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context); for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) it->info = classifyArgumentType(it->type, Context); } virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const; }; /// X86_32ABIInfo - The X86-32 ABI information. class X86_32ABIInfo : public ABIInfo { ASTContext &Context; bool IsDarwin; static bool isRegisterSize(unsigned Size) { return (Size == 8 || Size == 16 || Size == 32 || Size == 64); } static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context); public: ABIArgInfo classifyReturnType(QualType RetTy, ASTContext &Context) const; ABIArgInfo classifyArgumentType(QualType RetTy, ASTContext &Context) const; virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const { FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context); for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) it->info = classifyArgumentType(it->type, Context); } virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const; X86_32ABIInfo(ASTContext &Context, bool d) : ABIInfo(), Context(Context), IsDarwin(d) {} }; } /// shouldReturnTypeInRegister - Determine if the given type should be /// passed in a register (for the Darwin ABI). bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) { uint64_t Size = Context.getTypeSize(Ty); // Type must be register sized. if (!isRegisterSize(Size)) return false; if (Ty->isVectorType()) { // 64- and 128- bit vectors inside structures are not returned in // registers. if (Size == 64 || Size == 128) return false; return true; } // If this is a builtin, pointer, or complex type, it is ok. if (Ty->getAsBuiltinType() || Ty->isPointerType() || Ty->isAnyComplexType()) return true; // Arrays are treated like records. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) return shouldReturnTypeInRegister(AT->getElementType(), Context); // Otherwise, it must be a record type. const RecordType *RT = Ty->getAsRecordType(); if (!RT) return false; // Structure types are passed in register if all fields would be // passed in a register. for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(Context), e = RT->getDecl()->field_end(Context); i != e; ++i) { const FieldDecl *FD = *i; // FIXME: Reject bitfields wholesale for now; this is incorrect. if (FD->isBitField()) return false; // Empty structures are ignored. if (isEmptyRecord(Context, FD->getType())) continue; // Check fields recursively. if (!shouldReturnTypeInRegister(FD->getType(), Context)) return false; } return true; } ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, ASTContext &Context) const { if (RetTy->isVoidType()) { return ABIArgInfo::getIgnore(); } else if (const VectorType *VT = RetTy->getAsVectorType()) { // On Darwin, some vectors are returned in registers. if (IsDarwin) { uint64_t Size = Context.getTypeSize(RetTy); // 128-bit vectors are a special case; they are returned in // registers and we need to make sure to pick a type the LLVM // backend will like. if (Size == 128) return ABIArgInfo::getCoerce(llvm::VectorType::get(llvm::Type::Int64Ty, 2)); // Always return in register if it fits in a general purpose // register, or if it is 64 bits and has a single element. if ((Size == 8 || Size == 16 || Size == 32) || (Size == 64 && VT->getNumElements() == 1)) return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size)); return ABIArgInfo::getIndirect(0); } return ABIArgInfo::getDirect(); } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { // Outside of Darwin, structs and unions are always indirect. if (!IsDarwin && !RetTy->isAnyComplexType()) return ABIArgInfo::getIndirect(0); // Classify "single element" structs as their element type. if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) { if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) { // FIXME: This is gross, it would be nice if we could just // pass back SeltTy and have clients deal with it. Is it worth // supporting coerce to both LLVM and clang Types? if (BT->isIntegerType()) { uint64_t Size = Context.getTypeSize(SeltTy); return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size)); } else if (BT->getKind() == BuiltinType::Float) { return ABIArgInfo::getCoerce(llvm::Type::FloatTy); } else if (BT->getKind() == BuiltinType::Double) { return ABIArgInfo::getCoerce(llvm::Type::DoubleTy); } } else if (SeltTy->isPointerType()) { // FIXME: It would be really nice if this could come out as // the proper pointer type. llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); return ABIArgInfo::getCoerce(PtrTy); } else if (SeltTy->isVectorType()) { // 64- and 128-bit vectors are never returned in a // register when inside a structure. uint64_t Size = Context.getTypeSize(RetTy); if (Size == 64 || Size == 128) return ABIArgInfo::getIndirect(0); return classifyReturnType(QualType(SeltTy, 0), Context); } } uint64_t Size = Context.getTypeSize(RetTy); if (isRegisterSize(Size)) { // Always return in register for unions for now. // FIXME: This is wrong, but better than treating as a // structure. if (RetTy->isUnionType()) return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size)); // Small structures which are register sized are generally returned // in a register. if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size)); } return ABIArgInfo::getIndirect(0); } else { return ABIArgInfo::getDirect(); } } ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context) const { // FIXME: Set alignment on indirect arguments. if (CodeGenFunction::hasAggregateLLVMType(Ty)) { // Structures with flexible arrays are always indirect. if (const RecordType *RT = Ty->getAsStructureType()) if (RT->getDecl()->hasFlexibleArrayMember()) return ABIArgInfo::getIndirect(0); // Ignore empty structs. uint64_t Size = Context.getTypeSize(Ty); if (Ty->isStructureType() && Size == 0) return ABIArgInfo::getIgnore(); // Expand structs with size <= 128-bits which consist only of // basic types (int, long long, float, double, xxx*). This is // non-recursive and does not ignore empty fields. if (const RecordType *RT = Ty->getAsStructureType()) { if (Context.getTypeSize(Ty) <= 4*32 && areAllFields32Or64BitBasicType(RT->getDecl(), Context)) return ABIArgInfo::getExpand(); } return ABIArgInfo::getIndirect(0); } else { return ABIArgInfo::getDirect(); } } llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const { const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); const llvm::Type *BPP = llvm::PointerType::getUnqual(BP); CGBuilderTy &Builder = CGF.Builder; llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); uint64_t Offset = llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); llvm::Value *NextAddr = Builder.CreateGEP(Addr, llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset), "ap.next"); Builder.CreateStore(NextAddr, VAListAddrAsBPP); return AddrTyped; } namespace { /// X86_64ABIInfo - The X86_64 ABI information. class X86_64ABIInfo : public ABIInfo { enum Class { Integer = 0, SSE, SSEUp, X87, X87Up, ComplexX87, NoClass, Memory }; /// merge - Implement the X86_64 ABI merging algorithm. /// /// Merge an accumulating classification \arg Accum with a field /// classification \arg Field. /// /// \param Accum - The accumulating classification. This should /// always be either NoClass or the result of a previous merge /// call. In addition, this should never be Memory (the caller /// should just return Memory for the aggregate). Class merge(Class Accum, Class Field) const; /// classify - Determine the x86_64 register classes in which the /// given type T should be passed. /// /// \param Lo - The classification for the parts of the type /// residing in the low word of the containing object. /// /// \param Hi - The classification for the parts of the type /// residing in the high word of the containing object. /// /// \param OffsetBase - The bit offset of this type in the /// containing object. Some parameters are classified different /// depending on whether they straddle an eightbyte boundary. /// /// If a word is unused its result will be NoClass; if a type should /// be passed in Memory then at least the classification of \arg Lo /// will be Memory. /// /// The \arg Lo class will be NoClass iff the argument is ignored. /// /// If the \arg Lo class is ComplexX87, then the \arg Hi class will /// also be ComplexX87. void classify(QualType T, ASTContext &Context, uint64_t OffsetBase, Class &Lo, Class &Hi) const; /// getCoerceResult - Given a source type \arg Ty and an LLVM type /// to coerce to, chose the best way to pass Ty in the same place /// that \arg CoerceTo would be passed, but while keeping the /// emitted code as simple as possible. /// /// FIXME: Note, this should be cleaned up to just take an /// enumeration of all the ways we might want to pass things, /// instead of constructing an LLVM type. This makes this code more /// explicit, and it makes it clearer that we are also doing this /// for correctness in the case of passing scalar types. ABIArgInfo getCoerceResult(QualType Ty, const llvm::Type *CoerceTo, ASTContext &Context) const; ABIArgInfo classifyReturnType(QualType RetTy, ASTContext &Context) const; ABIArgInfo classifyArgumentType(QualType Ty, ASTContext &Context, unsigned &neededInt, unsigned &neededSSE) const; public: virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const; virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const; }; } X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) const { // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is // classified recursively so that always two fields are // considered. The resulting class is calculated according to // the classes of the fields in the eightbyte: // // (a) If both classes are equal, this is the resulting class. // // (b) If one of the classes is NO_CLASS, the resulting class is // the other class. // // (c) If one of the classes is MEMORY, the result is the MEMORY // class. // // (d) If one of the classes is INTEGER, the result is the // INTEGER. // // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, // MEMORY is used as class. // // (f) Otherwise class SSE is used. // Accum should never be memory (we should have returned) or // ComplexX87 (because this cannot be passed in a structure). assert((Accum != Memory && Accum != ComplexX87) && "Invalid accumulated classification during merge."); if (Accum == Field || Field == NoClass) return Accum; else if (Field == Memory) return Memory; else if (Accum == NoClass) return Field; else if (Accum == Integer || Field == Integer) return Integer; else if (Field == X87 || Field == X87Up || Field == ComplexX87) return Memory; else return SSE; } void X86_64ABIInfo::classify(QualType Ty, ASTContext &Context, uint64_t OffsetBase, Class &Lo, Class &Hi) const { // FIXME: This code can be simplified by introducing a simple value // class for Class pairs with appropriate constructor methods for // the various situations. // FIXME: Some of the split computations are wrong; unaligned // vectors shouldn't be passed in registers for example, so there is // no chance they can straddle an eightbyte. Verify & simplify. Lo = Hi = NoClass; Class &Current = OffsetBase < 64 ? Lo : Hi; Current = Memory; if (const BuiltinType *BT = Ty->getAsBuiltinType()) { BuiltinType::Kind k = BT->getKind(); if (k == BuiltinType::Void) { Current = NoClass; } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { Current = Integer; } else if (k == BuiltinType::Float || k == BuiltinType::Double) { Current = SSE; } else if (k == BuiltinType::LongDouble) { Lo = X87; Hi = X87Up; } // FIXME: _Decimal32 and _Decimal64 are SSE. // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). // FIXME: __int128 is (Integer, Integer). } else if (const EnumType *ET = Ty->getAsEnumType()) { // Classify the underlying integer type. classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi); } else if (Ty->hasPointerRepresentation()) { Current = Integer; } else if (const VectorType *VT = Ty->getAsVectorType()) { uint64_t Size = Context.getTypeSize(VT); if (Size == 32) { // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x // float> as integer. Current = Integer; // If this type crosses an eightbyte boundary, it should be // split. uint64_t EB_Real = (OffsetBase) / 64; uint64_t EB_Imag = (OffsetBase + Size - 1) / 64; if (EB_Real != EB_Imag) Hi = Lo; } else if (Size == 64) { // gcc passes <1 x double> in memory. :( if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) return; // gcc passes <1 x long long> as INTEGER. if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong)) Current = Integer; else Current = SSE; // If this type crosses an eightbyte boundary, it should be // split. if (OffsetBase && OffsetBase != 64) Hi = Lo; } else if (Size == 128) { Lo = SSE; Hi = SSEUp; } } else if (const ComplexType *CT = Ty->getAsComplexType()) { QualType ET = Context.getCanonicalType(CT->getElementType()); uint64_t Size = Context.getTypeSize(Ty); if (ET->isIntegralType()) { if (Size <= 64) Current = Integer; else if (Size <= 128) Lo = Hi = Integer; } else if (ET == Context.FloatTy) Current = SSE; else if (ET == Context.DoubleTy) Lo = Hi = SSE; else if (ET == Context.LongDoubleTy) Current = ComplexX87; // If this complex type crosses an eightbyte boundary then it // should be split. uint64_t EB_Real = (OffsetBase) / 64; uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64; if (Hi == NoClass && EB_Real != EB_Imag) Hi = Lo; } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { // Arrays are treated like structures. uint64_t Size = Context.getTypeSize(Ty); // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger // than two eightbytes, ..., it has class MEMORY. if (Size > 128) return; // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned // fields, it has class MEMORY. // // Only need to check alignment of array base. if (OffsetBase % Context.getTypeAlign(AT->getElementType())) return; // Otherwise implement simplified merge. We could be smarter about // this, but it isn't worth it and would be harder to verify. Current = NoClass; uint64_t EltSize = Context.getTypeSize(AT->getElementType()); uint64_t ArraySize = AT->getSize().getZExtValue(); for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { Class FieldLo, FieldHi; classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi); Lo = merge(Lo, FieldLo); Hi = merge(Hi, FieldHi); if (Lo == Memory || Hi == Memory) break; } // Do post merger cleanup (see below). Only case we worry about is Memory. if (Hi == Memory) Lo = Memory; assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); } else if (const RecordType *RT = Ty->getAsRecordType()) { uint64_t Size = Context.getTypeSize(Ty); // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger // than two eightbytes, ..., it has class MEMORY. if (Size > 128) return; const RecordDecl *RD = RT->getDecl(); // Assume variable sized types are passed in memory. if (RD->hasFlexibleArrayMember()) return; const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); // Reset Lo class, this will be recomputed. Current = NoClass; unsigned idx = 0; for (RecordDecl::field_iterator i = RD->field_begin(Context), e = RD->field_end(Context); i != e; ++i, ++idx) { uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); bool BitField = i->isBitField(); // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned // fields, it has class MEMORY. // // Note, skip this test for bitfields, see below. if (!BitField && Offset % Context.getTypeAlign(i->getType())) { Lo = Memory; return; } // Classify this field. // // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate // exceeds a single eightbyte, each is classified // separately. Each eightbyte gets initialized to class // NO_CLASS. Class FieldLo, FieldHi; // Bitfields require special handling, they do not force the // structure to be passed in memory even if unaligned, and // therefore they can straddle an eightbyte. if (BitField) { uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); uint64_t Size = i->getBitWidth()->getIntegerConstantExprValue(Context).getZExtValue(); uint64_t EB_Lo = Offset / 64; uint64_t EB_Hi = (Offset + Size - 1) / 64; FieldLo = FieldHi = NoClass; if (EB_Lo) { assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); FieldLo = NoClass; FieldHi = Integer; } else { FieldLo = Integer; FieldHi = EB_Hi ? Integer : NoClass; } } else classify(i->getType(), Context, Offset, FieldLo, FieldHi); Lo = merge(Lo, FieldLo); Hi = merge(Hi, FieldHi); if (Lo == Memory || Hi == Memory) break; } // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: // // (a) If one of the classes is MEMORY, the whole argument is // passed in memory. // // (b) If SSEUP is not preceeded by SSE, it is converted to SSE. // The first of these conditions is guaranteed by how we implement // the merge (just bail). // // The second condition occurs in the case of unions; for example // union { _Complex double; unsigned; }. if (Hi == Memory) Lo = Memory; if (Hi == SSEUp && Lo != SSE) Hi = SSE; } } ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty, const llvm::Type *CoerceTo, ASTContext &Context) const { if (CoerceTo == llvm::Type::Int64Ty) { // Integer and pointer types will end up in a general purpose // register. if (Ty->isIntegralType() || Ty->isPointerType()) return ABIArgInfo::getDirect(); } else if (CoerceTo == llvm::Type::DoubleTy) { // FIXME: It would probably be better to make CGFunctionInfo only // map using canonical types than to canonize here. QualType CTy = Context.getCanonicalType(Ty); // Float and double end up in a single SSE reg. if (CTy == Context.FloatTy || CTy == Context.DoubleTy) return ABIArgInfo::getDirect(); } return ABIArgInfo::getCoerce(CoerceTo); } ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy, ASTContext &Context) const { // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the // classification algorithm. X86_64ABIInfo::Class Lo, Hi; classify(RetTy, Context, 0, Lo, Hi); // Check some invariants. assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification."); assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); const llvm::Type *ResType = 0; switch (Lo) { case NoClass: return ABIArgInfo::getIgnore(); case SSEUp: case X87Up: assert(0 && "Invalid classification for lo word."); // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via // hidden argument. case Memory: return ABIArgInfo::getIndirect(0); // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next // available register of the sequence %rax, %rdx is used. case Integer: ResType = llvm::Type::Int64Ty; break; // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next // available SSE register of the sequence %xmm0, %xmm1 is used. case SSE: ResType = llvm::Type::DoubleTy; break; // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is // returned on the X87 stack in %st0 as 80-bit x87 number. case X87: ResType = llvm::Type::X86_FP80Ty; break; // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real // part of the value is returned in %st0 and the imaginary part in // %st1. case ComplexX87: assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); ResType = llvm::StructType::get(llvm::Type::X86_FP80Ty, llvm::Type::X86_FP80Ty, NULL); break; } switch (Hi) { // Memory was handled previously and X87 should // never occur as a hi class. case Memory: case X87: assert(0 && "Invalid classification for hi word."); case ComplexX87: // Previously handled. case NoClass: break; case Integer: ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL); break; case SSE: ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL); break; // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte // is passed in the upper half of the last used SSE register. // // SSEUP should always be preceeded by SSE, just widen. case SSEUp: assert(Lo == SSE && "Unexpected SSEUp classification."); ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2); break; // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is // returned together with the previous X87 value in %st0. case X87Up: // If X87Up is preceeded by X87, we don't need to do // anything. However, in some cases with unions it may not be // preceeded by X87. In such situations we follow gcc and pass the // extra bits in an SSE reg. if (Lo != X87) ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL); break; } return getCoerceResult(RetTy, ResType, Context); } ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context, unsigned &neededInt, unsigned &neededSSE) const { X86_64ABIInfo::Class Lo, Hi; classify(Ty, Context, 0, Lo, Hi); // Check some invariants. // FIXME: Enforce these by construction. assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification."); assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); neededInt = 0; neededSSE = 0; const llvm::Type *ResType = 0; switch (Lo) { case NoClass: return ABIArgInfo::getIgnore(); // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument // on the stack. case Memory: // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or // COMPLEX_X87, it is passed in memory. case X87: case ComplexX87: return ABIArgInfo::getIndirect(0); case SSEUp: case X87Up: assert(0 && "Invalid classification for lo word."); // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 // and %r9 is used. case Integer: ++neededInt; ResType = llvm::Type::Int64Ty; break; // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next // available SSE register is used, the registers are taken in the // order from %xmm0 to %xmm7. case SSE: ++neededSSE; ResType = llvm::Type::DoubleTy; break; } switch (Hi) { // Memory was handled previously, ComplexX87 and X87 should // never occur as hi classes, and X87Up must be preceed by X87, // which is passed in memory. case Memory: case X87: case ComplexX87: assert(0 && "Invalid classification for hi word."); break; case NoClass: break; case Integer: ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL); ++neededInt; break; // X87Up generally doesn't occur here (long double is passed in // memory), except in situations involving unions. case X87Up: case SSE: ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL); ++neededSSE; break; // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the // eightbyte is passed in the upper half of the last used SSE // register. case SSEUp: assert(Lo == SSE && "Unexpected SSEUp classification."); ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2); break; } return getCoerceResult(Ty, ResType, Context); } void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const { FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context); // Keep track of the number of assigned registers. unsigned freeIntRegs = 6, freeSSERegs = 8; // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers // get assigned (in left-to-right order) for passing as follows... for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) { unsigned neededInt, neededSSE; it->info = classifyArgumentType(it->type, Context, neededInt, neededSSE); // AMD64-ABI 3.2.3p3: If there are no registers available for any // eightbyte of an argument, the whole argument is passed on the // stack. If registers have already been assigned for some // eightbytes of such an argument, the assignments get reverted. if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) { freeIntRegs -= neededInt; freeSSERegs -= neededSSE; } else { it->info = ABIArgInfo::getIndirect(0); } } } static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) { llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); llvm::Value *overflow_arg_area = CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 // byte boundary if alignment needed by type exceeds 8 byte boundary. uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; if (Align > 8) { // Note that we follow the ABI & gcc here, even though the type // could in theory have an alignment greater than 16. This case // shouldn't ever matter in practice. // overflow_arg_area = (overflow_arg_area + 15) & ~15; llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, 15); overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset); llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area, llvm::Type::Int64Ty); llvm::Value *Mask = llvm::ConstantInt::get(llvm::Type::Int64Ty, ~15LL); overflow_arg_area = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask), overflow_arg_area->getType(), "overflow_arg_area.align"); } // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); llvm::Value *Res = CGF.Builder.CreateBitCast(overflow_arg_area, llvm::PointerType::getUnqual(LTy)); // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: // l->overflow_arg_area + sizeof(type). // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to // an 8 byte boundary. uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, (SizeInBytes + 7) & ~7); overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, "overflow_arg_area.next"); CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. return Res; } llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const { // Assume that va_list type is correct; should be pointer to LLVM type: // struct { // i32 gp_offset; // i32 fp_offset; // i8* overflow_arg_area; // i8* reg_save_area; // }; unsigned neededInt, neededSSE; ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(), neededInt, neededSSE); // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed // in the registers. If not go to step 7. if (!neededInt && !neededSSE) return EmitVAArgFromMemory(VAListAddr, Ty, CGF); // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of // general purpose registers needed to pass type and num_fp to hold // the number of floating point registers needed. // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into // registers. In the case: l->gp_offset > 48 - num_gp * 8 or // l->fp_offset > 304 - num_fp * 16 go to step 7. // // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of // register save space). llvm::Value *InRegs = 0; llvm::Value *gp_offset_p = 0, *gp_offset = 0; llvm::Value *fp_offset_p = 0, *fp_offset = 0; if (neededInt) { gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); InRegs = CGF.Builder.CreateICmpULE(gp_offset, llvm::ConstantInt::get(llvm::Type::Int32Ty, 48 - neededInt * 8), "fits_in_gp"); } if (neededSSE) { fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); llvm::Value *FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, llvm::ConstantInt::get(llvm::Type::Int32Ty, 176 - neededSSE * 16), "fits_in_fp"); InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; } llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); // Emit code to load the value if it was passed in registers. CGF.EmitBlock(InRegBlock); // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with // an offset of l->gp_offset and/or l->fp_offset. This may require // copying to a temporary location in case the parameter is passed // in different register classes or requires an alignment greater // than 8 for general purpose registers and 16 for XMM registers. // // FIXME: This really results in shameful code when we end up // needing to collect arguments from different places; often what // should result in a simple assembling of a structure from // scattered addresses has many more loads than necessary. Can we // clean this up? const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); llvm::Value *RegAddr = CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); if (neededInt && neededSSE) { // FIXME: Cleanup. assert(AI.isCoerce() && "Unexpected ABI info for mixed regs"); const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); llvm::Value *Tmp = CGF.CreateTempAlloca(ST); assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); const llvm::Type *TyLo = ST->getElementType(0); const llvm::Type *TyHi = ST->getElementType(1); assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) && "Unexpected ABI info for mixed regs"); const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr; llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr; llvm::Value *V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo)); CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi)); CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy)); } else if (neededInt) { RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset); RegAddr = CGF.Builder.CreateBitCast(RegAddr, llvm::PointerType::getUnqual(LTy)); } else { if (neededSSE == 1) { RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset); RegAddr = CGF.Builder.CreateBitCast(RegAddr, llvm::PointerType::getUnqual(LTy)); } else { assert(neededSSE == 2 && "Invalid number of needed registers!"); // SSE registers are spaced 16 bytes apart in the register save // area, we need to collect the two eightbytes together. llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset); llvm::Value *RegAddrHi = CGF.Builder.CreateGEP(RegAddrLo, llvm::ConstantInt::get(llvm::Type::Int32Ty, 16)); const llvm::Type *DblPtrTy = llvm::PointerType::getUnqual(llvm::Type::DoubleTy); const llvm::StructType *ST = llvm::StructType::get(llvm::Type::DoubleTy, llvm::Type::DoubleTy, NULL); llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST); V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo, DblPtrTy)); CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi, DblPtrTy)); CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy)); } } // AMD64-ABI 3.5.7p5: Step 5. Set: // l->gp_offset = l->gp_offset + num_gp * 8 // l->fp_offset = l->fp_offset + num_fp * 16. if (neededInt) { llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, neededInt * 8); CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), gp_offset_p); } if (neededSSE) { llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, neededSSE * 16); CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), fp_offset_p); } CGF.EmitBranch(ContBlock); // Emit code to load the value if it was passed in memory. CGF.EmitBlock(InMemBlock); llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF); // Return the appropriate result. CGF.EmitBlock(ContBlock); llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), "vaarg.addr"); ResAddr->reserveOperandSpace(2); ResAddr->addIncoming(RegAddr, InRegBlock); ResAddr->addIncoming(MemAddr, InMemBlock); return ResAddr; } class ARMABIInfo : public ABIInfo { ABIArgInfo classifyReturnType(QualType RetTy, ASTContext &Context) const; ABIArgInfo classifyArgumentType(QualType RetTy, ASTContext &Context) const; virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const; virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const; }; void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const { FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context); for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) { it->info = classifyArgumentType(it->type, Context); } } ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context) const { if (!CodeGenFunction::hasAggregateLLVMType(Ty)) { return ABIArgInfo::getDirect(); } // FIXME: This is kind of nasty... but there isn't much choice // because the ARM backend doesn't support byval. // FIXME: This doesn't handle alignment > 64 bits. const llvm::Type* ElemTy; unsigned SizeRegs; if (Context.getTypeAlign(Ty) > 32) { ElemTy = llvm::Type::Int64Ty; SizeRegs = (Context.getTypeSize(Ty) + 63) / 64; } else { ElemTy = llvm::Type::Int32Ty; SizeRegs = (Context.getTypeSize(Ty) + 31) / 32; } std::vector<const llvm::Type*> LLVMFields; LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs)); const llvm::Type* STy = llvm::StructType::get(LLVMFields, true); return ABIArgInfo::getCoerce(STy); } ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, ASTContext &Context) const { if (RetTy->isVoidType()) { return ABIArgInfo::getIgnore(); } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { // Aggregates <= 4 bytes are returned in r0; other aggregates // are returned indirectly. uint64_t Size = Context.getTypeSize(RetTy); if (Size <= 32) return ABIArgInfo::getCoerce(llvm::Type::Int32Ty); return ABIArgInfo::getIndirect(0); } else { return ABIArgInfo::getDirect(); } } llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const { // FIXME: Need to handle alignment const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); const llvm::Type *BPP = llvm::PointerType::getUnqual(BP); CGBuilderTy &Builder = CGF.Builder; llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy); uint64_t Offset = llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4); llvm::Value *NextAddr = Builder.CreateGEP(Addr, llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset), "ap.next"); Builder.CreateStore(NextAddr, VAListAddrAsBPP); return AddrTyped; } ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy, ASTContext &Context) const { if (RetTy->isVoidType()) { return ABIArgInfo::getIgnore(); } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { return ABIArgInfo::getIndirect(0); } else { return ABIArgInfo::getDirect(); } } ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context) const { if (CodeGenFunction::hasAggregateLLVMType(Ty)) { return ABIArgInfo::getIndirect(0); } else { return ABIArgInfo::getDirect(); } } llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGenFunction &CGF) const { return 0; } const ABIInfo &CodeGenTypes::getABIInfo() const { if (TheABIInfo) return *TheABIInfo; // For now we just cache this in the CodeGenTypes and don't bother // to free it. const char *TargetPrefix = getContext().Target.getTargetPrefix(); if (strcmp(TargetPrefix, "x86") == 0) { bool IsDarwin = strstr(getContext().Target.getTargetTriple(), "darwin"); switch (getContext().Target.getPointerWidth(0)) { case 32: return *(TheABIInfo = new X86_32ABIInfo(Context, IsDarwin)); case 64: return *(TheABIInfo = new X86_64ABIInfo()); } } else if (strcmp(TargetPrefix, "arm") == 0) { // FIXME: Support for OABI? return *(TheABIInfo = new ARMABIInfo()); } return *(TheABIInfo = new DefaultABIInfo); } /***/ CGFunctionInfo::CGFunctionInfo(QualType ResTy, const llvm::SmallVector<QualType, 16> &ArgTys) { NumArgs = ArgTys.size(); Args = new ArgInfo[1 + NumArgs]; Args[0].type = ResTy; for (unsigned i = 0; i < NumArgs; ++i) Args[1 + i].type = ArgTys[i]; } /***/ void CodeGenTypes::GetExpandedTypes(QualType Ty, std::vector<const llvm::Type*> &ArgTys) { const RecordType *RT = Ty->getAsStructureType(); assert(RT && "Can only expand structure types."); const RecordDecl *RD = RT->getDecl(); assert(!RD->hasFlexibleArrayMember() && "Cannot expand structure with flexible array."); for (RecordDecl::field_iterator i = RD->field_begin(Context), e = RD->field_end(Context); i != e; ++i) { const FieldDecl *FD = *i; assert(!FD->isBitField() && "Cannot expand structure with bit-field members."); QualType FT = FD->getType(); if (CodeGenFunction::hasAggregateLLVMType(FT)) { GetExpandedTypes(FT, ArgTys); } else { ArgTys.push_back(ConvertType(FT)); } } } llvm::Function::arg_iterator CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV, llvm::Function::arg_iterator AI) { const RecordType *RT = Ty->getAsStructureType(); assert(RT && "Can only expand structure types."); RecordDecl *RD = RT->getDecl(); assert(LV.isSimple() && "Unexpected non-simple lvalue during struct expansion."); llvm::Value *Addr = LV.getAddress(); for (RecordDecl::field_iterator i = RD->field_begin(getContext()), e = RD->field_end(getContext()); i != e; ++i) { FieldDecl *FD = *i; QualType FT = FD->getType(); // FIXME: What are the right qualifiers here? LValue LV = EmitLValueForField(Addr, FD, false, 0); if (CodeGenFunction::hasAggregateLLVMType(FT)) { AI = ExpandTypeFromArgs(FT, LV, AI); } else { EmitStoreThroughLValue(RValue::get(AI), LV, FT); ++AI; } } return AI; } void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV, llvm::SmallVector<llvm::Value*, 16> &Args) { const RecordType *RT = Ty->getAsStructureType(); assert(RT && "Can only expand structure types."); RecordDecl *RD = RT->getDecl(); assert(RV.isAggregate() && "Unexpected rvalue during struct expansion"); llvm::Value *Addr = RV.getAggregateAddr(); for (RecordDecl::field_iterator i = RD->field_begin(getContext()), e = RD->field_end(getContext()); i != e; ++i) { FieldDecl *FD = *i; QualType FT = FD->getType(); // FIXME: What are the right qualifiers here? LValue LV = EmitLValueForField(Addr, FD, false, 0); if (CodeGenFunction::hasAggregateLLVMType(FT)) { ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args); } else { RValue RV = EmitLoadOfLValue(LV, FT); assert(RV.isScalar() && "Unexpected non-scalar rvalue during struct expansion."); Args.push_back(RV.getScalarVal()); } } } /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as /// a pointer to an object of type \arg Ty. /// /// This safely handles the case when the src type is smaller than the /// destination type; in this situation the values of bits which not /// present in the src are undefined. static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr, const llvm::Type *Ty, CodeGenFunction &CGF) { const llvm::Type *SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType(); uint64_t SrcSize = CGF.CGM.getTargetData().getTypePaddedSize(SrcTy); uint64_t DstSize = CGF.CGM.getTargetData().getTypePaddedSize(Ty); // If load is legal, just bitcast the src pointer. if (SrcSize == DstSize) { llvm::Value *Casted = CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty)); llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); // FIXME: Use better alignment / avoid requiring aligned load. Load->setAlignment(1); return Load; } else { assert(SrcSize < DstSize && "Coercion is losing source bits!"); // Otherwise do coercion through memory. This is stupid, but // simple. llvm::Value *Tmp = CGF.CreateTempAlloca(Ty); llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy)); llvm::StoreInst *Store = CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted); // FIXME: Use better alignment / avoid requiring aligned store. Store->setAlignment(1); return CGF.Builder.CreateLoad(Tmp); } } /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, /// where the source and destination may have different types. /// /// This safely handles the case when the src type is larger than the /// destination type; the upper bits of the src will be lost. static void CreateCoercedStore(llvm::Value *Src, llvm::Value *DstPtr, CodeGenFunction &CGF) { const llvm::Type *SrcTy = Src->getType(); const llvm::Type *DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType(); uint64_t SrcSize = CGF.CGM.getTargetData().getTypePaddedSize(SrcTy); uint64_t DstSize = CGF.CGM.getTargetData().getTypePaddedSize(DstTy); // If store is legal, just bitcast the src pointer. if (SrcSize == DstSize) { llvm::Value *Casted = CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy)); // FIXME: Use better alignment / avoid requiring aligned store. CGF.Builder.CreateStore(Src, Casted)->setAlignment(1); } else { assert(SrcSize > DstSize && "Coercion is missing bits!"); // Otherwise do coercion through memory. This is stupid, but // simple. llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy); CGF.Builder.CreateStore(Src, Tmp); llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy)); llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted); // FIXME: Use better alignment / avoid requiring aligned load. Load->setAlignment(1); CGF.Builder.CreateStore(Load, DstPtr); } } /***/ bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) { return FI.getReturnInfo().isIndirect(); } const llvm::FunctionType * CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) { std::vector<const llvm::Type*> ArgTys; const llvm::Type *ResultType = 0; QualType RetTy = FI.getReturnType(); const ABIArgInfo &RetAI = FI.getReturnInfo(); switch (RetAI.getKind()) { case ABIArgInfo::Expand: assert(0 && "Invalid ABI kind for return argument"); case ABIArgInfo::Direct: ResultType = ConvertType(RetTy); break; case ABIArgInfo::Indirect: { assert(!RetAI.getIndirectAlign() && "Align unused on indirect return."); ResultType = llvm::Type::VoidTy; const llvm::Type *STy = ConvertType(RetTy); ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace())); break; } case ABIArgInfo::Ignore: ResultType = llvm::Type::VoidTy; break; case ABIArgInfo::Coerce: ResultType = RetAI.getCoerceToType(); break; } for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) { const ABIArgInfo &AI = it->info; switch (AI.getKind()) { case ABIArgInfo::Ignore: break; case ABIArgInfo::Coerce: ArgTys.push_back(AI.getCoerceToType()); break; case ABIArgInfo::Indirect: { // indirect arguments are always on the stack, which is addr space #0. const llvm::Type *LTy = ConvertTypeForMem(it->type); ArgTys.push_back(llvm::PointerType::getUnqual(LTy)); break; } case ABIArgInfo::Direct: ArgTys.push_back(ConvertType(it->type)); break; case ABIArgInfo::Expand: GetExpandedTypes(it->type, ArgTys); break; } } return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic); } void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI, const Decl *TargetDecl, AttributeListType &PAL) { unsigned FuncAttrs = 0; unsigned RetAttrs = 0; // FIXME: handle sseregparm someday... if (TargetDecl) { if (TargetDecl->hasAttr<NoThrowAttr>()) FuncAttrs |= llvm::Attribute::NoUnwind; if (TargetDecl->hasAttr<NoReturnAttr>()) FuncAttrs |= llvm::Attribute::NoReturn; if (TargetDecl->hasAttr<ConstAttr>()) FuncAttrs |= llvm::Attribute::ReadNone; else if (TargetDecl->hasAttr<PureAttr>()) FuncAttrs |= llvm::Attribute::ReadOnly; } QualType RetTy = FI.getReturnType(); unsigned Index = 1; const ABIArgInfo &RetAI = FI.getReturnInfo(); switch (RetAI.getKind()) { case ABIArgInfo::Direct: if (RetTy->isPromotableIntegerType()) { if (RetTy->isSignedIntegerType()) { RetAttrs |= llvm::Attribute::SExt; } else if (RetTy->isUnsignedIntegerType()) { RetAttrs |= llvm::Attribute::ZExt; } } break; case ABIArgInfo::Indirect: PAL.push_back(llvm::AttributeWithIndex::get(Index, llvm::Attribute::StructRet | llvm::Attribute::NoAlias)); ++Index; // sret disables readnone and readonly FuncAttrs &= ~(llvm::Attribute::ReadOnly | llvm::Attribute::ReadNone); break; case ABIArgInfo::Ignore: case ABIArgInfo::Coerce: break; case ABIArgInfo::Expand: assert(0 && "Invalid ABI kind for return argument"); } if (RetAttrs) PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs)); // FIXME: we need to honour command line settings also... // FIXME: RegParm should be reduced in case of nested functions and/or global // register variable. signed RegParm = 0; if (TargetDecl) if (const RegparmAttr *RegParmAttr = TargetDecl->getAttr<RegparmAttr>()) RegParm = RegParmAttr->getNumParams(); unsigned PointerWidth = getContext().Target.getPointerWidth(0); for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); it != ie; ++it) { QualType ParamType = it->type; const ABIArgInfo &AI = it->info; unsigned Attributes = 0; switch (AI.getKind()) { case ABIArgInfo::Coerce: break; case ABIArgInfo::Indirect: Attributes |= llvm::Attribute::ByVal; Attributes |= llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign()); // byval disables readnone and readonly. FuncAttrs &= ~(llvm::Attribute::ReadOnly | llvm::Attribute::ReadNone); break; case ABIArgInfo::Direct: if (ParamType->isPromotableIntegerType()) { if (ParamType->isSignedIntegerType()) { Attributes |= llvm::Attribute::SExt; } else if (ParamType->isUnsignedIntegerType()) { Attributes |= llvm::Attribute::ZExt; } } if (RegParm > 0 && (ParamType->isIntegerType() || ParamType->isPointerType())) { RegParm -= (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth; if (RegParm >= 0) Attributes |= llvm::Attribute::InReg; } // FIXME: handle sseregparm someday... break; case ABIArgInfo::Ignore: // Skip increment, no matching LLVM parameter. continue; case ABIArgInfo::Expand: { std::vector<const llvm::Type*> Tys; // FIXME: This is rather inefficient. Do we ever actually need // to do anything here? The result should be just reconstructed // on the other side, so extension should be a non-issue. getTypes().GetExpandedTypes(ParamType, Tys); Index += Tys.size(); continue; } } if (Attributes) PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes)); ++Index; } if (FuncAttrs) PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs)); } void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args) { // FIXME: We no longer need the types from FunctionArgList; lift up // and simplify. // Emit allocs for param decls. Give the LLVM Argument nodes names. llvm::Function::arg_iterator AI = Fn->arg_begin(); // Name the struct return argument. if (CGM.ReturnTypeUsesSret(FI)) { AI->setName("agg.result"); ++AI; } assert(FI.arg_size() == Args.size() && "Mismatch between function signature & arguments."); CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); i != e; ++i, ++info_it) { const VarDecl *Arg = i->first; QualType Ty = info_it->type; const ABIArgInfo &ArgI = info_it->info; switch (ArgI.getKind()) { case ABIArgInfo::Indirect: { llvm::Value* V = AI; if (hasAggregateLLVMType(Ty)) { // Do nothing, aggregates and complex variables are accessed by // reference. } else { // Load scalar value from indirect argument. V = EmitLoadOfScalar(V, false, Ty); if (!getContext().typesAreCompatible(Ty, Arg->getType())) { // This must be a promotion, for something like // "void a(x) short x; {..." V = EmitScalarConversion(V, Ty, Arg->getType()); } } EmitParmDecl(*Arg, V); break; } case ABIArgInfo::Direct: { assert(AI != Fn->arg_end() && "Argument mismatch!"); llvm::Value* V = AI; if (hasAggregateLLVMType(Ty)) { // Create a temporary alloca to hold the argument; the rest of // codegen expects to access aggregates & complex values by // reference. V = CreateTempAlloca(ConvertTypeForMem(Ty)); Builder.CreateStore(AI, V); } else { if (!getContext().typesAreCompatible(Ty, Arg->getType())) { // This must be a promotion, for something like // "void a(x) short x; {..." V = EmitScalarConversion(V, Ty, Arg->getType()); } } EmitParmDecl(*Arg, V); break; } case ABIArgInfo::Expand: { // If this structure was expanded into multiple arguments then // we need to create a temporary and reconstruct it from the // arguments. std::string Name = Arg->getNameAsString(); llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty), (Name + ".addr").c_str()); // FIXME: What are the right qualifiers here? llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI); EmitParmDecl(*Arg, Temp); // Name the arguments used in expansion and increment AI. unsigned Index = 0; for (; AI != End; ++AI, ++Index) AI->setName(Name + "." + llvm::utostr(Index)); continue; } case ABIArgInfo::Ignore: // Initialize the local variable appropriately. if (hasAggregateLLVMType(Ty)) { EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty))); } else { EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType()))); } // Skip increment, no matching LLVM parameter. continue; case ABIArgInfo::Coerce: { assert(AI != Fn->arg_end() && "Argument mismatch!"); // FIXME: This is very wasteful; EmitParmDecl is just going to // drop the result in a new alloca anyway, so we could just // store into that directly if we broke the abstraction down // more. llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(Ty), "coerce"); CreateCoercedStore(AI, V, *this); // Match to what EmitParmDecl is expecting for this type. if (!CodeGenFunction::hasAggregateLLVMType(Ty)) { V = EmitLoadOfScalar(V, false, Ty); if (!getContext().typesAreCompatible(Ty, Arg->getType())) { // This must be a promotion, for something like // "void a(x) short x; {..." V = EmitScalarConversion(V, Ty, Arg->getType()); } } EmitParmDecl(*Arg, V); break; } } ++AI; } assert(AI == Fn->arg_end() && "Argument mismatch!"); } void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue) { llvm::Value *RV = 0; // Functions with no result always return void. if (ReturnValue) { QualType RetTy = FI.getReturnType(); const ABIArgInfo &RetAI = FI.getReturnInfo(); switch (RetAI.getKind()) { case ABIArgInfo::Indirect: if (RetTy->isAnyComplexType()) { ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false); StoreComplexToAddr(RT, CurFn->arg_begin(), false); } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy); } else { EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(), false); } break; case ABIArgInfo::Direct: // The internal return value temp always will have // pointer-to-return-type type. RV = Builder.CreateLoad(ReturnValue); break; case ABIArgInfo::Ignore: break; case ABIArgInfo::Coerce: RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this); break; case ABIArgInfo::Expand: assert(0 && "Invalid ABI kind for return argument"); } } if (RV) { Builder.CreateRet(RV); } else { Builder.CreateRetVoid(); } } RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) { return EmitAnyExprToTemp(E); } void CodeGenFunction::EmitCallArgs(CallArgList& Args, const FunctionProtoType *FPT, CallExpr::const_arg_iterator ArgBeg, CallExpr::const_arg_iterator ArgEnd) { CallExpr::const_arg_iterator Arg = ArgBeg; // First, use the function argument types. if (FPT) { for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(), E = FPT->arg_type_end(); I != E; ++I, ++Arg) { assert(getContext().getCanonicalType(I->getNonReferenceType()). getTypePtr() == getContext().getCanonicalType(Arg->getType()).getTypePtr() && "type mismatch in call argument!"); QualType ArgType = *I; Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), ArgType)); } assert(Arg == ArgEnd || FPT->isVariadic() && "Extra arguments in non-variadic function!"); } // If we still have any arguments, emit them using the type of the argument. for (; Arg != ArgEnd; ++Arg) { QualType ArgType = Arg->getType(); Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType), ArgType)); } } RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, llvm::Value *Callee, const CallArgList &CallArgs, const Decl *TargetDecl) { // FIXME: We no longer need the types from CallArgs; lift up and // simplify. llvm::SmallVector<llvm::Value*, 16> Args; // Handle struct-return functions by passing a pointer to the // location that we would like to return into. QualType RetTy = CallInfo.getReturnType(); const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); if (CGM.ReturnTypeUsesSret(CallInfo)) { // Create a temporary alloca to hold the result of the call. :( Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy))); } assert(CallInfo.arg_size() == CallArgs.size() && "Mismatch between function signature & arguments."); CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); I != E; ++I, ++info_it) { const ABIArgInfo &ArgInfo = info_it->info; RValue RV = I->first; switch (ArgInfo.getKind()) { case ABIArgInfo::Indirect: if (RV.isScalar() || RV.isComplex()) { // Make a temporary alloca to pass the argument. Args.push_back(CreateTempAlloca(ConvertTypeForMem(I->second))); if (RV.isScalar()) EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false); else StoreComplexToAddr(RV.getComplexVal(), Args.back(), false); } else { Args.push_back(RV.getAggregateAddr()); } break; case ABIArgInfo::Direct: if (RV.isScalar()) { Args.push_back(RV.getScalarVal()); } else if (RV.isComplex()) { llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second)); Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0); Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1); Args.push_back(Tmp); } else { Args.push_back(Builder.CreateLoad(RV.getAggregateAddr())); } break; case ABIArgInfo::Ignore: break; case ABIArgInfo::Coerce: { // FIXME: Avoid the conversion through memory if possible. llvm::Value *SrcPtr; if (RV.isScalar()) { SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce"); EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false); } else if (RV.isComplex()) { SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce"); StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false); } else SrcPtr = RV.getAggregateAddr(); Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this)); break; } case ABIArgInfo::Expand: ExpandTypeToArgs(I->second, RV, Args); break; } } llvm::BasicBlock *InvokeDest = getInvokeDest(); CodeGen::AttributeListType AttributeList; CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList); llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(), AttributeList.end()); llvm::CallSite CS; if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) { CS = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size()); } else { llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, &Args[0], &Args[0]+Args.size()); EmitBlock(Cont); } CS.setAttributes(Attrs); if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee)) CS.setCallingConv(F->getCallingConv()); // If the call doesn't return, finish the basic block and clear the // insertion point; this allows the rest of IRgen to discard // unreachable code. if (CS.doesNotReturn()) { Builder.CreateUnreachable(); Builder.ClearInsertionPoint(); // FIXME: For now, emit a dummy basic block because expr // emitters in generally are not ready to handle emitting // expressions at unreachable points. EnsureInsertPoint(); // Return a reasonable RValue. return GetUndefRValue(RetTy); } llvm::Instruction *CI = CS.getInstruction(); if (Builder.isNamePreserving() && CI->getType() != llvm::Type::VoidTy) CI->setName("call"); switch (RetAI.getKind()) { case ABIArgInfo::Indirect: if (RetTy->isAnyComplexType()) return RValue::getComplex(LoadComplexFromAddr(Args[0], false)); if (CodeGenFunction::hasAggregateLLVMType(RetTy)) return RValue::getAggregate(Args[0]); return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy)); case ABIArgInfo::Direct: if (RetTy->isAnyComplexType()) { llvm::Value *Real = Builder.CreateExtractValue(CI, 0); llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); return RValue::getComplex(std::make_pair(Real, Imag)); } if (CodeGenFunction::hasAggregateLLVMType(RetTy)) { llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "agg.tmp"); Builder.CreateStore(CI, V); return RValue::getAggregate(V); } return RValue::get(CI); case ABIArgInfo::Ignore: // If we are ignoring an argument that had a result, make sure to // construct the appropriate return value for our caller. return GetUndefRValue(RetTy); case ABIArgInfo::Coerce: { // FIXME: Avoid the conversion through memory if possible. llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "coerce"); CreateCoercedStore(CI, V, *this); if (RetTy->isAnyComplexType()) return RValue::getComplex(LoadComplexFromAddr(V, false)); if (CodeGenFunction::hasAggregateLLVMType(RetTy)) return RValue::getAggregate(V); return RValue::get(EmitLoadOfScalar(V, false, RetTy)); } case ABIArgInfo::Expand: assert(0 && "Invalid ABI kind for return argument"); } assert(0 && "Unhandled ABIArgInfo::Kind"); return RValue::get(0); } /* VarArg handling */ llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) { return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this); } <file_sep>/include/clang/Analysis/PathSensitive/GRExprEngine.h //===-- GRExprEngine.h - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-= // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a meta-engine for path-sensitive dataflow analysis that // is built on GRCoreEngine, but provides the boilerplate to execute transfer // functions and build the ExplodedGraph at the expression level. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_GREXPRENGINE #define LLVM_CLANG_ANALYSIS_GREXPRENGINE #include "clang/Analysis/PathSensitive/GRCoreEngine.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/PathSensitive/GRSimpleAPICheck.h" #include "clang/Analysis/PathSensitive/GRTransferFuncs.h" #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/AST/Type.h" #include "clang/AST/ExprObjC.h" namespace clang { class PathDiagnosticClient; class Diagnostic; class GRExprEngine { public: typedef GRState StateTy; typedef ExplodedGraph<StateTy> GraphTy; typedef GraphTy::NodeTy NodeTy; // Builders. typedef GRStmtNodeBuilder<StateTy> StmtNodeBuilder; typedef GRBranchNodeBuilder<StateTy> BranchNodeBuilder; typedef GRIndirectGotoNodeBuilder<StateTy> IndirectGotoNodeBuilder; typedef GRSwitchNodeBuilder<StateTy> SwitchNodeBuilder; typedef GREndPathNodeBuilder<StateTy> EndPathNodeBuilder; typedef ExplodedNodeSet<StateTy> NodeSet; protected: GRCoreEngine<GRExprEngine> CoreEngine; /// G - the simulation graph. GraphTy& G; /// Liveness - live-variables information the ValueDecl* and block-level /// Expr* in the CFG. Used to prune out dead state. LiveVariables& Liveness; /// Builder - The current GRStmtNodeBuilder which is used when building the /// nodes for a given statement. StmtNodeBuilder* Builder; /// StateMgr - Object that manages the data for all created states. GRStateManager StateMgr; /// SymMgr - Object that manages the symbol information. SymbolManager& SymMgr; /// ValMgr - Object that manages/creates SVals. ValueManager &ValMgr; /// EntryNode - The immediate predecessor node. NodeTy* EntryNode; /// CleanedState - The state for EntryNode "cleaned" of all dead /// variables and symbols (as determined by a liveness analysis). const GRState* CleanedState; /// CurrentStmt - The current block-level statement. Stmt* CurrentStmt; // Obj-C Class Identifiers. IdentifierInfo* NSExceptionII; // Obj-C Selectors. Selector* NSExceptionInstanceRaiseSelectors; Selector RaiseSel; llvm::OwningPtr<GRSimpleAPICheck> BatchAuditor; /// PurgeDead - Remove dead bindings before processing a statement. bool PurgeDead; /// BR - The BugReporter associated with this engine. It is important that // this object be placed at the very end of member variables so that its // destructor is called before the rest of the GRExprEngine is destroyed. GRBugReporter BR; /// EargerlyAssume - A flag indicating how the engine should handle // expressions such as: 'x = (y != 0)'. When this flag is true then // the subexpression 'y != 0' will be eagerly assumed to be true or false, // thus evaluating it to the integers 0 or 1 respectively. The upside // is that this can increase analysis precision until we have a better way // to lazily evaluate such logic. The downside is that it eagerly // bifurcates paths. const bool EagerlyAssume; public: typedef llvm::SmallPtrSet<NodeTy*,2> ErrorNodes; typedef llvm::DenseMap<NodeTy*, Expr*> UndefArgsTy; /// NilReceiverStructRetExplicit - Nodes in the ExplodedGraph that resulted /// from [x ...] with 'x' definitely being nil and the result was a 'struct' // (an undefined value). ErrorNodes NilReceiverStructRetExplicit; /// NilReceiverStructRetImplicit - Nodes in the ExplodedGraph that resulted /// from [x ...] with 'x' possibly being nil and the result was a 'struct' // (an undefined value). ErrorNodes NilReceiverStructRetImplicit; /// NilReceiverLargerThanVoidPtrRetExplicit - Nodes in the ExplodedGraph that /// resulted from [x ...] with 'x' definitely being nil and the result's size // was larger than sizeof(void *) (an undefined value). ErrorNodes NilReceiverLargerThanVoidPtrRetExplicit; /// NilReceiverLargerThanVoidPtrRetImplicit - Nodes in the ExplodedGraph that /// resulted from [x ...] with 'x' possibly being nil and the result's size // was larger than sizeof(void *) (an undefined value). ErrorNodes NilReceiverLargerThanVoidPtrRetImplicit; /// RetsStackAddr - Nodes in the ExplodedGraph that result from returning /// the address of a stack variable. ErrorNodes RetsStackAddr; /// RetsUndef - Nodes in the ExplodedGraph that result from returning /// an undefined value. ErrorNodes RetsUndef; /// UndefBranches - Nodes in the ExplodedGraph that result from /// taking a branch based on an undefined value. ErrorNodes UndefBranches; /// UndefStores - Sinks in the ExplodedGraph that result from /// making a store to an undefined lvalue. ErrorNodes UndefStores; /// NoReturnCalls - Sinks in the ExplodedGraph that result from // calling a function with the attribute "noreturn". ErrorNodes NoReturnCalls; /// ImplicitNullDeref - Nodes in the ExplodedGraph that result from /// taking a dereference on a symbolic pointer that MAY be NULL. ErrorNodes ImplicitNullDeref; /// ExplicitNullDeref - Nodes in the ExplodedGraph that result from /// taking a dereference on a symbolic pointer that MUST be NULL. ErrorNodes ExplicitNullDeref; /// UnitDeref - Nodes in the ExplodedGraph that result from /// taking a dereference on an undefined value. ErrorNodes UndefDeref; /// ImplicitBadDivides - Nodes in the ExplodedGraph that result from /// evaluating a divide or modulo operation where the denominator /// MAY be zero. ErrorNodes ImplicitBadDivides; /// ExplicitBadDivides - Nodes in the ExplodedGraph that result from /// evaluating a divide or modulo operation where the denominator /// MUST be zero or undefined. ErrorNodes ExplicitBadDivides; /// ImplicitBadSizedVLA - Nodes in the ExplodedGraph that result from /// constructing a zero-sized VLA where the size may be zero. ErrorNodes ImplicitBadSizedVLA; /// ExplicitBadSizedVLA - Nodes in the ExplodedGraph that result from /// constructing a zero-sized VLA where the size must be zero. ErrorNodes ExplicitBadSizedVLA; /// UndefResults - Nodes in the ExplodedGraph where the operands are defined /// by the result is not. Excludes divide-by-zero errors. ErrorNodes UndefResults; /// BadCalls - Nodes in the ExplodedGraph resulting from calls to function /// pointers that are NULL (or other constants) or Undefined. ErrorNodes BadCalls; /// UndefReceiver - Nodes in the ExplodedGraph resulting from message /// ObjC message expressions where the receiver is undefined (uninitialized). ErrorNodes UndefReceivers; /// UndefArg - Nodes in the ExplodedGraph resulting from calls to functions /// where a pass-by-value argument has an undefined value. UndefArgsTy UndefArgs; /// MsgExprUndefArgs - Nodes in the ExplodedGraph resulting from /// message expressions where a pass-by-value argument has an undefined /// value. UndefArgsTy MsgExprUndefArgs; /// OutOfBoundMemAccesses - Nodes in the ExplodedGraph resulting from /// out-of-bound memory accesses where the index MAY be out-of-bound. ErrorNodes ImplicitOOBMemAccesses; /// OutOfBoundMemAccesses - Nodes in the ExplodedGraph resulting from /// out-of-bound memory accesses where the index MUST be out-of-bound. ErrorNodes ExplicitOOBMemAccesses; public: GRExprEngine(CFG& cfg, Decl& CD, ASTContext& Ctx, LiveVariables& L, BugReporterData& BRD, bool purgeDead, bool eagerlyAssume = true, StoreManagerCreator SMC = CreateBasicStoreManager, ConstraintManagerCreator CMC = CreateBasicConstraintManager); ~GRExprEngine(); void ExecuteWorkList(unsigned Steps = 150000) { CoreEngine.ExecuteWorkList(Steps); } /// getContext - Return the ASTContext associated with this analysis. ASTContext& getContext() const { return G.getContext(); } /// getCFG - Returns the CFG associated with this analysis. CFG& getCFG() { return G.getCFG(); } GRTransferFuncs& getTF() { return *StateMgr.TF; } BugReporter& getBugReporter() { return BR; } /// setTransferFunctions void setTransferFunctions(GRTransferFuncs* tf); void setTransferFunctions(GRTransferFuncs& tf) { setTransferFunctions(&tf); } /// ViewGraph - Visualize the ExplodedGraph created by executing the /// simulation. void ViewGraph(bool trim = false); void ViewGraph(NodeTy** Beg, NodeTy** End); /// getLiveness - Returned computed live-variables information for the /// analyzed function. const LiveVariables& getLiveness() const { return Liveness; } LiveVariables& getLiveness() { return Liveness; } /// getInitialState - Return the initial state used for the root vertex /// in the ExplodedGraph. const GRState* getInitialState(); GraphTy& getGraph() { return G; } const GraphTy& getGraph() const { return G; } void RegisterInternalChecks(); bool isRetStackAddr(const NodeTy* N) const { return N->isSink() && RetsStackAddr.count(const_cast<NodeTy*>(N)) != 0; } bool isUndefControlFlow(const NodeTy* N) const { return N->isSink() && UndefBranches.count(const_cast<NodeTy*>(N)) != 0; } bool isUndefStore(const NodeTy* N) const { return N->isSink() && UndefStores.count(const_cast<NodeTy*>(N)) != 0; } bool isImplicitNullDeref(const NodeTy* N) const { return N->isSink() && ImplicitNullDeref.count(const_cast<NodeTy*>(N)) != 0; } bool isExplicitNullDeref(const NodeTy* N) const { return N->isSink() && ExplicitNullDeref.count(const_cast<NodeTy*>(N)) != 0; } bool isUndefDeref(const NodeTy* N) const { return N->isSink() && UndefDeref.count(const_cast<NodeTy*>(N)) != 0; } bool isImplicitBadDivide(const NodeTy* N) const { return N->isSink() && ImplicitBadDivides.count(const_cast<NodeTy*>(N)) != 0; } bool isExplicitBadDivide(const NodeTy* N) const { return N->isSink() && ExplicitBadDivides.count(const_cast<NodeTy*>(N)) != 0; } bool isNoReturnCall(const NodeTy* N) const { return N->isSink() && NoReturnCalls.count(const_cast<NodeTy*>(N)) != 0; } bool isUndefResult(const NodeTy* N) const { return N->isSink() && UndefResults.count(const_cast<NodeTy*>(N)) != 0; } bool isBadCall(const NodeTy* N) const { return N->isSink() && BadCalls.count(const_cast<NodeTy*>(N)) != 0; } bool isUndefArg(const NodeTy* N) const { return N->isSink() && (UndefArgs.find(const_cast<NodeTy*>(N)) != UndefArgs.end() || MsgExprUndefArgs.find(const_cast<NodeTy*>(N)) != MsgExprUndefArgs.end()); } bool isUndefReceiver(const NodeTy* N) const { return N->isSink() && UndefReceivers.count(const_cast<NodeTy*>(N)) != 0; } typedef ErrorNodes::iterator ret_stackaddr_iterator; ret_stackaddr_iterator ret_stackaddr_begin() { return RetsStackAddr.begin(); } ret_stackaddr_iterator ret_stackaddr_end() { return RetsStackAddr.end(); } typedef ErrorNodes::iterator ret_undef_iterator; ret_undef_iterator ret_undef_begin() { return RetsUndef.begin(); } ret_undef_iterator ret_undef_end() { return RetsUndef.end(); } typedef ErrorNodes::iterator undef_branch_iterator; undef_branch_iterator undef_branches_begin() { return UndefBranches.begin(); } undef_branch_iterator undef_branches_end() { return UndefBranches.end(); } typedef ErrorNodes::iterator null_deref_iterator; null_deref_iterator null_derefs_begin() { return ExplicitNullDeref.begin(); } null_deref_iterator null_derefs_end() { return ExplicitNullDeref.end(); } null_deref_iterator implicit_null_derefs_begin() { return ImplicitNullDeref.begin(); } null_deref_iterator implicit_null_derefs_end() { return ImplicitNullDeref.end(); } typedef ErrorNodes::iterator nil_receiver_struct_ret_iterator; nil_receiver_struct_ret_iterator nil_receiver_struct_ret_begin() { return NilReceiverStructRetExplicit.begin(); } nil_receiver_struct_ret_iterator nil_receiver_struct_ret_end() { return NilReceiverStructRetExplicit.end(); } typedef ErrorNodes::iterator nil_receiver_larger_than_voidptr_ret_iterator; nil_receiver_larger_than_voidptr_ret_iterator nil_receiver_larger_than_voidptr_ret_begin() { return NilReceiverLargerThanVoidPtrRetExplicit.begin(); } nil_receiver_larger_than_voidptr_ret_iterator nil_receiver_larger_than_voidptr_ret_end() { return NilReceiverLargerThanVoidPtrRetExplicit.end(); } typedef ErrorNodes::iterator undef_deref_iterator; undef_deref_iterator undef_derefs_begin() { return UndefDeref.begin(); } undef_deref_iterator undef_derefs_end() { return UndefDeref.end(); } typedef ErrorNodes::iterator bad_divide_iterator; bad_divide_iterator explicit_bad_divides_begin() { return ExplicitBadDivides.begin(); } bad_divide_iterator explicit_bad_divides_end() { return ExplicitBadDivides.end(); } bad_divide_iterator implicit_bad_divides_begin() { return ImplicitBadDivides.begin(); } bad_divide_iterator implicit_bad_divides_end() { return ImplicitBadDivides.end(); } typedef ErrorNodes::iterator undef_result_iterator; undef_result_iterator undef_results_begin() { return UndefResults.begin(); } undef_result_iterator undef_results_end() { return UndefResults.end(); } typedef ErrorNodes::iterator bad_calls_iterator; bad_calls_iterator bad_calls_begin() { return BadCalls.begin(); } bad_calls_iterator bad_calls_end() { return BadCalls.end(); } typedef UndefArgsTy::iterator undef_arg_iterator; undef_arg_iterator undef_arg_begin() { return UndefArgs.begin(); } undef_arg_iterator undef_arg_end() { return UndefArgs.end(); } undef_arg_iterator msg_expr_undef_arg_begin() { return MsgExprUndefArgs.begin(); } undef_arg_iterator msg_expr_undef_arg_end() { return MsgExprUndefArgs.end(); } typedef ErrorNodes::iterator undef_receivers_iterator; undef_receivers_iterator undef_receivers_begin() { return UndefReceivers.begin(); } undef_receivers_iterator undef_receivers_end() { return UndefReceivers.end(); } typedef ErrorNodes::iterator oob_memacc_iterator; oob_memacc_iterator implicit_oob_memacc_begin() { return ImplicitOOBMemAccesses.begin(); } oob_memacc_iterator implicit_oob_memacc_end() { return ImplicitOOBMemAccesses.end(); } oob_memacc_iterator explicit_oob_memacc_begin() { return ExplicitOOBMemAccesses.begin(); } oob_memacc_iterator explicit_oob_memacc_end() { return ExplicitOOBMemAccesses.end(); } void AddCheck(GRSimpleAPICheck* A, Stmt::StmtClass C); void AddCheck(GRSimpleAPICheck* A); /// ProcessStmt - Called by GRCoreEngine. Used to generate new successor /// nodes by processing the 'effects' of a block-level statement. void ProcessStmt(Stmt* S, StmtNodeBuilder& builder); /// ProcessBlockEntrance - Called by GRCoreEngine when start processing /// a CFGBlock. This method returns true if the analysis should continue /// exploring the given path, and false otherwise. bool ProcessBlockEntrance(CFGBlock* B, const GRState* St, GRBlockCounter BC); /// ProcessBranch - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a branch condition. void ProcessBranch(Stmt* Condition, Stmt* Term, BranchNodeBuilder& builder); /// ProcessIndirectGoto - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a computed goto jump. void ProcessIndirectGoto(IndirectGotoNodeBuilder& builder); /// ProcessSwitch - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a switch statement. void ProcessSwitch(SwitchNodeBuilder& builder); /// ProcessEndPath - Called by GRCoreEngine. Used to generate end-of-path /// nodes when the control reaches the end of a function. void ProcessEndPath(EndPathNodeBuilder& builder) { getTF().EvalEndPath(*this, builder); StateMgr.EndPath(builder.getState()); } GRStateManager& getStateManager() { return StateMgr; } const GRStateManager& getStateManger() const { return StateMgr; } StoreManager& getStoreManager() { return StateMgr.getStoreManager(); } ConstraintManager& getConstraintManager() { return StateMgr.getConstraintManager(); } // FIXME: Remove when we migrate over to just using ValueManager. BasicValueFactory& getBasicVals() { return StateMgr.getBasicVals(); } const BasicValueFactory& getBasicVals() const { return StateMgr.getBasicVals(); } ValueManager &getValueManager() { return ValMgr; } const ValueManager &getValueManager() const { return ValMgr; } // FIXME: Remove when we migrate over to just using ValueManager. SymbolManager& getSymbolManager() { return SymMgr; } const SymbolManager& getSymbolManager() const { return SymMgr; } protected: const GRState* GetState(NodeTy* N) { return N == EntryNode ? CleanedState : N->getState(); } public: const GRState* BindExpr(const GRState* St, Expr* Ex, SVal V) { return StateMgr.BindExpr(St, Ex, V); } const GRState* BindExpr(const GRState* St, const Expr* Ex, SVal V) { return BindExpr(St, const_cast<Expr*>(Ex), V); } protected: const GRState* BindBlkExpr(const GRState* St, Expr* Ex, SVal V) { return StateMgr.BindExpr(St, Ex, V, true, false); } const GRState* BindLoc(const GRState* St, Loc LV, SVal V) { return StateMgr.BindLoc(St, LV, V); } SVal GetSVal(const GRState* St, Stmt* Ex) { return StateMgr.GetSVal(St, Ex); } SVal GetSVal(const GRState* St, const Stmt* Ex) { return GetSVal(St, const_cast<Stmt*>(Ex)); } SVal GetBlkExprSVal(const GRState* St, Stmt* Ex) { return StateMgr.GetBlkExprSVal(St, Ex); } SVal GetSVal(const GRState* St, Loc LV, QualType T = QualType()) { return StateMgr.GetSVal(St, LV, T); } inline NonLoc MakeConstantVal(uint64_t X, Expr* Ex) { return NonLoc::MakeVal(getBasicVals(), X, Ex->getType()); } /// Assume - Create new state by assuming that a given expression /// is true or false. const GRState* Assume(const GRState* St, SVal Cond, bool Assumption, bool& isFeasible) { return StateMgr.Assume(St, Cond, Assumption, isFeasible); } const GRState* Assume(const GRState* St, Loc Cond, bool Assumption, bool& isFeasible) { return StateMgr.Assume(St, Cond, Assumption, isFeasible); } const GRState* AssumeInBound(const GRState* St, SVal Idx, SVal UpperBound, bool Assumption, bool& isFeasible) { return StateMgr.AssumeInBound(St, Idx, UpperBound, Assumption, isFeasible); } public: NodeTy* MakeNode(NodeSet& Dst, Stmt* S, NodeTy* Pred, const GRState* St, ProgramPoint::Kind K = ProgramPoint::PostStmtKind, const void *tag = 0); protected: /// Visit - Transfer function logic for all statements. Dispatches to /// other functions that handle specific kinds of statements. void Visit(Stmt* S, NodeTy* Pred, NodeSet& Dst); /// VisitLValue - Evaluate the lvalue of the expression. For example, if Ex is /// a DeclRefExpr, it evaluates to the MemRegionVal which represents its /// storage location. Note that not all kinds of expressions has lvalue. void VisitLValue(Expr* Ex, NodeTy* Pred, NodeSet& Dst); /// VisitArraySubscriptExpr - Transfer function for array accesses. void VisitArraySubscriptExpr(ArraySubscriptExpr* Ex, NodeTy* Pred, NodeSet& Dst, bool asLValue); /// VisitAsmStmt - Transfer function logic for inline asm. void VisitAsmStmt(AsmStmt* A, NodeTy* Pred, NodeSet& Dst); void VisitAsmStmtHelperOutputs(AsmStmt* A, AsmStmt::outputs_iterator I, AsmStmt::outputs_iterator E, NodeTy* Pred, NodeSet& Dst); void VisitAsmStmtHelperInputs(AsmStmt* A, AsmStmt::inputs_iterator I, AsmStmt::inputs_iterator E, NodeTy* Pred, NodeSet& Dst); /// VisitBinaryOperator - Transfer function logic for binary operators. void VisitBinaryOperator(BinaryOperator* B, NodeTy* Pred, NodeSet& Dst); /// VisitCall - Transfer function for function calls. void VisitCall(CallExpr* CE, NodeTy* Pred, CallExpr::arg_iterator AI, CallExpr::arg_iterator AE, NodeSet& Dst); void VisitCallRec(CallExpr* CE, NodeTy* Pred, CallExpr::arg_iterator AI, CallExpr::arg_iterator AE, NodeSet& Dst, const FunctionProtoType *, unsigned ParamIdx = 0); /// VisitCast - Transfer function logic for all casts (implicit and explicit). void VisitCast(Expr* CastE, Expr* Ex, NodeTy* Pred, NodeSet& Dst); /// VisitCastPointerToInteger - Transfer function (called by VisitCast) that /// handles pointer to integer casts and array to integer casts. void VisitCastPointerToInteger(SVal V, const GRState* state, QualType PtrTy, Expr* CastE, NodeTy* Pred, NodeSet& Dst); /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. void VisitCompoundLiteralExpr(CompoundLiteralExpr* CL, NodeTy* Pred, NodeSet& Dst, bool asLValue); /// VisitDeclRefExpr - Transfer function logic for DeclRefExprs. void VisitDeclRefExpr(DeclRefExpr* DR, NodeTy* Pred, NodeSet& Dst, bool asLValue); /// VisitDeclStmt - Transfer function logic for DeclStmts. void VisitDeclStmt(DeclStmt* DS, NodeTy* Pred, NodeSet& Dst); /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose void VisitGuardedExpr(Expr* Ex, Expr* L, Expr* R, NodeTy* Pred, NodeSet& Dst); void VisitInitListExpr(InitListExpr* E, NodeTy* Pred, NodeSet& Dst); /// VisitLogicalExpr - Transfer function logic for '&&', '||' void VisitLogicalExpr(BinaryOperator* B, NodeTy* Pred, NodeSet& Dst); /// VisitMemberExpr - Transfer function for member expressions. void VisitMemberExpr(MemberExpr* M, NodeTy* Pred, NodeSet& Dst,bool asLValue); /// VisitObjCIvarRefExpr - Transfer function logic for ObjCIvarRefExprs. void VisitObjCIvarRefExpr(ObjCIvarRefExpr* DR, NodeTy* Pred, NodeSet& Dst, bool asLValue); /// VisitObjCForCollectionStmt - Transfer function logic for /// ObjCForCollectionStmt. void VisitObjCForCollectionStmt(ObjCForCollectionStmt* S, NodeTy* Pred, NodeSet& Dst); void VisitObjCForCollectionStmtAux(ObjCForCollectionStmt* S, NodeTy* Pred, NodeSet& Dst, SVal ElementV); /// VisitObjCMessageExpr - Transfer function for ObjC message expressions. void VisitObjCMessageExpr(ObjCMessageExpr* ME, NodeTy* Pred, NodeSet& Dst); void VisitObjCMessageExprArgHelper(ObjCMessageExpr* ME, ObjCMessageExpr::arg_iterator I, ObjCMessageExpr::arg_iterator E, NodeTy* Pred, NodeSet& Dst); void VisitObjCMessageExprDispatchHelper(ObjCMessageExpr* ME, NodeTy* Pred, NodeSet& Dst); /// VisitReturnStmt - Transfer function logic for return statements. void VisitReturnStmt(ReturnStmt* R, NodeTy* Pred, NodeSet& Dst); /// VisitSizeOfAlignOfExpr - Transfer function for sizeof. void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr* Ex, NodeTy* Pred, NodeSet& Dst); /// VisitUnaryOperator - Transfer function logic for unary operators. void VisitUnaryOperator(UnaryOperator* B, NodeTy* Pred, NodeSet& Dst, bool asLValue); const GRState* CheckDivideZero(Expr* Ex, const GRState* St, NodeTy* Pred, SVal Denom); /// EvalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) /// with those assumptions. void EvalEagerlyAssume(NodeSet& Dst, NodeSet& Src, Expr *Ex); SVal EvalCast(SVal X, QualType CastT) { if (X.isUnknownOrUndef()) return X; if (isa<Loc>(X)) return getTF().EvalCast(*this, cast<Loc>(X), CastT); else return getTF().EvalCast(*this, cast<NonLoc>(X), CastT); } SVal EvalMinus(UnaryOperator* U, SVal X) { return X.isValid() ? getTF().EvalMinus(*this, U, cast<NonLoc>(X)) : X; } SVal EvalComplement(SVal X) { return X.isValid() ? getTF().EvalComplement(*this, cast<NonLoc>(X)) : X; } public: SVal EvalBinOp(BinaryOperator::Opcode Op, NonLoc L, NonLoc R, QualType T) { return R.isValid() ? getTF().DetermEvalBinOpNN(*this, Op, L, R, T) : R; } SVal EvalBinOp(BinaryOperator::Opcode Op, NonLoc L, SVal R, QualType T) { return R.isValid() ? getTF().DetermEvalBinOpNN(*this, Op, L, cast<NonLoc>(R), T) : R; } void EvalBinOp(ExplodedNodeSet<GRState>& Dst, Expr* Ex, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, ExplodedNode<GRState>* Pred, QualType T); void EvalBinOp(GRStateSet& OStates, const GRState* St, Expr* Ex, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, QualType T); SVal EvalBinOp(BinaryOperator::Opcode Op, SVal L, SVal R, QualType T); protected: void EvalCall(NodeSet& Dst, CallExpr* CE, SVal L, NodeTy* Pred); void EvalObjCMessageExpr(NodeSet& Dst, ObjCMessageExpr* ME, NodeTy* Pred) { assert (Builder && "GRStmtNodeBuilder must be defined."); getTF().EvalObjCMessageExpr(Dst, *this, *Builder, ME, Pred); } void EvalReturn(NodeSet& Dst, ReturnStmt* s, NodeTy* Pred); const GRState* MarkBranch(const GRState* St, Stmt* Terminator, bool branchTaken); /// EvalBind - Handle the semantics of binding a value to a specific location. /// This method is used by EvalStore, VisitDeclStmt, and others. void EvalBind(NodeSet& Dst, Expr* Ex, NodeTy* Pred, const GRState* St, SVal location, SVal Val); public: void EvalLoad(NodeSet& Dst, Expr* Ex, NodeTy* Pred, const GRState* St, SVal location, const void *tag = 0); NodeTy* EvalLocation(Stmt* Ex, NodeTy* Pred, const GRState* St, SVal location, const void *tag = 0); void EvalStore(NodeSet& Dst, Expr* E, NodeTy* Pred, const GRState* St, SVal TargetLV, SVal Val, const void *tag = 0); void EvalStore(NodeSet& Dst, Expr* E, Expr* StoreE, NodeTy* Pred, const GRState* St, SVal TargetLV, SVal Val, const void *tag = 0); }; } // end clang namespace #endif <file_sep>/tools/ccc/ccclib/Util.py def any_true(list, predicate): for i in list: if predicate(i): return True return False def any_false(list, predicate): return any_true(list, lambda x: not predicate(x)) def all_true(list, predicate): return not any_false(list, predicate) def all_false(list, predicate): return not any_true(list, predicate) def prependLines(prependStr, str): return ('\n'+prependStr).join(str.splitlines()) def pprint(object, useRepr=True): def recur(ob): return pprint(ob, useRepr) def wrapString(prefix, string, suffix): return '%s%s%s' % (prefix, prependLines(' ' * len(prefix), string), suffix) def pprintArgs(name, args): return wrapString(name + '(', ',\n'.join(map(recur,args)), ')') if isinstance(object, tuple): return wrapString('(', ',\n'.join(map(recur,object)), [')',',)'][len(object) == 1]) elif isinstance(object, list): return wrapString('[', ',\n'.join(map(recur,object)), ']') elif isinstance(object, set): return pprintArgs('set', list(object)) elif isinstance(object, dict): elts = [] for k,v in object.items(): kr = recur(k) vr = recur(v) elts.append('%s : %s' % (kr, prependLines(' ' * (3 + len(kr.splitlines()[-1])), vr))) return wrapString('{', ',\n'.join(elts), '}') else: if useRepr: return repr(object) return str(object) def prefixAndPPrint(prefix, object, useRepr=True): return prefix + prependLines(' '*len(prefix), pprint(object, useRepr)) <file_sep>/lib/Sema/SemaExpr.cpp //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for expressions. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Parse/DeclSpec.h" #include "clang/Parse/Designator.h" #include "clang/Parse/Scope.h" using namespace clang; /// \brief Determine whether the use of this declaration is valid, and /// emit any corresponding diagnostics. /// /// This routine diagnoses various problems with referencing /// declarations that can occur when using a declaration. For example, /// it might warn if a deprecated or unavailable declaration is being /// used, or produce an error (and return true) if a C++0x deleted /// function is being used. /// /// \returns true if there was an error (this declaration cannot be /// referenced), false otherwise. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { // See if the decl is deprecated. if (D->getAttr<DeprecatedAttr>()) { // Implementing deprecated stuff requires referencing deprecated // stuff. Don't warn if we are implementing a deprecated // construct. bool isSilenced = false; if (NamedDecl *ND = getCurFunctionOrMethodDecl()) { // If this reference happens *in* a deprecated function or method, don't // warn. isSilenced = ND->getAttr<DeprecatedAttr>(); // If this is an Objective-C method implementation, check to see if the // method was deprecated on the declaration, not the definition. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) { // The semantic decl context of a ObjCMethodDecl is the // ObjCImplementationDecl. if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(MD->getParent())) { MD = Impl->getClassInterface()->getMethod(Context, MD->getSelector(), MD->isInstanceMethod()); isSilenced |= MD && MD->getAttr<DeprecatedAttr>(); } } } if (!isSilenced) Diag(Loc, diag::warn_deprecated) << D->getDeclName(); } // See if this is a deleted function. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isDeleted()) { Diag(Loc, diag::err_deleted_function_use); Diag(D->getLocation(), diag::note_unavailable_here) << true; return true; } } // See if the decl is unavailable if (D->getAttr<UnavailableAttr>()) { Diag(Loc, diag::warn_unavailable) << D->getDeclName(); Diag(D->getLocation(), diag::note_unavailable_here) << 0; } return false; } SourceRange Sema::getExprRange(ExprTy *E) const { Expr *Ex = (Expr *)E; return Ex? Ex->getSourceRange() : SourceRange(); } //===----------------------------------------------------------------------===// // Standard Promotions and Conversions //===----------------------------------------------------------------------===// /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). void Sema::DefaultFunctionArrayConversion(Expr *&E) { QualType Ty = E->getType(); assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); if (Ty->isFunctionType()) ImpCastExprToType(E, Context.getPointerType(Ty)); else if (Ty->isArrayType()) { // In C90 mode, arrays only promote to pointers if the array expression is // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has // type 'array of type' is converted to an expression that has type 'pointer // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression // that has type 'array of type' ...". The relevant change is "an lvalue" // (C90) to "an expression" (C99). // // C++ 4.2p1: // An lvalue or rvalue of type "array of N T" or "array of unknown bound of // T" can be converted to an rvalue of type "pointer to T". // if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLvalue(Context) == Expr::LV_Valid) ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); } } /// UsualUnaryConversions - Performs various conversions that are common to most /// operators (C99 6.3). The conversions of array and function types are /// sometimes surpressed. For example, the array->pointer conversion doesn't /// apply if the array is an argument to the sizeof or address (&) operators. /// In these instances, this routine should *not* be called. Expr *Sema::UsualUnaryConversions(Expr *&Expr) { QualType Ty = Expr->getType(); assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2 ImpCastExprToType(Expr, Context.IntTy); else DefaultFunctionArrayConversion(Expr); return Expr; } /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that /// do not have a prototype. Arguments that have type float are promoted to /// double. All other argument types are converted by UsualUnaryConversions(). void Sema::DefaultArgumentPromotion(Expr *&Expr) { QualType Ty = Expr->getType(); assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); // If this is a 'float' (CVR qualified or typedef) promote to double. if (const BuiltinType *BT = Ty->getAsBuiltinType()) if (BT->getKind() == BuiltinType::Float) return ImpCastExprToType(Expr, Context.DoubleTy); UsualUnaryConversions(Expr); } /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but /// will warn if the resulting type is not a POD type, and rejects ObjC /// interfaces passed by value. This returns true if the argument type is /// completely illegal. bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) { DefaultArgumentPromotion(Expr); if (Expr->getType()->isObjCInterfaceType()) { Diag(Expr->getLocStart(), diag::err_cannot_pass_objc_interface_to_vararg) << Expr->getType() << CT; return true; } if (!Expr->getType()->isPODType()) Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg) << Expr->getType() << CT; return false; } /// UsualArithmeticConversions - Performs various conversions that are common to /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this /// routine returns the first non-arithmetic type found. The client is /// responsible for emitting appropriate error diagnostics. /// FIXME: verify the conversion rules for "complex int" are consistent with /// GCC. QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, bool isCompAssign) { if (!isCompAssign) UsualUnaryConversions(lhsExpr); UsualUnaryConversions(rhsExpr); // For conversion purposes, we ignore any qualifiers. // For example, "const float" and "float" are equivalent. QualType lhs = Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); QualType rhs = Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); // If both types are identical, no conversion is needed. if (lhs == rhs) return lhs; // If either side is a non-arithmetic type (e.g. a pointer), we are done. // The caller can deal with this (e.g. pointer + int). if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) return lhs; QualType destType = UsualArithmeticConversionsType(lhs, rhs); if (!isCompAssign) ImpCastExprToType(lhsExpr, destType); ImpCastExprToType(rhsExpr, destType); return destType; } QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { // Perform the usual unary conversions. We do this early so that // integral promotions to "int" can allow us to exit early, in the // lhs == rhs check. Also, for conversion purposes, we ignore any // qualifiers. For example, "const float" and "float" are // equivalent. if (lhs->isPromotableIntegerType()) lhs = Context.IntTy; else lhs = lhs.getUnqualifiedType(); if (rhs->isPromotableIntegerType()) rhs = Context.IntTy; else rhs = rhs.getUnqualifiedType(); // If both types are identical, no conversion is needed. if (lhs == rhs) return lhs; // If either side is a non-arithmetic type (e.g. a pointer), we are done. // The caller can deal with this (e.g. pointer + int). if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) return lhs; // At this point, we have two different arithmetic types. // Handle complex types first (C99 6.3.1.8p1). if (lhs->isComplexType() || rhs->isComplexType()) { // if we have an integer operand, the result is the complex type. if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { // convert the rhs to the lhs complex type. return lhs; } if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { // convert the lhs to the rhs complex type. return rhs; } // This handles complex/complex, complex/float, or float/complex. // When both operands are complex, the shorter operand is converted to the // type of the longer, and that is the type of the result. This corresponds // to what is done when combining two real floating-point operands. // The fun begins when size promotion occur across type domains. // From H&S 6.3.4: When one operand is complex and the other is a real // floating-point type, the less precise type is converted, within it's // real or complex domain, to the precision of the other type. For example, // when combining a "long double" with a "double _Complex", the // "double _Complex" is promoted to "long double _Complex". int result = Context.getFloatingTypeOrder(lhs, rhs); if (result > 0) { // The left side is bigger, convert rhs. rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); } else if (result < 0) { // The right side is bigger, convert lhs. lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); } // At this point, lhs and rhs have the same rank/size. Now, make sure the // domains match. This is a requirement for our implementation, C99 // does not require this promotion. if (lhs != rhs) { // Domains don't match, we have complex/float mix. if (lhs->isRealFloatingType()) { // handle "double, _Complex double". return rhs; } else { // handle "_Complex double, double". return lhs; } } return lhs; // The domain/size match exactly. } // Now handle "real" floating types (i.e. float, double, long double). if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { // if we have an integer operand, the result is the real floating type. if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type. return lhs; } if (rhs->isComplexIntegerType()) { // convert rhs to the complex floating point type. return Context.getComplexType(lhs); } if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type. return rhs; } if (lhs->isComplexIntegerType()) { // convert lhs to the complex floating point type. return Context.getComplexType(rhs); } // We have two real floating types, float/complex combos were handled above. // Convert the smaller operand to the bigger result. int result = Context.getFloatingTypeOrder(lhs, rhs); if (result > 0) // convert the rhs return lhs; assert(result < 0 && "illegal float comparison"); return rhs; // convert the lhs } if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { // Handle GCC complex int extension. const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); if (lhsComplexInt && rhsComplexInt) { if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), rhsComplexInt->getElementType()) >= 0) return lhs; // convert the rhs return rhs; } else if (lhsComplexInt && rhs->isIntegerType()) { // convert the rhs to the lhs complex type. return lhs; } else if (rhsComplexInt && lhs->isIntegerType()) { // convert the lhs to the rhs complex type. return rhs; } } // Finally, we have two differing integer types. // The rules for this case are in C99 6.3.1.8 int compare = Context.getIntegerTypeOrder(lhs, rhs); bool lhsSigned = lhs->isSignedIntegerType(), rhsSigned = rhs->isSignedIntegerType(); QualType destType; if (lhsSigned == rhsSigned) { // Same signedness; use the higher-ranked type destType = compare >= 0 ? lhs : rhs; } else if (compare != (lhsSigned ? 1 : -1)) { // The unsigned type has greater than or equal rank to the // signed type, so use the unsigned type destType = lhsSigned ? rhs : lhs; } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { // The two types are different widths; if we are here, that // means the signed type is larger than the unsigned type, so // use the signed type. destType = lhsSigned ? lhs : rhs; } else { // The signed type is higher-ranked than the unsigned type, // but isn't actually any bigger (like unsigned int and long // on most 32-bit systems). Use the unsigned type corresponding // to the signed type. destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); } return destType; } //===----------------------------------------------------------------------===// // Semantic Analysis for various Expression Types //===----------------------------------------------------------------------===// /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from /// multiple tokens. However, the common case is that StringToks points to one /// string. /// Action::OwningExprResult Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { assert(NumStringToks && "Must have at least one string!"); StringLiteralParser Literal(StringToks, NumStringToks, PP); if (Literal.hadError) return ExprError(); llvm::SmallVector<SourceLocation, 4> StringTokLocs; for (unsigned i = 0; i != NumStringToks; ++i) StringTokLocs.push_back(StringToks[i].getLocation()); QualType StrTy = Context.CharTy; if (Literal.AnyWide) StrTy = Context.getWCharType(); if (Literal.Pascal) StrTy = Context.UnsignedCharTy; // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). if (getLangOptions().CPlusPlus) StrTy.addConst(); // Get an array type for the string, according to C99 6.4.5. This includes // the nul terminator character as well as the string length for pascal // strings. StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Literal.GetNumStringChars()+1), ArrayType::Normal, 0); // Pass &StringTokLocs[0], StringTokLocs.size() to factory! return Owned(StringLiteral::Create(Context, Literal.GetString(), Literal.GetStringLength(), Literal.AnyWide, StrTy, &StringTokLocs[0], StringTokLocs.size())); } /// ShouldSnapshotBlockValueReference - Return true if a reference inside of /// CurBlock to VD should cause it to be snapshotted (as we do for auto /// variables defined outside the block) or false if this is not needed (e.g. /// for values inside the block or for globals). /// /// FIXME: This will create BlockDeclRefExprs for global variables, /// function references, etc which is suboptimal :) and breaks /// things like "integer constant expression" tests. static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock, ValueDecl *VD) { // If the value is defined inside the block, we couldn't snapshot it even if // we wanted to. if (CurBlock->TheDecl == VD->getDeclContext()) return false; // If this is an enum constant or function, it is constant, don't snapshot. if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) return false; // If this is a reference to an extern, static, or global variable, no need to // snapshot it. // FIXME: What about 'const' variables in C++? if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) return Var->hasLocalStorage(); return true; } /// ActOnIdentifierExpr - The parser read an identifier in expression context, /// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this /// identifier is used in a function call context. /// SS is only used for a C++ qualified-id (foo::bar) to indicate the /// class or namespace that the identifier must be a member of. Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, IdentifierInfo &II, bool HasTrailingLParen, const CXXScopeSpec *SS, bool isAddressOfOperand) { return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS, isAddressOfOperand); } /// BuildDeclRefExpr - Build either a DeclRefExpr or a /// QualifiedDeclRefExpr based on whether or not SS is a /// nested-name-specifier. DeclRefExpr * Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc, bool TypeDependent, bool ValueDependent, const CXXScopeSpec *SS) { if (SS && !SS->isEmpty()) { return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent, SS->getRange(), static_cast<NestedNameSpecifier *>(SS->getScopeRep())); } else return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent); } /// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or /// variable corresponding to the anonymous union or struct whose type /// is Record. static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context, RecordDecl *Record) { assert(Record->isAnonymousStructOrUnion() && "Record must be an anonymous struct or union!"); // FIXME: Once Decls are directly linked together, this will // be an O(1) operation rather than a slow walk through DeclContext's // vector (which itself will be eliminated). DeclGroups might make // this even better. DeclContext *Ctx = Record->getDeclContext(); for (DeclContext::decl_iterator D = Ctx->decls_begin(Context), DEnd = Ctx->decls_end(Context); D != DEnd; ++D) { if (*D == Record) { // The object for the anonymous struct/union directly // follows its type in the list of declarations. ++D; assert(D != DEnd && "Missing object for anonymous record"); assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed"); return *D; } } assert(false && "Missing object for anonymous record"); return 0; } /// \brief Given a field that represents a member of an anonymous /// struct/union, build the path from that field's context to the /// actual member. /// /// Construct the sequence of field member references we'll have to /// perform to get to the field in the anonymous union/struct. The /// list of members is built from the field outward, so traverse it /// backwards to go from an object in the current context to the field /// we found. /// /// \returns The variable from which the field access should begin, /// for an anonymous struct/union that is not a member of another /// class. Otherwise, returns NULL. VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field, llvm::SmallVectorImpl<FieldDecl *> &Path) { assert(Field->getDeclContext()->isRecord() && cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() && "Field must be stored inside an anonymous struct or union"); Path.push_back(Field); VarDecl *BaseObject = 0; DeclContext *Ctx = Field->getDeclContext(); do { RecordDecl *Record = cast<RecordDecl>(Ctx); Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record); if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) Path.push_back(AnonField); else { BaseObject = cast<VarDecl>(AnonObject); break; } Ctx = Ctx->getParent(); } while (Ctx->isRecord() && cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); return BaseObject; } Sema::OwningExprResult Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, FieldDecl *Field, Expr *BaseObjectExpr, SourceLocation OpLoc) { llvm::SmallVector<FieldDecl *, 4> AnonFields; VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field, AnonFields); // Build the expression that refers to the base object, from // which we will build a sequence of member references to each // of the anonymous union objects and, eventually, the field we // found via name lookup. bool BaseObjectIsPointer = false; unsigned ExtraQuals = 0; if (BaseObject) { // BaseObject is an anonymous struct/union variable (and is, // therefore, not part of another non-anonymous record). if (BaseObjectExpr) BaseObjectExpr->Destroy(Context); BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), SourceLocation()); ExtraQuals = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers(); } else if (BaseObjectExpr) { // The caller provided the base object expression. Determine // whether its a pointer and whether it adds any qualifiers to the // anonymous struct/union fields we're looking into. QualType ObjectType = BaseObjectExpr->getType(); if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) { BaseObjectIsPointer = true; ObjectType = ObjectPtr->getPointeeType(); } ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers(); } else { // We've found a member of an anonymous struct/union that is // inside a non-anonymous struct/union, so in a well-formed // program our base object expression is "this". if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { if (!MD->isStatic()) { QualType AnonFieldType = Context.getTagDeclType( cast<RecordDecl>(AnonFields.back()->getDeclContext())); QualType ThisType = Context.getTagDeclType(MD->getParent()); if ((Context.getCanonicalType(AnonFieldType) == Context.getCanonicalType(ThisType)) || IsDerivedFrom(ThisType, AnonFieldType)) { // Our base object expression is "this". BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(), MD->getThisType(Context)); BaseObjectIsPointer = true; } } else { return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) << Field->getDeclName()); } ExtraQuals = MD->getTypeQualifiers(); } if (!BaseObjectExpr) return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) << Field->getDeclName()); } // Build the implicit member references to the field of the // anonymous struct/union. Expr *Result = BaseObjectExpr; for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); FI != FIEnd; ++FI) { QualType MemberType = (*FI)->getType(); if (!(*FI)->isMutable()) { unsigned combinedQualifiers = MemberType.getCVRQualifiers() | ExtraQuals; MemberType = MemberType.getQualifiedType(combinedQualifiers); } Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, OpLoc, MemberType); BaseObjectIsPointer = false; ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers(); } return Owned(Result); } /// ActOnDeclarationNameExpr - The parser has read some kind of name /// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine /// performs lookup on that name and returns an expression that refers /// to that name. This routine isn't directly called from the parser, /// because the parser doesn't know about DeclarationName. Rather, /// this routine is called by ActOnIdentifierExpr, /// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr, /// which form the DeclarationName from the corresponding syntactic /// forms. /// /// HasTrailingLParen indicates whether this identifier is used in a /// function call context. LookupCtx is only used for a C++ /// qualified-id (foo::bar) to indicate the class or namespace that /// the identifier must be a member of. /// /// isAddressOfOperand means that this expression is the direct operand /// of an address-of operator. This matters because this is the only /// situation where a qualified name referencing a non-static member may /// appear outside a member function of this class. Sema::OwningExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc, DeclarationName Name, bool HasTrailingLParen, const CXXScopeSpec *SS, bool isAddressOfOperand) { // Could be enum-constant, value decl, instance variable, etc. if (SS && SS->isInvalid()) return ExprError(); // C++ [temp.dep.expr]p3: // An id-expression is type-dependent if it contains: // -- a nested-name-specifier that contains a class-name that // names a dependent type. if (SS && isDependentScopeSpecifier(*SS)) { return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy, Loc, SS->getRange(), static_cast<NestedNameSpecifier *>(SS->getScopeRep()))); } LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName, false, true, Loc); NamedDecl *D = 0; if (Lookup.isAmbiguous()) { DiagnoseAmbiguousLookup(Lookup, Name, Loc, SS && SS->isSet() ? SS->getRange() : SourceRange()); return ExprError(); } else D = Lookup.getAsDecl(); // If this reference is in an Objective-C method, then ivar lookup happens as // well. IdentifierInfo *II = Name.getAsIdentifierInfo(); if (II && getCurMethodDecl()) { // There are two cases to handle here. 1) scoped lookup could have failed, // in which case we should look for an ivar. 2) scoped lookup could have // found a decl, but that decl is outside the current instance method (i.e. // a global variable). In these two cases, we do a lookup for an ivar with // this name, if the lookup sucedes, we replace it our current decl. if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) { ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); ObjCInterfaceDecl *ClassDeclared; if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II, ClassDeclared)) { // Check if referencing a field with __attribute__((deprecated)). if (DiagnoseUseOfDecl(IV, Loc)) return ExprError(); bool IsClsMethod = getCurMethodDecl()->isClassMethod(); // If a class method attemps to use a free standing ivar, this is // an error. if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod()) return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) << IV->getDeclName()); // If a class method uses a global variable, even if an ivar with // same name exists, use the global. if (!IsClsMethod) { if (IV->getAccessControl() == ObjCIvarDecl::Private && ClassDeclared != IFace) Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); // FIXME: This should use a new expr for a direct reference, don't turn // this into Self->ivar, just return a BareIVarExpr or something. IdentifierInfo &II = Context.Idents.get("self"); OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(), Loc, static_cast<Expr*>(SelfExpr.release()), true, true); Context.setFieldDecl(IFace, IV, MRef); return Owned(MRef); } } } else if (getCurMethodDecl()->isInstanceMethod()) { // We should warn if a local variable hides an ivar. ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); ObjCInterfaceDecl *ClassDeclared; if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II, ClassDeclared)) { if (IV->getAccessControl() != ObjCIvarDecl::Private || IFace == ClassDeclared) Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName(); } } // Needed to implement property "super.method" notation. if (D == 0 && II->isStr("super")) { QualType T; if (getCurMethodDecl()->isInstanceMethod()) T = Context.getPointerType(Context.getObjCInterfaceType( getCurMethodDecl()->getClassInterface())); else T = Context.getObjCClassType(); return Owned(new (Context) ObjCSuperExpr(Loc, T)); } } // Determine whether this name might be a candidate for // argument-dependent lookup. bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) && HasTrailingLParen; if (ADL && D == 0) { // We've seen something of the form // // identifier( // // and we did not find any entity by the name // "identifier". However, this identifier is still subject to // argument-dependent lookup, so keep track of the name. return Owned(new (Context) UnresolvedFunctionNameExpr(Name, Context.OverloadTy, Loc)); } if (D == 0) { // Otherwise, this could be an implicitly declared function reference (legal // in C90, extension in C99). if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) // Not in C++. D = ImplicitlyDefineFunction(Loc, *II, S); else { // If this name wasn't predeclared and if this is not a function call, // diagnose the problem. if (SS && !SS->isEmpty()) return ExprError(Diag(Loc, diag::err_typecheck_no_member) << Name << SS->getRange()); else if (Name.getNameKind() == DeclarationName::CXXOperatorName || Name.getNameKind() == DeclarationName::CXXConversionFunctionName) return ExprError(Diag(Loc, diag::err_undeclared_use) << Name.getAsString()); else return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name); } } // If this is an expression of the form &Class::member, don't build an // implicit member ref, because we want a pointer to the member in general, // not any specific instance's member. if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) { DeclContext *DC = computeDeclContext(*SS); if (D && isa<CXXRecordDecl>(DC)) { QualType DType; if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { DType = FD->getType().getNonReferenceType(); } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { DType = Method->getType(); } else if (isa<OverloadedFunctionDecl>(D)) { DType = Context.OverloadTy; } // Could be an inner type. That's diagnosed below, so ignore it here. if (!DType.isNull()) { // The pointer is type- and value-dependent if it points into something // dependent. bool Dependent = false; for (; DC; DC = DC->getParent()) { // FIXME: could stop early at namespace scope. if (DC->isRecord()) { CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); if (Context.getTypeDeclType(Record)->isDependentType()) { Dependent = true; break; } } } return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS)); } } } // We may have found a field within an anonymous union or struct // (C++ [class.union]). if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) return BuildAnonymousStructUnionMemberReference(Loc, FD); if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { if (!MD->isStatic()) { // C++ [class.mfct.nonstatic]p2: // [...] if name lookup (3.4.1) resolves the name in the // id-expression to a nonstatic nontype member of class X or of // a base class of X, the id-expression is transformed into a // class member access expression (5.2.5) using (*this) (9.3.2) // as the postfix-expression to the left of the '.' operator. DeclContext *Ctx = 0; QualType MemberType; if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { Ctx = FD->getDeclContext(); MemberType = FD->getType(); if (const ReferenceType *RefType = MemberType->getAsReferenceType()) MemberType = RefType->getPointeeType(); else if (!FD->isMutable()) { unsigned combinedQualifiers = MemberType.getCVRQualifiers() | MD->getTypeQualifiers(); MemberType = MemberType.getQualifiedType(combinedQualifiers); } } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { if (!Method->isStatic()) { Ctx = Method->getParent(); MemberType = Method->getType(); } } else if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) { for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), FuncEnd = Ovl->function_end(); Func != FuncEnd; ++Func) { if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func)) if (!DMethod->isStatic()) { Ctx = Ovl->getDeclContext(); MemberType = Context.OverloadTy; break; } } } if (Ctx && Ctx->isRecord()) { QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx)); QualType ThisType = Context.getTagDeclType(MD->getParent()); if ((Context.getCanonicalType(CtxType) == Context.getCanonicalType(ThisType)) || IsDerivedFrom(ThisType, CtxType)) { // Build the implicit member access expression. Expr *This = new (Context) CXXThisExpr(SourceLocation(), MD->getThisType(Context)); return Owned(new (Context) MemberExpr(This, true, D, SourceLocation(), MemberType)); } } } } if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { if (MD->isStatic()) // "invalid use of member 'x' in static member function" return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) << FD->getDeclName()); } // Any other ways we could have found the field in a well-formed // program would have been turned into implicit member expressions // above. return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) << FD->getDeclName()); } if (isa<TypedefDecl>(D)) return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name); if (isa<ObjCInterfaceDecl>(D)) return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name); if (isa<NamespaceDecl>(D)) return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name); // Make the DeclRefExpr or BlockDeclRefExpr for the decl. if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, false, false, SS)); else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc, false, false, SS)); ValueDecl *VD = cast<ValueDecl>(D); // Check whether this declaration can be used. Note that we suppress // this check when we're going to perform argument-dependent lookup // on this function name, because this might not be the function // that overload resolution actually selects. if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc)) return ExprError(); if (VarDecl *Var = dyn_cast<VarDecl>(VD)) { // Warn about constructs like: // if (void *X = foo()) { ... } else { X }. // In the else block, the pointer is always false. if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) { Scope *CheckS = S; while (CheckS) { if (CheckS->isWithinElse() && CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) { if (Var->getType()->isBooleanType()) ExprError(Diag(Loc, diag::warn_value_always_false) << Var->getDeclName()); else ExprError(Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName()); break; } // Move up one more control parent to check again. CheckS = CheckS->getControlParent(); if (CheckS) CheckS = CheckS->getParent(); } } } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) { if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { // C99 DR 316 says that, if a function type comes from a // function definition (without a prototype), that type is only // used for checking compatibility. Therefore, when referencing // the function, we pretend that we don't have the full function // type. QualType T = Func->getType(); QualType NoProtoType = T; if (const FunctionProtoType *Proto = T->getAsFunctionProtoType()) NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType()); return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS)); } } // Only create DeclRefExpr's for valid Decl's. if (VD->isInvalidDecl()) return ExprError(); // If the identifier reference is inside a block, and it refers to a value // that is outside the block, create a BlockDeclRefExpr instead of a // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when // the block is formed. // // We do not do this for things like enum constants, global variables, etc, // as they do not get snapshotted. // if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) { // Blocks that have these can't be constant. CurBlock->hasBlockDeclRefExprs = true; QualType ExprTy = VD->getType().getNonReferenceType(); // The BlocksAttr indicates the variable is bound by-reference. if (VD->getAttr<BlocksAttr>()) return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true)); // Variable will be bound by-copy, make it const within the closure. ExprTy.addConst(); return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false)); } // If this reference is not in a block or if the referenced variable is // within the block, create a normal DeclRefExpr. bool TypeDependent = false; bool ValueDependent = false; if (getLangOptions().CPlusPlus) { // C++ [temp.dep.expr]p3: // An id-expression is type-dependent if it contains: // - an identifier that was declared with a dependent type, if (VD->getType()->isDependentType()) TypeDependent = true; // - FIXME: a template-id that is dependent, // - a conversion-function-id that specifies a dependent type, else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && Name.getCXXNameType()->isDependentType()) TypeDependent = true; // - a nested-name-specifier that contains a class-name that // names a dependent type. else if (SS && !SS->isEmpty()) { for (DeclContext *DC = computeDeclContext(*SS); DC; DC = DC->getParent()) { // FIXME: could stop early at namespace scope. if (DC->isRecord()) { CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); if (Context.getTypeDeclType(Record)->isDependentType()) { TypeDependent = true; break; } } } } // C++ [temp.dep.constexpr]p2: // // An identifier is value-dependent if it is: // - a name declared with a dependent type, if (TypeDependent) ValueDependent = true; // - the name of a non-type template parameter, else if (isa<NonTypeTemplateParmDecl>(VD)) ValueDependent = true; // - a constant with integral or enumeration type and is // initialized with an expression that is value-dependent // (FIXME!). } return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, TypeDependent, ValueDependent, SS)); } Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { PredefinedExpr::IdentType IT; switch (Kind) { default: assert(0 && "Unknown simple primary expr!"); case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; } // Pre-defined identifiers are of type char[x], where x is the length of the // string. unsigned Length; if (FunctionDecl *FD = getCurFunctionDecl()) Length = FD->getIdentifier()->getLength(); else if (ObjCMethodDecl *MD = getCurMethodDecl()) Length = MD->getSynthesizedMethodSize(); else { Diag(Loc, diag::ext_predef_outside_function); // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0; } llvm::APInt LengthI(32, Length + 1); QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); } Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) { llvm::SmallString<16> CharBuffer; CharBuffer.resize(Tok.getLength()); const char *ThisTokBegin = &CharBuffer[0]; unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, Tok.getLocation(), PP); if (Literal.hadError()) return ExprError(); QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; return Owned(new (Context) CharacterLiteral(Literal.getValue(), Literal.isWide(), type, Tok.getLocation())); } Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) { // Fast path for a single digit (which is quite common). A single digit // cannot have a trigraph, escaped newline, radix prefix, or type suffix. if (Tok.getLength() == 1) { const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); unsigned IntSize = Context.Target.getIntWidth(); return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'), Context.IntTy, Tok.getLocation())); } llvm::SmallString<512> IntegerBuffer; // Add padding so that NumericLiteralParser can overread by one character. IntegerBuffer.resize(Tok.getLength()+1); const char *ThisTokBegin = &IntegerBuffer[0]; // Get the spelling of the token, which eliminates trigraphs, etc. unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, Tok.getLocation(), PP); if (Literal.hadError) return ExprError(); Expr *Res; if (Literal.isFloatingLiteral()) { QualType Ty; if (Literal.isFloat) Ty = Context.FloatTy; else if (!Literal.isLong) Ty = Context.DoubleTy; else Ty = Context.LongDoubleTy; const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); // isExact will be set by GetFloatValue(). bool isExact = false; Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact, Ty, Tok.getLocation()); } else if (!Literal.isIntegerLiteral()) { return ExprError(); } else { QualType Ty; // long long is a C99 feature. if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && Literal.isLongLong) Diag(Tok.getLocation(), diag::ext_longlong); // Get the value in the widest-possible width. llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); if (Literal.GetIntegerValue(ResultVal)) { // If this value didn't fit into uintmax_t, warn and force to ull. Diag(Tok.getLocation(), diag::warn_integer_too_large); Ty = Context.UnsignedLongLongTy; assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && "long long is not intmax_t?"); } else { // If this value fits into a ULL, try to figure out what else it fits into // according to the rules of C99 6.4.4.1p5. // Octal, Hexadecimal, and integers with a U suffix are allowed to // be an unsigned int. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; // Check from smallest to largest, picking the smallest type we can. unsigned Width = 0; if (!Literal.isLong && !Literal.isLongLong) { // Are int/unsigned possibilities? unsigned IntSize = Context.Target.getIntWidth(); // Does it fit in a unsigned int? if (ResultVal.isIntN(IntSize)) { // Does it fit in a signed int? if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) Ty = Context.IntTy; else if (AllowUnsigned) Ty = Context.UnsignedIntTy; Width = IntSize; } } // Are long/unsigned long possibilities? if (Ty.isNull() && !Literal.isLongLong) { unsigned LongSize = Context.Target.getLongWidth(); // Does it fit in a unsigned long? if (ResultVal.isIntN(LongSize)) { // Does it fit in a signed long? if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) Ty = Context.LongTy; else if (AllowUnsigned) Ty = Context.UnsignedLongTy; Width = LongSize; } } // Finally, check long long if needed. if (Ty.isNull()) { unsigned LongLongSize = Context.Target.getLongLongWidth(); // Does it fit in a unsigned long long? if (ResultVal.isIntN(LongLongSize)) { // Does it fit in a signed long long? if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) Ty = Context.LongLongTy; else if (AllowUnsigned) Ty = Context.UnsignedLongLongTy; Width = LongLongSize; } } // If we still couldn't decide a type, we probably have something that // does not fit in a signed long long, but has no U suffix. if (Ty.isNull()) { Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); Ty = Context.UnsignedLongLongTy; Width = Context.Target.getLongLongWidth(); } if (ResultVal.getBitWidth() != Width) ResultVal.trunc(Width); } Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation()); } // If this is an imaginary literal, create the ImaginaryLiteral wrapper. if (Literal.isImaginary) Res = new (Context) ImaginaryLiteral(Res, Context.getComplexType(Res->getType())); return Owned(Res); } Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, ExprArg Val) { Expr *E = (Expr *)Val.release(); assert((E != 0) && "ActOnParenExpr() missing expr"); return Owned(new (Context) ParenExpr(L, R, E)); } /// The UsualUnaryConversions() function is *not* called by this routine. /// See C99 6.3.2.1p[2-4] for more details. bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, SourceLocation OpLoc, const SourceRange &ExprRange, bool isSizeof) { if (exprType->isDependentType()) return false; // C99 6.5.3.4p1: if (isa<FunctionType>(exprType)) { // alignof(function) is allowed. if (isSizeof) Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; return false; } if (exprType->isVoidType()) { Diag(OpLoc, diag::ext_sizeof_void_type) << (isSizeof ? "sizeof" : "__alignof") << ExprRange; return false; } return RequireCompleteType(OpLoc, exprType, isSizeof ? diag::err_sizeof_incomplete_type : diag::err_alignof_incomplete_type, ExprRange); } bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc, const SourceRange &ExprRange) { E = E->IgnoreParens(); // alignof decl is always ok. if (isa<DeclRefExpr>(E)) return false; // Cannot know anything else if the expression is dependent. if (E->isTypeDependent()) return false; if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { if (FD->isBitField()) { Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; return true; } // Other fields are ok. return false; } } return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); } /// \brief Build a sizeof or alignof expression given a type operand. Action::OwningExprResult Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc, bool isSizeOf, SourceRange R) { if (T.isNull()) return ExprError(); if (!T->isDependentType() && CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf)) return ExprError(); // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T, Context.getSizeType(), OpLoc, R.getEnd())); } /// \brief Build a sizeof or alignof expression given an expression /// operand. Action::OwningExprResult Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc, bool isSizeOf, SourceRange R) { // Verify that the operand is valid. bool isInvalid = false; if (E->isTypeDependent()) { // Delay type-checking for type-dependent expressions. } else if (!isSizeOf) { isInvalid = CheckAlignOfExpr(E, OpLoc, R); } else if (E->isBitField()) { // C99 6.5.3.4p1. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; isInvalid = true; } else { isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true); } if (isInvalid) return ExprError(); // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E, Context.getSizeType(), OpLoc, R.getEnd())); } /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and /// the same for @c alignof and @c __alignof /// Note that the ArgRange is invalid if isType is false. Action::OwningExprResult Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, void *TyOrEx, const SourceRange &ArgRange) { // If error parsing type, ignore. if (TyOrEx == 0) return ExprError(); if (isType) { QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx); return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange); } // Get the end location. Expr *ArgEx = (Expr *)TyOrEx; Action::OwningExprResult Result = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange()); if (Result.isInvalid()) DeleteExpr(ArgEx); return move(Result); } QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { if (V->isTypeDependent()) return Context.DependentTy; DefaultFunctionArrayConversion(V); // These operators return the element type of a complex type. if (const ComplexType *CT = V->getType()->getAsComplexType()) return CT->getElementType(); // Otherwise they pass through real integer and floating point types here. if (V->getType()->isArithmeticType()) return V->getType(); // Reject anything else. Diag(Loc, diag::err_realimag_invalid_type) << V->getType() << (isReal ? "__real" : "__imag"); return QualType(); } Action::OwningExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, ExprArg Input) { Expr *Arg = (Expr *)Input.get(); UnaryOperator::Opcode Opc; switch (Kind) { default: assert(0 && "Unknown unary op!"); case tok::plusplus: Opc = UnaryOperator::PostInc; break; case tok::minusminus: Opc = UnaryOperator::PostDec; break; } if (getLangOptions().CPlusPlus && (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) { // Which overloaded operator? OverloadedOperatorKind OverOp = (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus; // C++ [over.inc]p1: // // [...] If the function is a member function with one // parameter (which shall be of type int) or a non-member // function with two parameters (the second of which shall be // of type int), it defines the postfix increment operator ++ // for objects of that type. When the postfix increment is // called as a result of using the ++ operator, the int // argument will have value zero. Expr *Args[2] = { Arg, new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0, /*isSigned=*/true), Context.IntTy, SourceLocation()) }; // Build the candidate set for overloading OverloadCandidateSet CandidateSet; AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet); // Perform overload resolution. OverloadCandidateSet::iterator Best; switch (BestViableFunction(CandidateSet, Best)) { case OR_Success: { // We found a built-in operator or an overloaded operator. FunctionDecl *FnDecl = Best->Function; if (FnDecl) { // We matched an overloaded operator. Build a call to that // operator. // Convert the arguments. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { if (PerformObjectArgumentInitialization(Arg, Method)) return ExprError(); } else { // Convert the arguments. if (PerformCopyInitialization(Arg, FnDecl->getParamDecl(0)->getType(), "passing")) return ExprError(); } // Determine the result type QualType ResultTy = FnDecl->getType()->getAsFunctionType()->getResultType(); ResultTy = ResultTy.getNonReferenceType(); // Build the actual expression node. Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), SourceLocation()); UsualUnaryConversions(FnExpr); Input.release(); return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr, Args, 2, ResultTy, OpLoc)); } else { // We matched a built-in operator. Convert the arguments, then // break out so that we will build the appropriate built-in // operator node. if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0], "passing")) return ExprError(); break; } } case OR_No_Viable_Function: // No viable function; fall through to handling this as a // built-in operator, which will produce an error message for us. break; case OR_Ambiguous: Diag(OpLoc, diag::err_ovl_ambiguous_oper) << UnaryOperator::getOpcodeStr(Opc) << Arg->getSourceRange(); PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); return ExprError(); case OR_Deleted: Diag(OpLoc, diag::err_ovl_deleted_oper) << Best->Function->isDeleted() << UnaryOperator::getOpcodeStr(Opc) << Arg->getSourceRange(); PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); return ExprError(); } // Either we found no viable overloaded operator or we matched a // built-in operator. In either case, fall through to trying to // build a built-in operation. } QualType result = CheckIncrementDecrementOperand(Arg, OpLoc, Opc == UnaryOperator::PostInc); if (result.isNull()) return ExprError(); Input.release(); return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc)); } Action::OwningExprResult Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, ExprArg Idx, SourceLocation RLoc) { Expr *LHSExp = static_cast<Expr*>(Base.get()), *RHSExp = static_cast<Expr*>(Idx.get()); if (getLangOptions().CPlusPlus && (LHSExp->getType()->isRecordType() || LHSExp->getType()->isEnumeralType() || RHSExp->getType()->isRecordType() || RHSExp->getType()->isEnumeralType())) { // Add the appropriate overloaded operators (C++ [over.match.oper]) // to the candidate set. OverloadCandidateSet CandidateSet; Expr *Args[2] = { LHSExp, RHSExp }; AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet, SourceRange(LLoc, RLoc)); // Perform overload resolution. OverloadCandidateSet::iterator Best; switch (BestViableFunction(CandidateSet, Best)) { case OR_Success: { // We found a built-in operator or an overloaded operator. FunctionDecl *FnDecl = Best->Function; if (FnDecl) { // We matched an overloaded operator. Build a call to that // operator. // Convert the arguments. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { if (PerformObjectArgumentInitialization(LHSExp, Method) || PerformCopyInitialization(RHSExp, FnDecl->getParamDecl(0)->getType(), "passing")) return ExprError(); } else { // Convert the arguments. if (PerformCopyInitialization(LHSExp, FnDecl->getParamDecl(0)->getType(), "passing") || PerformCopyInitialization(RHSExp, FnDecl->getParamDecl(1)->getType(), "passing")) return ExprError(); } // Determine the result type QualType ResultTy = FnDecl->getType()->getAsFunctionType()->getResultType(); ResultTy = ResultTy.getNonReferenceType(); // Build the actual expression node. Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), SourceLocation()); UsualUnaryConversions(FnExpr); Base.release(); Idx.release(); return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, FnExpr, Args, 2, ResultTy, LLoc)); } else { // We matched a built-in operator. Convert the arguments, then // break out so that we will build the appropriate built-in // operator node. if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0], "passing") || PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1], "passing")) return ExprError(); break; } } case OR_No_Viable_Function: // No viable function; fall through to handling this as a // built-in operator, which will produce an error message for us. break; case OR_Ambiguous: Diag(LLoc, diag::err_ovl_ambiguous_oper) << "[]" << LHSExp->getSourceRange() << RHSExp->getSourceRange(); PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); return ExprError(); case OR_Deleted: Diag(LLoc, diag::err_ovl_deleted_oper) << Best->Function->isDeleted() << "[]" << LHSExp->getSourceRange() << RHSExp->getSourceRange(); PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); return ExprError(); } // Either we found no viable overloaded operator or we matched a // built-in operator. In either case, fall through to trying to // build a built-in operation. } // Perform default conversions. DefaultFunctionArrayConversion(LHSExp); DefaultFunctionArrayConversion(RHSExp); QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent // to the expression *((e1)+(e2)). This means the array "Base" may actually be // in the subscript position. As a result, we need to derive the array base // and index from the expression types. Expr *BaseExpr, *IndexExpr; QualType ResultType; if (LHSTy->isDependentType() || RHSTy->isDependentType()) { BaseExpr = LHSExp; IndexExpr = RHSExp; ResultType = Context.DependentTy; } else if (const PointerType *PTy = LHSTy->getAsPointerType()) { BaseExpr = LHSExp; IndexExpr = RHSExp; // FIXME: need to deal with const... ResultType = PTy->getPointeeType(); } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { // Handle the uncommon case of "123[Ptr]". BaseExpr = RHSExp; IndexExpr = LHSExp; // FIXME: need to deal with const... ResultType = PTy->getPointeeType(); } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { BaseExpr = LHSExp; // vectors: V[123] IndexExpr = RHSExp; // FIXME: need to deal with const... ResultType = VTy->getElementType(); } else { return ExprError(Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value) << RHSExp->getSourceRange()); } // C99 6.5.2.1p1 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) return ExprError(Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript) << IndexExpr->getSourceRange()); // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, // C++ [expr.sub]p1: The type "T" shall be a completely-defined object // type. Note that Functions are not objects, and that (in C99 parlance) // incomplete types are not object types. if (ResultType->isFunctionType()) { Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) << ResultType << BaseExpr->getSourceRange(); return ExprError(); } if (!ResultType->isDependentType() && RequireCompleteType(BaseExpr->getLocStart(), ResultType, diag::err_subscript_incomplete_type, BaseExpr->getSourceRange())) return ExprError(); Base.release(); Idx.release(); return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc)); } QualType Sema:: CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, IdentifierInfo &CompName, SourceLocation CompLoc) { const ExtVectorType *vecType = baseType->getAsExtVectorType(); // The vector accessor can't exceed the number of elements. const char *compStr = CompName.getName(); // This flag determines whether or not the component is one of the four // special names that indicate a subset of exactly half the elements are // to be selected. bool HalvingSwizzle = false; // This flag determines whether or not CompName has an 's' char prefix, // indicating that it is a string of hex values to be used as vector indices. bool HexSwizzle = *compStr == 's'; // Check that we've found one of the special components, or that the component // names must come from the same set. if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { HalvingSwizzle = true; } else if (vecType->getPointAccessorIdx(*compStr) != -1) { do compStr++; while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { do compStr++; while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); } if (!HalvingSwizzle && *compStr) { // We didn't get to the end of the string. This means the component names // didn't come from the same set *or* we encountered an illegal name. Diag(OpLoc, diag::err_ext_vector_component_name_illegal) << std::string(compStr,compStr+1) << SourceRange(CompLoc); return QualType(); } // Ensure no component accessor exceeds the width of the vector type it // operates on. if (!HalvingSwizzle) { compStr = CompName.getName(); if (HexSwizzle) compStr++; while (*compStr) { if (!vecType->isAccessorWithinNumElements(*compStr++)) { Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) << baseType << SourceRange(CompLoc); return QualType(); } } } // If this is a halving swizzle, verify that the base type has an even // number of elements. if (HalvingSwizzle && (vecType->getNumElements() & 1U)) { Diag(OpLoc, diag::err_ext_vector_component_requires_even) << baseType << SourceRange(CompLoc); return QualType(); } // The component accessor looks fine - now we need to compute the actual type. // The vector type is implied by the component accessor. For example, // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. // vec4.s0 is a float, vec4.s23 is a vec3, etc. // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2 : CompName.getLength(); if (HexSwizzle) CompSize--; if (CompSize == 1) return vecType->getElementType(); QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); // Now look up the TypeDefDecl from the vector type. Without this, // diagostics look bad. We want extended vector types to appear built-in. for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { if (ExtVectorDecls[i]->getUnderlyingType() == VT) return Context.getTypedefType(ExtVectorDecls[i]); } return VT; // should never get here (a typedef type should always be found). } static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, IdentifierInfo &Member, const Selector &Sel, ASTContext &Context) { if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member)) return PD; if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel)) return OMD; for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), E = PDecl->protocol_end(); I != E; ++I) { if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context)) return D; } return 0; } static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy, IdentifierInfo &Member, const Selector &Sel, ASTContext &Context) { // Check protocols on qualified interfaces. Decl *GDecl = 0; for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(), E = QIdTy->qual_end(); I != E; ++I) { if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) { GDecl = PD; break; } // Also must look for a getter name which uses property syntax. if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) { GDecl = OMD; break; } } if (!GDecl) { for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(), E = QIdTy->qual_end(); I != E; ++I) { // Search in the protocol-qualifier list of current protocol. GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context); if (GDecl) return GDecl; } } return GDecl; } /// FindMethodInNestedImplementations - Look up a method in current and /// all base class implementations. /// ObjCMethodDecl *Sema::FindMethodInNestedImplementations( const ObjCInterfaceDecl *IFace, const Selector &Sel) { ObjCMethodDecl *Method = 0; if (ObjCImplementationDecl *ImpDecl = Sema::ObjCImplementations[IFace->getIdentifier()]) Method = ImpDecl->getInstanceMethod(Sel); if (!Method && IFace->getSuperClass()) return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel); return Method; } Action::OwningExprResult Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation MemberLoc, IdentifierInfo &Member, DeclPtrTy ObjCImpDecl) { Expr *BaseExpr = static_cast<Expr *>(Base.release()); assert(BaseExpr && "no record expression"); // Perform default conversions. DefaultFunctionArrayConversion(BaseExpr); QualType BaseType = BaseExpr->getType(); assert(!BaseType.isNull() && "no type for member expression"); // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr // must have pointer type, and the accessed type is the pointee. if (OpKind == tok::arrow) { if (const PointerType *PT = BaseType->getAsPointerType()) BaseType = PT->getPointeeType(); else if (getLangOptions().CPlusPlus && BaseType->isRecordType()) return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member)); else return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) << BaseType << BaseExpr->getSourceRange()); } // Handle field access to simple records. This also handles access to fields // of the ObjC 'id' struct. if (const RecordType *RTy = BaseType->getAsRecordType()) { RecordDecl *RDecl = RTy->getDecl(); if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag, BaseExpr->getSourceRange())) return ExprError(); // The record definition is complete, now make sure the member is valid. // FIXME: Qualified name lookup for C++ is a bit more complicated // than this. LookupResult Result = LookupQualifiedName(RDecl, DeclarationName(&Member), LookupMemberName, false); if (!Result) return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member) << &Member << BaseExpr->getSourceRange()); if (Result.isAmbiguous()) { DiagnoseAmbiguousLookup(Result, DeclarationName(&Member), MemberLoc, BaseExpr->getSourceRange()); return ExprError(); } NamedDecl *MemberDecl = Result; // If the decl being referenced had an error, return an error for this // sub-expr without emitting another error, in order to avoid cascading // error cases. if (MemberDecl->isInvalidDecl()) return ExprError(); // Check the use of this field if (DiagnoseUseOfDecl(MemberDecl, MemberLoc)) return ExprError(); if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { // We may have found a field within an anonymous union or struct // (C++ [class.union]). if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, BaseExpr, OpLoc); // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] // FIXME: Handle address space modifiers QualType MemberType = FD->getType(); if (const ReferenceType *Ref = MemberType->getAsReferenceType()) MemberType = Ref->getPointeeType(); else { unsigned combinedQualifiers = MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); if (FD->isMutable()) combinedQualifiers &= ~QualType::Const; MemberType = MemberType.getQualifiedType(combinedQualifiers); } return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD, MemberLoc, MemberType)); } if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc, Var->getType().getNonReferenceType())); if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc, MemberFn->getType())); if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc, Context.OverloadTy)); if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc, Enum->getType())); if (isa<TypeDecl>(MemberDecl)) return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type) << DeclarationName(&Member) << int(OpKind == tok::arrow)); // We found a declaration kind that we didn't expect. This is a // generic error message that tells the user that she can't refer // to this member with '.' or '->'. return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_unknown) << DeclarationName(&Member) << int(OpKind == tok::arrow)); } // Handle access to Objective-C instance variables, such as "Obj->ivar" and // (*Obj).ivar. if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { ObjCInterfaceDecl *ClassDeclared; if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context, &Member, ClassDeclared)) { // If the decl being referenced had an error, return an error for this // sub-expr without emitting another error, in order to avoid cascading // error cases. if (IV->isInvalidDecl()) return ExprError(); // Check whether we can reference this field. if (DiagnoseUseOfDecl(IV, MemberLoc)) return ExprError(); if (IV->getAccessControl() != ObjCIvarDecl::Public && IV->getAccessControl() != ObjCIvarDecl::Package) { ObjCInterfaceDecl *ClassOfMethodDecl = 0; if (ObjCMethodDecl *MD = getCurMethodDecl()) ClassOfMethodDecl = MD->getClassInterface(); else if (ObjCImpDecl && getCurFunctionDecl()) { // Case of a c-function declared inside an objc implementation. // FIXME: For a c-style function nested inside an objc implementation // class, there is no implementation context available, so we pass down // the context as argument to this routine. Ideally, this context need // be passed down in the AST node and somehow calculated from the AST // for a function decl. Decl *ImplDecl = ObjCImpDecl.getAs<Decl>(); if (ObjCImplementationDecl *IMPD = dyn_cast<ObjCImplementationDecl>(ImplDecl)) ClassOfMethodDecl = IMPD->getClassInterface(); else if (ObjCCategoryImplDecl* CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ImplDecl)) ClassOfMethodDecl = CatImplClass->getClassInterface(); } if (IV->getAccessControl() == ObjCIvarDecl::Private) { if (ClassDeclared != IFTy->getDecl() || ClassOfMethodDecl != ClassDeclared) Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName(); } // @protected else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl)) Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName(); } ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr, OpKind == tok::arrow); Context.setFieldDecl(IFTy->getDecl(), IV, MRef); return Owned(MRef); } return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) << IFTy->getDecl()->getDeclName() << &Member << BaseExpr->getSourceRange()); } // Handle Objective-C property access, which is "Obj.property" where Obj is a // pointer to a (potentially qualified) interface type. const PointerType *PTy; const ObjCInterfaceType *IFTy; if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { ObjCInterfaceDecl *IFace = IFTy->getDecl(); // Search for a declared property first. if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context, &Member)) { // Check whether we can reference this property. if (DiagnoseUseOfDecl(PD, MemberLoc)) return ExprError(); return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr)); } // Check protocols on qualified interfaces. for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), E = IFTy->qual_end(); I != E; ++I) if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) { // Check whether we can reference this property. if (DiagnoseUseOfDecl(PD, MemberLoc)) return ExprError(); return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr)); } // If that failed, look for an "implicit" property by seeing if the nullary // selector is implemented. // FIXME: The logic for looking up nullary and unary selectors should be // shared with the code in ActOnInstanceMessage. Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel); // If this reference is in an @implementation, check for 'private' methods. if (!Getter) Getter = FindMethodInNestedImplementations(IFace, Sel); // Look through local category implementations associated with the class. if (!Getter) { for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) { if (ObjCCategoryImpls[i]->getClassInterface() == IFace) Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel); } } if (Getter) { // Check if we can reference this property. if (DiagnoseUseOfDecl(Getter, MemberLoc)) return ExprError(); } // If we found a getter then this may be a valid dot-reference, we // will look for the matching setter, in case it is needed. Selector SetterSel = SelectorTable::constructSetterName(PP.getIdentifierTable(), PP.getSelectorTable(), &Member); ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel); if (!Setter) { // If this reference is in an @implementation, also check for 'private' // methods. Setter = FindMethodInNestedImplementations(IFace, SetterSel); } // Look through local category implementations associated with the class. if (!Setter) { for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { if (ObjCCategoryImpls[i]->getClassInterface() == IFace) Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel); } } if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) return ExprError(); if (Getter || Setter) { QualType PType; if (Getter) PType = Getter->getResultType(); else { for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), E = Setter->param_end(); PI != E; ++PI) PType = (*PI)->getType(); } // FIXME: we must check that the setter has property type. return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, Setter, MemberLoc, BaseExpr)); } return ExprError(Diag(MemberLoc, diag::err_property_not_found) << &Member << BaseType); } // Handle properties on qualified "id" protocols. const ObjCQualifiedIdType *QIdTy; if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) { // Check protocols on qualified interfaces. Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) { if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { // Check the use of this declaration if (DiagnoseUseOfDecl(PD, MemberLoc)) return ExprError(); return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr)); } if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { // Check the use of this method. if (DiagnoseUseOfDecl(OMD, MemberLoc)) return ExprError(); return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0)); } } return ExprError(Diag(MemberLoc, diag::err_property_not_found) << &Member << BaseType); } // Handle properties on ObjC 'Class' types. if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) { // Also must look for a getter name which uses property syntax. Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); if (ObjCMethodDecl *MD = getCurMethodDecl()) { ObjCInterfaceDecl *IFace = MD->getClassInterface(); ObjCMethodDecl *Getter; // FIXME: need to also look locally in the implementation. if ((Getter = IFace->lookupClassMethod(Context, Sel))) { // Check the use of this method. if (DiagnoseUseOfDecl(Getter, MemberLoc)) return ExprError(); } // If we found a getter then this may be a valid dot-reference, we // will look for the matching setter, in case it is needed. Selector SetterSel = SelectorTable::constructSetterName(PP.getIdentifierTable(), PP.getSelectorTable(), &Member); ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel); if (!Setter) { // If this reference is in an @implementation, also check for 'private' // methods. Setter = FindMethodInNestedImplementations(IFace, SetterSel); } // Look through local category implementations associated with the class. if (!Setter) { for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { if (ObjCCategoryImpls[i]->getClassInterface() == IFace) Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel); } } if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) return ExprError(); if (Getter || Setter) { QualType PType; if (Getter) PType = Getter->getResultType(); else { for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), E = Setter->param_end(); PI != E; ++PI) PType = (*PI)->getType(); } // FIXME: we must check that the setter has property type. return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, Setter, MemberLoc, BaseExpr)); } return ExprError(Diag(MemberLoc, diag::err_property_not_found) << &Member << BaseType); } } // Handle 'field access' to vectors, such as 'V.xx'. if (BaseType->isExtVectorType()) { QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); if (ret.isNull()) return ExprError(); return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc)); } Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) << BaseType << BaseExpr->getSourceRange(); // If the user is trying to apply -> or . to a function or function // pointer, it's probably because they forgot parentheses to call // the function. Suggest the addition of those parentheses. if (BaseType == Context.OverloadTy || BaseType->isFunctionType() || (BaseType->isPointerType() && BaseType->getAsPointerType()->isFunctionType())) { SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd()); Diag(Loc, diag::note_member_reference_needs_call) << CodeModificationHint::CreateInsertion(Loc, "()"); } return ExprError(); } /// ConvertArgumentsForCall - Converts the arguments specified in /// Args/NumArgs to the parameter types of the function FDecl with /// function prototype Proto. Call is the call expression itself, and /// Fn is the function expression. For a C++ member function, this /// routine does not attempt to convert the object argument. Returns /// true if the call is ill-formed. bool Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr **Args, unsigned NumArgs, SourceLocation RParenLoc) { // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by // assignment, to the types of the corresponding parameter, ... unsigned NumArgsInProto = Proto->getNumArgs(); unsigned NumArgsToCheck = NumArgs; bool Invalid = false; // If too few arguments are available (and we don't have default // arguments for the remaining parameters), don't make the call. if (NumArgs < NumArgsInProto) { if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); // Use default arguments for missing arguments NumArgsToCheck = NumArgsInProto; Call->setNumArgs(Context, NumArgsInProto); } // If too many are passed and not variadic, error on the extras and drop // them. if (NumArgs > NumArgsInProto) { if (!Proto->isVariadic()) { Diag(Args[NumArgsInProto]->getLocStart(), diag::err_typecheck_call_too_many_args) << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() << SourceRange(Args[NumArgsInProto]->getLocStart(), Args[NumArgs-1]->getLocEnd()); // This deletes the extra arguments. Call->setNumArgs(Context, NumArgsInProto); Invalid = true; } NumArgsToCheck = NumArgsInProto; } // Continue to check argument types (even if we have too few/many args). for (unsigned i = 0; i != NumArgsToCheck; i++) { QualType ProtoArgType = Proto->getArgType(i); Expr *Arg; if (i < NumArgs) { Arg = Args[i]; if (RequireCompleteType(Arg->getSourceRange().getBegin(), ProtoArgType, diag::err_call_incomplete_argument, Arg->getSourceRange())) return true; // Pass the argument. if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) return true; } else // We already type-checked the argument, so we know it works. Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i)); QualType ArgType = Arg->getType(); Call->setArg(i, Arg); } // If this is a variadic call, handle args passed through "...". if (Proto->isVariadic()) { VariadicCallType CallType = VariadicFunction; if (Fn->getType()->isBlockPointerType()) CallType = VariadicBlock; // Block else if (isa<MemberExpr>(Fn)) CallType = VariadicMethod; // Promote the arguments (C99 6.5.2.2p7). for (unsigned i = NumArgsInProto; i != NumArgs; i++) { Expr *Arg = Args[i]; Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType); Call->setArg(i, Arg); } } return Invalid; } /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. Action::OwningExprResult Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc, MultiExprArg args, SourceLocation *CommaLocs, SourceLocation RParenLoc) { unsigned NumArgs = args.size(); Expr *Fn = static_cast<Expr *>(fn.release()); Expr **Args = reinterpret_cast<Expr**>(args.release()); assert(Fn && "no function call expression"); FunctionDecl *FDecl = NULL; DeclarationName UnqualifiedName; if (getLangOptions().CPlusPlus) { // Determine whether this is a dependent call inside a C++ template, // in which case we won't do any semantic analysis now. // FIXME: Will need to cache the results of name lookup (including ADL) in Fn. bool Dependent = false; if (Fn->isTypeDependent()) Dependent = true; else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) Dependent = true; if (Dependent) return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, Context.DependentTy, RParenLoc)); // Determine whether this is a call to an object (C++ [over.call.object]). if (Fn->getType()->isRecordType()) return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, CommaLocs, RParenLoc)); // Determine whether this is a call to a member function. if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) || isa<CXXMethodDecl>(MemExpr->getMemberDecl())) return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, CommaLocs, RParenLoc)); } // If we're directly calling a function, get the appropriate declaration. DeclRefExpr *DRExpr = NULL; Expr *FnExpr = Fn; bool ADL = true; while (true) { if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr)) FnExpr = IcExpr->getSubExpr(); else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) { // Parentheses around a function disable ADL // (C++0x [basic.lookup.argdep]p1). ADL = false; FnExpr = PExpr->getSubExpr(); } else if (isa<UnaryOperator>(FnExpr) && cast<UnaryOperator>(FnExpr)->getOpcode() == UnaryOperator::AddrOf) { FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr(); } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) { // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1). ADL &= !isa<QualifiedDeclRefExpr>(DRExpr); break; } else if (UnresolvedFunctionNameExpr *DepName = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) { UnqualifiedName = DepName->getName(); break; } else { // Any kind of name that does not refer to a declaration (or // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3). ADL = false; break; } } OverloadedFunctionDecl *Ovl = 0; if (DRExpr) { FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl()); } if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) { // We don't perform ADL for implicit declarations of builtins. if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit()) ADL = false; // We don't perform ADL in C. if (!getLangOptions().CPlusPlus) ADL = false; if (Ovl || ADL) { FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0, UnqualifiedName, LParenLoc, Args, NumArgs, CommaLocs, RParenLoc, ADL); if (!FDecl) return ExprError(); // Update Fn to refer to the actual function selected. Expr *NewFn = 0; if (QualifiedDeclRefExpr *QDRExpr = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr)) NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(), QDRExpr->getLocation(), false, false, QDRExpr->getQualifierRange(), QDRExpr->getQualifier()); else NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(), Fn->getSourceRange().getBegin()); Fn->Destroy(Context); Fn = NewFn; } } // Promote the function operand. UsualUnaryConversions(Fn); // Make the call expr early, before semantic checks. This guarantees cleanup // of arguments and function on error. ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn, Args, NumArgs, Context.BoolTy, RParenLoc)); const FunctionType *FuncT; if (!Fn->getType()->isBlockPointerType()) { // C99 6.5.2.2p1 - "The expression that denotes the called function shall // have type pointer to function". const PointerType *PT = Fn->getType()->getAsPointerType(); if (PT == 0) return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) << Fn->getType() << Fn->getSourceRange()); FuncT = PT->getPointeeType()->getAsFunctionType(); } else { // This is a block call. FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()-> getAsFunctionType(); } if (FuncT == 0) return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) << Fn->getType() << Fn->getSourceRange()); // Check for a valid return type if (!FuncT->getResultType()->isVoidType() && RequireCompleteType(Fn->getSourceRange().getBegin(), FuncT->getResultType(), diag::err_call_incomplete_return, TheCall->getSourceRange())) return ExprError(); // We know the result type of the call, set it. TheCall->setType(FuncT->getResultType().getNonReferenceType()); if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs, RParenLoc)) return ExprError(); } else { assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); if (FDecl) { // Check if we have too few/too many template arguments, based // on our knowledge of the function definition. const FunctionDecl *Def = 0; if (FDecl->getBody(Def) && NumArgs != Def->param_size()) Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); } // Promote the arguments (C99 6.5.2.2p6). for (unsigned i = 0; i != NumArgs; i++) { Expr *Arg = Args[i]; DefaultArgumentPromotion(Arg); if (RequireCompleteType(Arg->getSourceRange().getBegin(), Arg->getType(), diag::err_call_incomplete_argument, Arg->getSourceRange())) return ExprError(); TheCall->setArg(i, Arg); } } if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) if (!Method->isStatic()) return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) << Fn->getSourceRange()); // Do special checking on direct calls to functions. if (FDecl) return CheckFunctionCall(FDecl, TheCall.take()); return Owned(TheCall.take()); } Action::OwningExprResult Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, SourceLocation RParenLoc, ExprArg InitExpr) { assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); QualType literalType = QualType::getFromOpaquePtr(Ty); // FIXME: put back this assert when initializers are worked out. //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); Expr *literalExpr = static_cast<Expr*>(InitExpr.get()); if (literalType->isArrayType()) { if (literalType->isVariableArrayType()) return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); } else if (RequireCompleteType(LParenLoc, literalType, diag::err_typecheck_decl_incomplete_type, SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()))) return ExprError(); if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, DeclarationName(), /*FIXME:DirectInit=*/false)) return ExprError(); bool isFileScope = getCurFunctionOrMethodDecl() == 0; if (isFileScope) { // 6.5.2.5p3 if (CheckForConstantInitializer(literalExpr, literalType)) return ExprError(); } InitExpr.release(); return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope)); } Action::OwningExprResult Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, SourceLocation RBraceLoc) { unsigned NumInit = initlist.size(); Expr **InitList = reinterpret_cast<Expr**>(initlist.release()); // Semantic analysis for initializers is done by ActOnDeclarator() and // CheckInitializer() - it requires knowledge of the object being intialized. InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc); E->setType(Context.VoidTy); // FIXME: just a place holder for now. return Owned(E); } /// CheckCastTypes - Check type constraints for casting between types. bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) { UsualUnaryConversions(castExpr); // C99 6.5.4p2: the cast type needs to be void or scalar and the expression // type needs to be scalar. if (castType->isVoidType()) { // Cast to void allows any expr type. } else if (castType->isDependentType() || castExpr->isTypeDependent()) { // We can't check any more until template instantiation time. } else if (!castType->isScalarType() && !castType->isVectorType()) { if (Context.getCanonicalType(castType).getUnqualifiedType() == Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) && (castType->isStructureType() || castType->isUnionType())) { // GCC struct/union extension: allow cast to self. // FIXME: Check that the cast destination type is complete. Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) << castType << castExpr->getSourceRange(); } else if (castType->isUnionType()) { // GCC cast to union extension RecordDecl *RD = castType->getAsRecordType()->getDecl(); RecordDecl::field_iterator Field, FieldEnd; for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context); Field != FieldEnd; ++Field) { if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() == Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) { Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) << castExpr->getSourceRange(); break; } } if (Field == FieldEnd) return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) << castExpr->getType() << castExpr->getSourceRange(); } else { // Reject any other conversions to non-scalar types. return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) << castType << castExpr->getSourceRange(); } } else if (!castExpr->getType()->isScalarType() && !castExpr->getType()->isVectorType()) { return Diag(castExpr->getLocStart(), diag::err_typecheck_expect_scalar_operand) << castExpr->getType() << castExpr->getSourceRange(); } else if (castExpr->getType()->isVectorType()) { if (CheckVectorCast(TyR, castExpr->getType(), castType)) return true; } else if (castType->isVectorType()) { if (CheckVectorCast(TyR, castType, castExpr->getType())) return true; } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) { return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR; } return false; } bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { assert(VectorTy->isVectorType() && "Not a vector type!"); if (Ty->isVectorType() || Ty->isIntegerType()) { if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) return Diag(R.getBegin(), Ty->isVectorType() ? diag::err_invalid_conversion_between_vectors : diag::err_invalid_conversion_between_vector_and_integer) << VectorTy << Ty << R; } else return Diag(R.getBegin(), diag::err_invalid_conversion_between_vector_and_scalar) << VectorTy << Ty << R; return false; } Action::OwningExprResult Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, SourceLocation RParenLoc, ExprArg Op) { assert((Ty != 0) && (Op.get() != 0) && "ActOnCastExpr(): missing type or expr"); Expr *castExpr = static_cast<Expr*>(Op.release()); QualType castType = QualType::getFromOpaquePtr(Ty); if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr)) return ExprError(); return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc)); } /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. /// In that case, lhs = cond. /// C99 6.5.15 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, SourceLocation QuestionLoc) { UsualUnaryConversions(Cond); UsualUnaryConversions(LHS); UsualUnaryConversions(RHS); QualType CondTy = Cond->getType(); QualType LHSTy = LHS->getType(); QualType RHSTy = RHS->getType(); // first, check the condition. if (!Cond->isTypeDependent()) { if (!CondTy->isScalarType()) { // C99 6.5.15p2 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << CondTy; return QualType(); } } // Now check the two expressions. if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent())) return Context.DependentTy; // If both operands have arithmetic type, do the usual arithmetic conversions // to find a common type: C99 6.5.15p3,5. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { UsualArithmeticConversions(LHS, RHS); return LHS->getType(); } // If both operands are the same structure or union type, the result is that // type. if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3 if (const RecordType *RHSRT = RHSTy->getAsRecordType()) if (LHSRT->getDecl() == RHSRT->getDecl()) // "If both the operands have structure or union type, the result has // that type." This implies that CV qualifiers are dropped. return LHSTy.getUnqualifiedType(); // FIXME: Type of conditional expression must be complete in C mode. } // C99 6.5.15p5: "If both operands have void type, the result has void type." // The following || allows only one side to be void (a GCC-ism). if (LHSTy->isVoidType() || RHSTy->isVoidType()) { if (!LHSTy->isVoidType()) Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) << RHS->getSourceRange(); if (!RHSTy->isVoidType()) Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) << LHS->getSourceRange(); ImpCastExprToType(LHS, Context.VoidTy); ImpCastExprToType(RHS, Context.VoidTy); return Context.VoidTy; } // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has // the type of the other operand." if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() || Context.isObjCObjectPointerType(LHSTy)) && RHS->isNullPointerConstant(Context)) { ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer. return LHSTy; } if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() || Context.isObjCObjectPointerType(RHSTy)) && LHS->isNullPointerConstant(Context)) { ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer. return RHSTy; } // Handle the case where both operands are pointers before we handle null // pointer constants in case both operands are null pointer constants. if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) { // get the "pointed to" types QualType lhptee = LHSPT->getPointeeType(); QualType rhptee = RHSPT->getPointeeType(); // ignore qualifiers on void (C99 6.5.15p3, clause 6) if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { // Figure out necessary qualifiers (C99 6.5.15p6) QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); QualType destType = Context.getPointerType(destPointee); ImpCastExprToType(LHS, destType); // add qualifiers if necessary ImpCastExprToType(RHS, destType); // promote to void* return destType; } if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); QualType destType = Context.getPointerType(destPointee); ImpCastExprToType(LHS, destType); // add qualifiers if necessary ImpCastExprToType(RHS, destType); // promote to void* return destType; } if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { // Two identical pointer types are always compatible. return LHSTy; } QualType compositeType = LHSTy; // If either type is an Objective-C object type then check // compatibility according to Objective-C. if (Context.isObjCObjectPointerType(LHSTy) || Context.isObjCObjectPointerType(RHSTy)) { // If both operands are interfaces and either operand can be // assigned to the other, use that type as the composite // type. This allows // xxx ? (A*) a : (B*) b // where B is a subclass of A. // // Additionally, as for assignment, if either type is 'id' // allow silent coercion. Finally, if the types are // incompatible then make sure to use 'id' as the composite // type so the result is acceptable for sending messages to. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. // It could return the composite type. const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); if (LHSIface && RHSIface && Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { compositeType = LHSTy; } else if (LHSIface && RHSIface && Context.canAssignObjCInterfaces(RHSIface, LHSIface)) { compositeType = RHSTy; } else if (Context.isObjCIdStructType(lhptee) || Context.isObjCIdStructType(rhptee)) { compositeType = Context.getObjCIdType(); } else { Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers) << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); QualType incompatTy = Context.getObjCIdType(); ImpCastExprToType(LHS, incompatTy); ImpCastExprToType(RHS, incompatTy); return incompatTy; } } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), rhptee.getUnqualifiedType())) { Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); // In this situation, we assume void* type. No especially good // reason, but this is what gcc does, and we do have to pick // to get a consistent AST. QualType incompatTy = Context.getPointerType(Context.VoidTy); ImpCastExprToType(LHS, incompatTy); ImpCastExprToType(RHS, incompatTy); return incompatTy; } // The pointer types are compatible. // C99 6.5.15p6: If both operands are pointers to compatible types *or* to // differently qualified versions of compatible types, the result type is // a pointer to an appropriately qualified version of the *composite* // type. // FIXME: Need to calculate the composite type. // FIXME: Need to add qualifiers ImpCastExprToType(LHS, compositeType); ImpCastExprToType(RHS, compositeType); return compositeType; } } // GCC compatibility: soften pointer/integer mismatch. if (RHSTy->isPointerType() && LHSTy->isIntegerType()) { Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer. return RHSTy; } if (LHSTy->isPointerType() && RHSTy->isIntegerType()) { Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer. return LHSTy; } // Selection between block pointer types is ok as long as they are the same. if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() && Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) return LHSTy; // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type // evaluates to "struct objc_object *" (and is handled above when comparing // id with statically typed objects). if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) { // GCC allows qualified id and any Objective-C type to devolve to // id. Currently localizing to here until clear this should be // part of ObjCQualifiedIdTypesAreCompatible. if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) || (LHSTy->isObjCQualifiedIdType() && Context.isObjCObjectPointerType(RHSTy)) || (RHSTy->isObjCQualifiedIdType() && Context.isObjCObjectPointerType(LHSTy))) { // FIXME: This is not the correct composite type. This only // happens to work because id can more or less be used anywhere, // however this may change the type of method sends. // FIXME: gcc adds some type-checking of the arguments and emits // (confusing) incompatible comparison warnings in some // cases. Investigate. QualType compositeType = Context.getObjCIdType(); ImpCastExprToType(LHS, compositeType); ImpCastExprToType(RHS, compositeType); return compositeType; } } // Otherwise, the operands are not compatible. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, ExprArg Cond, ExprArg LHS, ExprArg RHS) { Expr *CondExpr = (Expr *) Cond.get(); Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get(); // If this is the gnu "x ?: y" extension, analyze the types as though the LHS // was the condition. bool isLHSNull = LHSExpr == 0; if (isLHSNull) LHSExpr = CondExpr; QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr, QuestionLoc); if (result.isNull()) return ExprError(); Cond.release(); LHS.release(); RHS.release(); return Owned(new (Context) ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr, RHSExpr, result)); } // CheckPointerTypesForAssignment - This is a very tricky routine (despite // being closely modeled after the C99 spec:-). The odd characteristic of this // routine is it effectively iqnores the qualifiers on the top level pointee. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. // FIXME: add a couple examples in this comment. Sema::AssignConvertType Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { QualType lhptee, rhptee; // get the "pointed to" type (ignoring qualifiers at the top level) lhptee = lhsType->getAsPointerType()->getPointeeType(); rhptee = rhsType->getAsPointerType()->getPointeeType(); // make sure we operate on the canonical type lhptee = Context.getCanonicalType(lhptee); rhptee = Context.getCanonicalType(rhptee); AssignConvertType ConvTy = Compatible; // C99 6.5.16.1p1: This following citation is common to constraints // 3 & 4 (below). ...and the type *pointed to* by the left has all the // qualifiers of the type *pointed to* by the right; // FIXME: Handle ExtQualType if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) ConvTy = CompatiblePointerDiscardsQualifiers; // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or // incomplete type and the other is a pointer to a qualified or unqualified // version of void... if (lhptee->isVoidType()) { if (rhptee->isIncompleteOrObjectType()) return ConvTy; // As an extension, we allow cast to/from void* to function pointer. assert(rhptee->isFunctionType()); return FunctionVoidPointer; } if (rhptee->isVoidType()) { if (lhptee->isIncompleteOrObjectType()) return ConvTy; // As an extension, we allow cast to/from void* to function pointer. assert(lhptee->isFunctionType()); return FunctionVoidPointer; } // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or // unqualified versions of compatible types, ... lhptee = lhptee.getUnqualifiedType(); rhptee = rhptee.getUnqualifiedType(); if (!Context.typesAreCompatible(lhptee, rhptee)) { // Check if the pointee types are compatible ignoring the sign. // We explicitly check for char so that we catch "char" vs // "unsigned char" on systems where "char" is unsigned. if (lhptee->isCharType()) { lhptee = Context.UnsignedCharTy; } else if (lhptee->isSignedIntegerType()) { lhptee = Context.getCorrespondingUnsignedType(lhptee); } if (rhptee->isCharType()) { rhptee = Context.UnsignedCharTy; } else if (rhptee->isSignedIntegerType()) { rhptee = Context.getCorrespondingUnsignedType(rhptee); } if (lhptee == rhptee) { // Types are compatible ignoring the sign. Qualifier incompatibility // takes priority over sign incompatibility because the sign // warning can be disabled. if (ConvTy != Compatible) return ConvTy; return IncompatiblePointerSign; } // General pointer incompatibility takes priority over qualifiers. return IncompatiblePointer; } return ConvTy; } /// CheckBlockPointerTypesForAssignment - This routine determines whether two /// block pointer types are compatible or whether a block and normal pointer /// are compatible. It is more restrict than comparing two function pointer // types. Sema::AssignConvertType Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, QualType rhsType) { QualType lhptee, rhptee; // get the "pointed to" type (ignoring qualifiers at the top level) lhptee = lhsType->getAsBlockPointerType()->getPointeeType(); rhptee = rhsType->getAsBlockPointerType()->getPointeeType(); // make sure we operate on the canonical type lhptee = Context.getCanonicalType(lhptee); rhptee = Context.getCanonicalType(rhptee); AssignConvertType ConvTy = Compatible; // For blocks we enforce that qualifiers are identical. if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) ConvTy = CompatiblePointerDiscardsQualifiers; if (!Context.typesAreBlockCompatible(lhptee, rhptee)) return IncompatibleBlockPointer; return ConvTy; } /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently /// has code to accommodate several GCC extensions when type checking /// pointers. Here are some objectionable examples that GCC considers warnings: /// /// int a, *pint; /// short *pshort; /// struct foo *pfoo; /// /// pint = pshort; // warning: assignment from incompatible pointer type /// a = pint; // warning: assignment makes integer from pointer without a cast /// pint = a; // warning: assignment makes pointer from integer without a cast /// pint = pfoo; // warning: assignment from incompatible pointer type /// /// As a result, the code for dealing with pointers is more complex than the /// C99 spec dictates. /// Sema::AssignConvertType Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { // Get canonical types. We're not formatting these types, just comparing // them. lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); if (lhsType == rhsType) return Compatible; // Common case: fast path an exact match. // If the left-hand side is a reference type, then we are in a // (rare!) case where we've allowed the use of references in C, // e.g., as a parameter type in a built-in function. In this case, // just make sure that the type referenced is compatible with the // right-hand side type. The caller is responsible for adjusting // lhsType so that the resulting expression does not have reference // type. if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) { if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) return Compatible; return Incompatible; } if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) return Compatible; // Relax integer conversions like we do for pointers below. if (rhsType->isIntegerType()) return IntToPointer; if (lhsType->isIntegerType()) return PointerToInt; return IncompatibleObjCQualifiedId; } if (lhsType->isVectorType() || rhsType->isVectorType()) { // For ExtVector, allow vector splats; float -> <n x float> if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) if (LV->getElementType() == rhsType) return Compatible; // If we are allowing lax vector conversions, and LHS and RHS are both // vectors, the total size only needs to be the same. This is a bitcast; // no bits are changed but the result type is different. if (getLangOptions().LaxVectorConversions && lhsType->isVectorType() && rhsType->isVectorType()) { if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) return IncompatibleVectors; } return Incompatible; } if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) return Compatible; if (isa<PointerType>(lhsType)) { if (rhsType->isIntegerType()) return IntToPointer; if (isa<PointerType>(rhsType)) return CheckPointerTypesForAssignment(lhsType, rhsType); if (rhsType->getAsBlockPointerType()) { if (lhsType->getAsPointerType()->getPointeeType()->isVoidType()) return Compatible; // Treat block pointers as objects. if (getLangOptions().ObjC1 && lhsType == Context.getCanonicalType(Context.getObjCIdType())) return Compatible; } return Incompatible; } if (isa<BlockPointerType>(lhsType)) { if (rhsType->isIntegerType()) return IntToBlockPointer; // Treat block pointers as objects. if (getLangOptions().ObjC1 && rhsType == Context.getCanonicalType(Context.getObjCIdType())) return Compatible; if (rhsType->isBlockPointerType()) return CheckBlockPointerTypesForAssignment(lhsType, rhsType); if (const PointerType *RHSPT = rhsType->getAsPointerType()) { if (RHSPT->getPointeeType()->isVoidType()) return Compatible; } return Incompatible; } if (isa<PointerType>(rhsType)) { // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. if (lhsType == Context.BoolTy) return Compatible; if (lhsType->isIntegerType()) return PointerToInt; if (isa<PointerType>(lhsType)) return CheckPointerTypesForAssignment(lhsType, rhsType); if (isa<BlockPointerType>(lhsType) && rhsType->getAsPointerType()->getPointeeType()->isVoidType()) return Compatible; return Incompatible; } if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { if (Context.typesAreCompatible(lhsType, rhsType)) return Compatible; } return Incompatible; } Sema::AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { if (getLangOptions().CPlusPlus) { if (!lhsType->isRecordType()) { // C++ 5.17p3: If the left operand is not of class type, the // expression is implicitly converted (C++ 4) to the // cv-unqualified type of the left operand. if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), "assigning")) return Incompatible; return Compatible; } // FIXME: Currently, we fall through and treat C++ classes like C // structures. } // C99 6.5.16.1p1: the left operand is a pointer and the right is // a null pointer constant. if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() || lhsType->isBlockPointerType()) && rExpr->isNullPointerConstant(Context)) { ImpCastExprToType(rExpr, lhsType); return Compatible; } // This check seems unnatural, however it is necessary to ensure the proper // conversion of functions/arrays. If the conversion were done for all // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary // expressions that surpress this implicit conversion (&, sizeof). // // Suppress this for references: C++ 8.5.3p5. if (!lhsType->isReferenceType()) DefaultFunctionArrayConversion(rExpr); Sema::AssignConvertType result = CheckAssignmentConstraints(lhsType, rExpr->getType()); // C99 6.5.16.1p2: The value of the right operand is converted to the // type of the assignment expression. // CheckAssignmentConstraints allows the left-hand side to be a reference, // so that we can use references in built-in functions even in C. // The getNonReferenceType() call makes sure that the resulting expression // does not have reference type. if (rExpr->getType() != lhsType) ImpCastExprToType(rExpr, lhsType.getNonReferenceType()); return result; } Sema::AssignConvertType Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { return CheckAssignmentConstraints(lhsType, rhsType); } QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { Diag(Loc, diag::err_typecheck_invalid_operands) << lex->getType() << rex->getType() << lex->getSourceRange() << rex->getSourceRange(); return QualType(); } inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { // For conversion purposes, we ignore any qualifiers. // For example, "const float" and "float" are equivalent. QualType lhsType = Context.getCanonicalType(lex->getType()).getUnqualifiedType(); QualType rhsType = Context.getCanonicalType(rex->getType()).getUnqualifiedType(); // If the vector types are identical, return. if (lhsType == rhsType) return lhsType; // Handle the case of a vector & extvector type of the same size and element // type. It would be nice if we only had one vector type someday. if (getLangOptions().LaxVectorConversions) { // FIXME: Should we warn here? if (const VectorType *LV = lhsType->getAsVectorType()) { if (const VectorType *RV = rhsType->getAsVectorType()) if (LV->getElementType() == RV->getElementType() && LV->getNumElements() == RV->getNumElements()) { return lhsType->isExtVectorType() ? lhsType : rhsType; } } } // If the lhs is an extended vector and the rhs is a scalar of the same type // or a literal, promote the rhs to the vector type. if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { QualType eltType = V->getElementType(); if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { ImpCastExprToType(rex, lhsType); return lhsType; } } // If the rhs is an extended vector and the lhs is a scalar of the same type, // promote the lhs to the vector type. if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { QualType eltType = V->getElementType(); if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { ImpCastExprToType(lex, rhsType); return rhsType; } } // You cannot convert between vector values of different size. Diag(Loc, diag::err_typecheck_vector_not_convertable) << lex->getType() << rex->getType() << lex->getSourceRange() << rex->getSourceRange(); return QualType(); } inline QualType Sema::CheckMultiplyDivideOperands( Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) return CheckVectorOperands(Loc, lex, rex); QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) return compType; return InvalidOperands(Loc, lex, rex); } inline QualType Sema::CheckRemainderOperands( Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) return CheckVectorOperands(Loc, lex, rex); return InvalidOperands(Loc, lex, rex); } QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) return compType; return InvalidOperands(Loc, lex, rex); } inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) { if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { QualType compType = CheckVectorOperands(Loc, lex, rex); if (CompLHSTy) *CompLHSTy = compType; return compType; } QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); // handle the common case first (both operands are arithmetic). if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) { if (CompLHSTy) *CompLHSTy = compType; return compType; } // Put any potential pointer into PExp Expr* PExp = lex, *IExp = rex; if (IExp->getType()->isPointerType()) std::swap(PExp, IExp); if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { if (IExp->getType()->isIntegerType()) { // Check for arithmetic on pointers to incomplete types if (PTy->getPointeeType()->isVoidType()) { if (getLangOptions().CPlusPlus) { Diag(Loc, diag::err_typecheck_pointer_arith_void_type) << lex->getSourceRange() << rex->getSourceRange(); return QualType(); } // GNU extension: arithmetic on pointer to void Diag(Loc, diag::ext_gnu_void_ptr) << lex->getSourceRange() << rex->getSourceRange(); } else if (PTy->getPointeeType()->isFunctionType()) { if (getLangOptions().CPlusPlus) { Diag(Loc, diag::err_typecheck_pointer_arith_function_type) << lex->getType() << lex->getSourceRange(); return QualType(); } // GNU extension: arithmetic on pointer to function Diag(Loc, diag::ext_gnu_ptr_func_arith) << lex->getType() << lex->getSourceRange(); } else if (!PTy->isDependentType() && RequireCompleteType(Loc, PTy->getPointeeType(), diag::err_typecheck_arithmetic_incomplete_type, lex->getSourceRange(), SourceRange(), lex->getType())) return QualType(); if (CompLHSTy) { QualType LHSTy = lex->getType(); if (LHSTy->isPromotableIntegerType()) LHSTy = Context.IntTy; *CompLHSTy = LHSTy; } return PExp->getType(); } } return InvalidOperands(Loc, lex, rex); } // C99 6.5.6 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) { if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { QualType compType = CheckVectorOperands(Loc, lex, rex); if (CompLHSTy) *CompLHSTy = compType; return compType; } QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); // Enforce type constraints: C99 6.5.6p3. // Handle the common case first (both operands are arithmetic). if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) { if (CompLHSTy) *CompLHSTy = compType; return compType; } // Either ptr - int or ptr - ptr. if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { QualType lpointee = LHSPTy->getPointeeType(); // The LHS must be an completely-defined object type. bool ComplainAboutVoid = false; Expr *ComplainAboutFunc = 0; if (lpointee->isVoidType()) { if (getLangOptions().CPlusPlus) { Diag(Loc, diag::err_typecheck_pointer_arith_void_type) << lex->getSourceRange() << rex->getSourceRange(); return QualType(); } // GNU C extension: arithmetic on pointer to void ComplainAboutVoid = true; } else if (lpointee->isFunctionType()) { if (getLangOptions().CPlusPlus) { Diag(Loc, diag::err_typecheck_pointer_arith_function_type) << lex->getType() << lex->getSourceRange(); return QualType(); } // GNU C extension: arithmetic on pointer to function ComplainAboutFunc = lex; } else if (!lpointee->isDependentType() && RequireCompleteType(Loc, lpointee, diag::err_typecheck_sub_ptr_object, lex->getSourceRange(), SourceRange(), lex->getType())) return QualType(); // The result type of a pointer-int computation is the pointer type. if (rex->getType()->isIntegerType()) { if (ComplainAboutVoid) Diag(Loc, diag::ext_gnu_void_ptr) << lex->getSourceRange() << rex->getSourceRange(); if (ComplainAboutFunc) Diag(Loc, diag::ext_gnu_ptr_func_arith) << ComplainAboutFunc->getType() << ComplainAboutFunc->getSourceRange(); if (CompLHSTy) *CompLHSTy = lex->getType(); return lex->getType(); } // Handle pointer-pointer subtractions. if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { QualType rpointee = RHSPTy->getPointeeType(); // RHS must be a completely-type object type. // Handle the GNU void* extension. if (rpointee->isVoidType()) { if (getLangOptions().CPlusPlus) { Diag(Loc, diag::err_typecheck_pointer_arith_void_type) << lex->getSourceRange() << rex->getSourceRange(); return QualType(); } ComplainAboutVoid = true; } else if (rpointee->isFunctionType()) { if (getLangOptions().CPlusPlus) { Diag(Loc, diag::err_typecheck_pointer_arith_function_type) << rex->getType() << rex->getSourceRange(); return QualType(); } // GNU extension: arithmetic on pointer to function if (!ComplainAboutFunc) ComplainAboutFunc = rex; } else if (!rpointee->isDependentType() && RequireCompleteType(Loc, rpointee, diag::err_typecheck_sub_ptr_object, rex->getSourceRange(), SourceRange(), rex->getType())) return QualType(); // Pointee types must be compatible. if (!Context.typesAreCompatible( Context.getCanonicalType(lpointee).getUnqualifiedType(), Context.getCanonicalType(rpointee).getUnqualifiedType())) { Diag(Loc, diag::err_typecheck_sub_ptr_compatible) << lex->getType() << rex->getType() << lex->getSourceRange() << rex->getSourceRange(); return QualType(); } if (ComplainAboutVoid) Diag(Loc, diag::ext_gnu_void_ptr) << lex->getSourceRange() << rex->getSourceRange(); if (ComplainAboutFunc) Diag(Loc, diag::ext_gnu_ptr_func_arith) << ComplainAboutFunc->getType() << ComplainAboutFunc->getSourceRange(); if (CompLHSTy) *CompLHSTy = lex->getType(); return Context.getPointerDiffType(); } } return InvalidOperands(Loc, lex, rex); } // C99 6.5.7 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { // C99 6.5.7p2: Each of the operands shall have integer type. if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) return InvalidOperands(Loc, lex, rex); // Shifts don't perform usual arithmetic conversions, they just do integer // promotions on each operand. C99 6.5.7p3 QualType LHSTy; if (lex->getType()->isPromotableIntegerType()) LHSTy = Context.IntTy; else LHSTy = lex->getType(); if (!isCompAssign) ImpCastExprToType(lex, LHSTy); UsualUnaryConversions(rex); // "The type of the result is that of the promoted left operand." return LHSTy; } // C99 6.5.8 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned OpaqueOpc, bool isRelational) { BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc; if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) return CheckVectorCompareOperands(lex, rex, Loc, isRelational); // C99 6.5.8p3 / C99 6.5.9p4 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) UsualArithmeticConversions(lex, rex); else { UsualUnaryConversions(lex); UsualUnaryConversions(rex); } QualType lType = lex->getType(); QualType rType = rex->getType(); if (!lType->isFloatingType()) { // For non-floating point types, check for self-comparisons of the form // x == x, x != x, x < x, etc. These always evaluate to a constant, and // often indicate logic errors in the program. // NOTE: Don't warn about comparisons of enum constants. These can arise // from macro expansions, and are usually quite deliberate. Expr *LHSStripped = lex->IgnoreParens(); Expr *RHSStripped = rex->IgnoreParens(); if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) if (DRL->getDecl() == DRR->getDecl() && !isa<EnumConstantDecl>(DRL->getDecl())) Diag(Loc, diag::warn_selfcomparison); if (isa<CastExpr>(LHSStripped)) LHSStripped = LHSStripped->IgnoreParenCasts(); if (isa<CastExpr>(RHSStripped)) RHSStripped = RHSStripped->IgnoreParenCasts(); // Warn about comparisons against a string constant (unless the other // operand is null), the user probably wants strcmp. Expr *literalString = 0; Expr *literalStringStripped = 0; if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && !RHSStripped->isNullPointerConstant(Context)) { literalString = lex; literalStringStripped = LHSStripped; } else if ((isa<StringLiteral>(RHSStripped) || isa<ObjCEncodeExpr>(RHSStripped)) && !LHSStripped->isNullPointerConstant(Context)) { literalString = rex; literalStringStripped = RHSStripped; } if (literalString) { std::string resultComparison; switch (Opc) { case BinaryOperator::LT: resultComparison = ") < 0"; break; case BinaryOperator::GT: resultComparison = ") > 0"; break; case BinaryOperator::LE: resultComparison = ") <= 0"; break; case BinaryOperator::GE: resultComparison = ") >= 0"; break; case BinaryOperator::EQ: resultComparison = ") == 0"; break; case BinaryOperator::NE: resultComparison = ") != 0"; break; default: assert(false && "Invalid comparison operator"); } Diag(Loc, diag::warn_stringcompare) << isa<ObjCEncodeExpr>(literalStringStripped) << literalString->getSourceRange() << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ") << CodeModificationHint::CreateInsertion(lex->getLocStart(), "strcmp(") << CodeModificationHint::CreateInsertion( PP.getLocForEndOfToken(rex->getLocEnd()), resultComparison); } } // The result of comparisons is 'bool' in C++, 'int' in C. QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy; if (isRelational) { if (lType->isRealType() && rType->isRealType()) return ResultTy; } else { // Check for comparisons of floating point operands using != and ==. if (lType->isFloatingType()) { assert(rType->isFloatingType()); CheckFloatComparison(Loc,lex,rex); } if (lType->isArithmeticType() && rType->isArithmeticType()) return ResultTy; } bool LHSIsNull = lex->isNullPointerConstant(Context); bool RHSIsNull = rex->isNullPointerConstant(Context); // All of the following pointer related warnings are GCC extensions, except // when handling null pointer constants. One day, we can consider making them // errors (when -pedantic-errors is enabled). if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 QualType LCanPointeeTy = Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); QualType RCanPointeeTy = Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), RCanPointeeTy.getUnqualifiedType()) && !Context.areComparableObjCPointerTypes(lType, rType)) { Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); } ImpCastExprToType(rex, lType); // promote the pointer to pointer return ResultTy; } // Handle block pointer types. if (lType->isBlockPointerType() && rType->isBlockPointerType()) { QualType lpointee = lType->getAsBlockPointerType()->getPointeeType(); QualType rpointee = rType->getAsBlockPointerType()->getPointeeType(); if (!LHSIsNull && !RHSIsNull && !Context.typesAreBlockCompatible(lpointee, rpointee)) { Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); } ImpCastExprToType(rex, lType); // promote the pointer to pointer return ResultTy; } // Allow block pointers to be compared with null pointer constants. if ((lType->isBlockPointerType() && rType->isPointerType()) || (lType->isPointerType() && rType->isBlockPointerType())) { if (!LHSIsNull && !RHSIsNull) { Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); } ImpCastExprToType(rex, lType); // promote the pointer to pointer return ResultTy; } if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { if (lType->isPointerType() || rType->isPointerType()) { const PointerType *LPT = lType->getAsPointerType(); const PointerType *RPT = rType->getAsPointerType(); bool LPtrToVoid = LPT ? Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; bool RPtrToVoid = RPT ? Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; if (!LPtrToVoid && !RPtrToVoid && !Context.typesAreCompatible(lType, rType)) { Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); ImpCastExprToType(rex, lType); return ResultTy; } ImpCastExprToType(rex, lType); return ResultTy; } if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { ImpCastExprToType(rex, lType); return ResultTy; } else { if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) { Diag(Loc, diag::warn_incompatible_qualified_id_operands) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); ImpCastExprToType(rex, lType); return ResultTy; } } } if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && rType->isIntegerType()) { if (!RHSIsNull) Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); ImpCastExprToType(rex, lType); // promote the integer to pointer return ResultTy; } if (lType->isIntegerType() && (rType->isPointerType() || rType->isObjCQualifiedIdType())) { if (!LHSIsNull) Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); ImpCastExprToType(lex, rType); // promote the integer to pointer return ResultTy; } // Handle block pointers. if (lType->isBlockPointerType() && rType->isIntegerType()) { if (!RHSIsNull) Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); ImpCastExprToType(rex, lType); // promote the integer to pointer return ResultTy; } if (lType->isIntegerType() && rType->isBlockPointerType()) { if (!LHSIsNull) Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); ImpCastExprToType(lex, rType); // promote the integer to pointer return ResultTy; } return InvalidOperands(Loc, lex, rex); } /// CheckVectorCompareOperands - vector comparisons are a clang extension that /// operates on extended vector types. Instead of producing an IntTy result, /// like a scalar comparison, a vector comparison produces a vector of integer /// types. QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, bool isRelational) { // Check to make sure we're operating on vectors of the same type and width, // Allowing one side to be a scalar of element type. QualType vType = CheckVectorOperands(Loc, lex, rex); if (vType.isNull()) return vType; QualType lType = lex->getType(); QualType rType = rex->getType(); // For non-floating point types, check for self-comparisons of the form // x == x, x != x, x < x, etc. These always evaluate to a constant, and // often indicate logic errors in the program. if (!lType->isFloatingType()) { if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) if (DRL->getDecl() == DRR->getDecl()) Diag(Loc, diag::warn_selfcomparison); } // Check for comparisons of floating point operands using != and ==. if (!isRelational && lType->isFloatingType()) { assert (rType->isFloatingType()); CheckFloatComparison(Loc,lex,rex); } // FIXME: Vector compare support in the LLVM backend is not fully reliable, // just reject all vector comparisons for now. if (1) { Diag(Loc, diag::err_typecheck_vector_comparison) << lType << rType << lex->getSourceRange() << rex->getSourceRange(); return QualType(); } // Return the type for the comparison, which is the same as vector type for // integer vectors, or an integer type of identical size and number of // elements for floating point vectors. if (lType->isIntegerType()) return lType; const VectorType *VTy = lType->getAsVectorType(); unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); if (TypeSize == Context.getTypeSize(Context.IntTy)) return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); if (TypeSize == Context.getTypeSize(Context.LongTy)) return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && "Unhandled vector element size in vector compare"); return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); } inline QualType Sema::CheckBitwiseOperands( Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) return CheckVectorOperands(Loc, lex, rex); QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) return compType; return InvalidOperands(Loc, lex, rex); } inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] Expr *&lex, Expr *&rex, SourceLocation Loc) { UsualUnaryConversions(lex); UsualUnaryConversions(rex); if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) return Context.IntTy; return InvalidOperands(Loc, lex, rex); } /// IsReadonlyProperty - Verify that otherwise a valid l-value expression /// is a read-only property; return true if so. A readonly property expression /// depends on various declarations and thus must be treated specially. /// static bool IsReadonlyProperty(Expr *E, Sema &S) { if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { QualType BaseType = PropExpr->getBase()->getType(); if (const PointerType *PTy = BaseType->getAsPointerType()) if (const ObjCInterfaceType *IFTy = PTy->getPointeeType()->getAsObjCInterfaceType()) if (ObjCInterfaceDecl *IFace = IFTy->getDecl()) if (S.isPropertyReadonly(PDecl, IFace)) return true; } } return false; } /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, /// emit an error and return true. If so, return false. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { SourceLocation OrigLoc = Loc; Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, &Loc); if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) IsLV = Expr::MLV_ReadonlyProperty; if (IsLV == Expr::MLV_Valid) return false; unsigned Diag = 0; bool NeedType = false; switch (IsLV) { // C99 6.5.16p2 default: assert(0 && "Unknown result from isModifiableLvalue!"); case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; case Expr::MLV_ArrayType: Diag = diag::err_typecheck_array_not_modifiable_lvalue; NeedType = true; break; case Expr::MLV_NotObjectType: Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; NeedType = true; break; case Expr::MLV_LValueCast: Diag = diag::err_typecheck_lvalue_casts_not_supported; break; case Expr::MLV_InvalidExpression: Diag = diag::err_typecheck_expression_not_modifiable_lvalue; break; case Expr::MLV_IncompleteType: case Expr::MLV_IncompleteVoidType: return S.RequireCompleteType(Loc, E->getType(), diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E->getSourceRange()); case Expr::MLV_DuplicateVectorComponents: Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; break; case Expr::MLV_NotBlockQualified: Diag = diag::err_block_decl_ref_not_modifiable_lvalue; break; case Expr::MLV_ReadonlyProperty: Diag = diag::error_readonly_property_assignment; break; case Expr::MLV_NoSetterProperty: Diag = diag::error_nosetter_property_assignment; break; } SourceRange Assign; if (Loc != OrigLoc) Assign = SourceRange(OrigLoc, OrigLoc); if (NeedType) S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; else S.Diag(Loc, Diag) << E->getSourceRange() << Assign; return true; } // C99 6.5.16.1 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc, QualType CompoundType) { // Verify that LHS is a modifiable lvalue, and emit error if not. if (CheckForModifiableLvalue(LHS, Loc, *this)) return QualType(); QualType LHSType = LHS->getType(); QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; AssignConvertType ConvTy; if (CompoundType.isNull()) { // Simple assignment "x = y". ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); // Special case of NSObject attributes on c-style pointer types. if (ConvTy == IncompatiblePointer && ((Context.isObjCNSObjectType(LHSType) && Context.isObjCObjectPointerType(RHSType)) || (Context.isObjCNSObjectType(RHSType) && Context.isObjCObjectPointerType(LHSType)))) ConvTy = Compatible; // If the RHS is a unary plus or minus, check to see if they = and + are // right next to each other. If so, the user may have typo'd "x =+ 4" // instead of "x += 4". Expr *RHSCheck = RHS; if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) RHSCheck = ICE->getSubExpr(); if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { if ((UO->getOpcode() == UnaryOperator::Plus || UO->getOpcode() == UnaryOperator::Minus) && Loc.isFileID() && UO->getOperatorLoc().isFileID() && // Only if the two operators are exactly adjacent. Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && // And there is a space or other character before the subexpr of the // unary +/-. We don't want to warn on "x=-1". Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && UO->getSubExpr()->getLocStart().isFileID()) { Diag(Loc, diag::warn_not_compound_assign) << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); } } } else { // Compound assignment "x += y" ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType); } if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS, "assigning")) return QualType(); // C99 6.5.16p3: The type of an assignment expression is the type of the // left operand unless the left operand has qualified type, in which case // it is the unqualified version of the type of the left operand. // C99 6.5.16.1p2: In simple assignment, the value of the right operand // is converted to the type of the assignment expression (above). // C++ 5.17p1: the type of the assignment expression is that of its left // oprdu. return LHSType.getUnqualifiedType(); } // C99 6.5.17 QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. DefaultFunctionArrayConversion(RHS); // FIXME: Check that RHS type is complete in C mode (it's legal for it to be // incomplete in C++). return RHS->getType(); } /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, bool isInc) { if (Op->isTypeDependent()) return Context.DependentTy; QualType ResType = Op->getType(); assert(!ResType.isNull() && "no type for increment/decrement expression"); if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { // Decrement of bool is not allowed. if (!isInc) { Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); return QualType(); } // Increment of bool sets it to true, but is deprecated. Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); } else if (ResType->isRealType()) { // OK! } else if (const PointerType *PT = ResType->getAsPointerType()) { // C99 6.5.2.4p2, 6.5.6p2 if (PT->getPointeeType()->isVoidType()) { if (getLangOptions().CPlusPlus) { Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) << Op->getSourceRange(); return QualType(); } // Pointer to void is a GNU extension in C. Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); } else if (PT->getPointeeType()->isFunctionType()) { if (getLangOptions().CPlusPlus) { Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) << Op->getType() << Op->getSourceRange(); return QualType(); } Diag(OpLoc, diag::ext_gnu_ptr_func_arith) << ResType << Op->getSourceRange(); } else if (RequireCompleteType(OpLoc, PT->getPointeeType(), diag::err_typecheck_arithmetic_incomplete_type, Op->getSourceRange(), SourceRange(), ResType)) return QualType(); } else if (ResType->isComplexType()) { // C99 does not support ++/-- on complex types, we allow as an extension. Diag(OpLoc, diag::ext_integer_increment_complex) << ResType << Op->getSourceRange(); } else { Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) << ResType << Op->getSourceRange(); return QualType(); } // At this point, we know we have a real, complex or pointer type. // Now make sure the operand is a modifiable lvalue. if (CheckForModifiableLvalue(Op, OpLoc, *this)) return QualType(); return ResType; } /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). /// This routine allows us to typecheck complex/recursive expressions /// where the declaration is needed for type checking. We only need to /// handle cases when the expression references a function designator /// or is an lvalue. Here are some examples: /// - &(x) => x /// - &*****f => f for f a function designator. /// - &s.xx => s /// - &s.zz[1].yy -> s, if zz is an array /// - *(x + 1) -> x, if x is an array /// - &"123"[2] -> 0 /// - & __real__ x -> x static NamedDecl *getPrimaryDecl(Expr *E) { switch (E->getStmtClass()) { case Stmt::DeclRefExprClass: case Stmt::QualifiedDeclRefExprClass: return cast<DeclRefExpr>(E)->getDecl(); case Stmt::MemberExprClass: // Fields cannot be declared with a 'register' storage class. // &X->f is always ok, even if X is declared register. if (cast<MemberExpr>(E)->isArrow()) return 0; return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); case Stmt::ArraySubscriptExprClass: { // &X[4] and &4[X] refers to X if X is not a pointer. NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); if (!VD || VD->getType()->isPointerType()) return 0; else return VD; } case Stmt::UnaryOperatorClass: { UnaryOperator *UO = cast<UnaryOperator>(E); switch(UO->getOpcode()) { case UnaryOperator::Deref: { // *(X + 1) refers to X if X is not a pointer. if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) { ValueDecl *VD = dyn_cast<ValueDecl>(D); if (!VD || VD->getType()->isPointerType()) return 0; return VD; } return 0; } case UnaryOperator::Real: case UnaryOperator::Imag: case UnaryOperator::Extension: return getPrimaryDecl(UO->getSubExpr()); default: return 0; } } case Stmt::BinaryOperatorClass: { BinaryOperator *BO = cast<BinaryOperator>(E); // Handle cases involving pointer arithmetic. The result of an // Assign or AddAssign is not an lvalue so they can be ignored. // (x + n) or (n + x) => x if (BO->getOpcode() == BinaryOperator::Add) { if (BO->getLHS()->getType()->isPointerType()) { return getPrimaryDecl(BO->getLHS()); } else if (BO->getRHS()->getType()->isPointerType()) { return getPrimaryDecl(BO->getRHS()); } } return 0; } case Stmt::ParenExprClass: return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); case Stmt::ImplicitCastExprClass: // &X[4] when X is an array, has an implicit cast from array to pointer. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); default: return 0; } } /// CheckAddressOfOperand - The operand of & must be either a function /// designator or an lvalue designating an object. If it is an lvalue, the /// object cannot be declared with storage class register or be a bit field. /// Note: The usual conversions are *not* applied to the operand of the & /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. /// In C++, the operand might be an overloaded function name, in which case /// we allow the '&' but retain the overloaded-function type. QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { if (op->isTypeDependent()) return Context.DependentTy; if (getLangOptions().C99) { // Implement C99-only parts of addressof rules. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { if (uOp->getOpcode() == UnaryOperator::Deref) // Per C99 6.5.3.2, the address of a deref always returns a valid result // (assuming the deref expression is valid). return uOp->getSubExpr()->getType(); } // Technically, there should be a check for array subscript // expressions here, but the result of one is always an lvalue anyway. } NamedDecl *dcl = getPrimaryDecl(op); Expr::isLvalueResult lval = op->isLvalue(Context); if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators // FIXME: emit more specific diag... Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) << op->getSourceRange(); return QualType(); } } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) { if (Field->isBitField()) { Diag(OpLoc, diag::err_typecheck_address_of) << "bit-field" << op->getSourceRange(); return QualType(); } } // Check for Apple extension for accessing vector components. } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) && cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){ Diag(OpLoc, diag::err_typecheck_address_of) << "vector element" << op->getSourceRange(); return QualType(); } else if (dcl) { // C99 6.5.3.2p1 // We have an lvalue with a decl. Make sure the decl is not declared // with the register storage-class specifier. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { if (vd->getStorageClass() == VarDecl::Register) { Diag(OpLoc, diag::err_typecheck_address_of) << "register variable" << op->getSourceRange(); return QualType(); } } else if (isa<OverloadedFunctionDecl>(dcl)) { return Context.OverloadTy; } else if (isa<FieldDecl>(dcl)) { // Okay: we can take the address of a field. // Could be a pointer to member, though, if there is an explicit // scope qualifier for the class. if (isa<QualifiedDeclRefExpr>(op)) { DeclContext *Ctx = dcl->getDeclContext(); if (Ctx && Ctx->isRecord()) return Context.getMemberPointerType(op->getType(), Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); } } else if (isa<FunctionDecl>(dcl)) { // Okay: we can take the address of a function. // As above. if (isa<QualifiedDeclRefExpr>(op)) { DeclContext *Ctx = dcl->getDeclContext(); if (Ctx && Ctx->isRecord()) return Context.getMemberPointerType(op->getType(), Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); } } else assert(0 && "Unknown/unexpected decl type"); } // If the operand has type "type", the result has type "pointer to type". return Context.getPointerType(op->getType()); } QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { if (Op->isTypeDependent()) return Context.DependentTy; UsualUnaryConversions(Op); QualType Ty = Op->getType(); // Note that per both C89 and C99, this is always legal, even if ptype is an // incomplete type or void. It would be possible to warn about dereferencing // a void pointer, but it's completely well-defined, and such a warning is // unlikely to catch any mistakes. if (const PointerType *PT = Ty->getAsPointerType()) return PT->getPointeeType(); Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) << Ty << Op->getSourceRange(); return QualType(); } static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( tok::TokenKind Kind) { BinaryOperator::Opcode Opc; switch (Kind) { default: assert(0 && "Unknown binop!"); case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; case tok::star: Opc = BinaryOperator::Mul; break; case tok::slash: Opc = BinaryOperator::Div; break; case tok::percent: Opc = BinaryOperator::Rem; break; case tok::plus: Opc = BinaryOperator::Add; break; case tok::minus: Opc = BinaryOperator::Sub; break; case tok::lessless: Opc = BinaryOperator::Shl; break; case tok::greatergreater: Opc = BinaryOperator::Shr; break; case tok::lessequal: Opc = BinaryOperator::LE; break; case tok::less: Opc = BinaryOperator::LT; break; case tok::greaterequal: Opc = BinaryOperator::GE; break; case tok::greater: Opc = BinaryOperator::GT; break; case tok::exclaimequal: Opc = BinaryOperator::NE; break; case tok::equalequal: Opc = BinaryOperator::EQ; break; case tok::amp: Opc = BinaryOperator::And; break; case tok::caret: Opc = BinaryOperator::Xor; break; case tok::pipe: Opc = BinaryOperator::Or; break; case tok::ampamp: Opc = BinaryOperator::LAnd; break; case tok::pipepipe: Opc = BinaryOperator::LOr; break; case tok::equal: Opc = BinaryOperator::Assign; break; case tok::starequal: Opc = BinaryOperator::MulAssign; break; case tok::slashequal: Opc = BinaryOperator::DivAssign; break; case tok::percentequal: Opc = BinaryOperator::RemAssign; break; case tok::plusequal: Opc = BinaryOperator::AddAssign; break; case tok::minusequal: Opc = BinaryOperator::SubAssign; break; case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; case tok::ampequal: Opc = BinaryOperator::AndAssign; break; case tok::caretequal: Opc = BinaryOperator::XorAssign; break; case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; case tok::comma: Opc = BinaryOperator::Comma; break; } return Opc; } static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( tok::TokenKind Kind) { UnaryOperator::Opcode Opc; switch (Kind) { default: assert(0 && "Unknown unary op!"); case tok::plusplus: Opc = UnaryOperator::PreInc; break; case tok::minusminus: Opc = UnaryOperator::PreDec; break; case tok::amp: Opc = UnaryOperator::AddrOf; break; case tok::star: Opc = UnaryOperator::Deref; break; case tok::plus: Opc = UnaryOperator::Plus; break; case tok::minus: Opc = UnaryOperator::Minus; break; case tok::tilde: Opc = UnaryOperator::Not; break; case tok::exclaim: Opc = UnaryOperator::LNot; break; case tok::kw___real: Opc = UnaryOperator::Real; break; case tok::kw___imag: Opc = UnaryOperator::Imag; break; case tok::kw___extension__: Opc = UnaryOperator::Extension; break; } return Opc; } /// CreateBuiltinBinOp - Creates a new built-in binary operation with /// operator @p Opc at location @c TokLoc. This routine only supports /// built-in operations; ActOnBinOp handles overloaded operators. Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, unsigned Op, Expr *lhs, Expr *rhs) { QualType ResultTy; // Result type of the binary operator. BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; // The following two variables are used for compound assignment operators QualType CompLHSTy; // Type of LHS after promotions for computation QualType CompResultTy; // Type of computation result switch (Opc) { case BinaryOperator::Assign: ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); break; case BinaryOperator::PtrMemD: case BinaryOperator::PtrMemI: ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, Opc == BinaryOperator::PtrMemI); break; case BinaryOperator::Mul: case BinaryOperator::Div: ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); break; case BinaryOperator::Rem: ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); break; case BinaryOperator::Add: ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); break; case BinaryOperator::Sub: ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); break; case BinaryOperator::Shl: case BinaryOperator::Shr: ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); break; case BinaryOperator::LE: case BinaryOperator::LT: case BinaryOperator::GE: case BinaryOperator::GT: ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); break; case BinaryOperator::EQ: case BinaryOperator::NE: ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); break; case BinaryOperator::And: case BinaryOperator::Xor: case BinaryOperator::Or: ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); break; case BinaryOperator::LAnd: case BinaryOperator::LOr: ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); break; case BinaryOperator::MulAssign: case BinaryOperator::DivAssign: CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); CompLHSTy = CompResultTy; if (!CompResultTy.isNull()) ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); break; case BinaryOperator::RemAssign: CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); CompLHSTy = CompResultTy; if (!CompResultTy.isNull()) ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); break; case BinaryOperator::AddAssign: CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); if (!CompResultTy.isNull()) ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); break; case BinaryOperator::SubAssign: CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); if (!CompResultTy.isNull()) ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); break; case BinaryOperator::ShlAssign: case BinaryOperator::ShrAssign: CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true); CompLHSTy = CompResultTy; if (!CompResultTy.isNull()) ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); break; case BinaryOperator::AndAssign: case BinaryOperator::XorAssign: case BinaryOperator::OrAssign: CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); CompLHSTy = CompResultTy; if (!CompResultTy.isNull()) ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); break; case BinaryOperator::Comma: ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); break; } if (ResultTy.isNull()) return ExprError(); if (CompResultTy.isNull()) return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); else return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompLHSTy, CompResultTy, OpLoc)); } // Binary Operators. 'Tok' is the token for the operator. Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, ExprArg LHS, ExprArg RHS) { BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release(); assert((lhs != 0) && "ActOnBinOp(): missing left expression"); assert((rhs != 0) && "ActOnBinOp(): missing right expression"); if (getLangOptions().CPlusPlus && (lhs->getType()->isOverloadableType() || rhs->getType()->isOverloadableType())) { // Find all of the overloaded operators visible from this // point. We perform both an operator-name lookup from the local // scope and an argument-dependent lookup based on the types of // the arguments. FunctionSet Functions; OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); if (OverOp != OO_None) { LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), Functions); Expr *Args[2] = { lhs, rhs }; DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OverOp); ArgumentDependentLookup(OpName, Args, 2, Functions); } // Build the (potentially-overloaded, potentially-dependent) // binary operation. return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs); } // Build a built-in binary operation. return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); } Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, unsigned OpcIn, ExprArg InputArg) { UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); // FIXME: Input is modified below, but InputArg is not updated // appropriately. Expr *Input = (Expr *)InputArg.get(); QualType resultType; switch (Opc) { case UnaryOperator::PostInc: case UnaryOperator::PostDec: case UnaryOperator::OffsetOf: assert(false && "Invalid unary operator"); break; case UnaryOperator::PreInc: case UnaryOperator::PreDec: resultType = CheckIncrementDecrementOperand(Input, OpLoc, Opc == UnaryOperator::PreInc); break; case UnaryOperator::AddrOf: resultType = CheckAddressOfOperand(Input, OpLoc); break; case UnaryOperator::Deref: DefaultFunctionArrayConversion(Input); resultType = CheckIndirectionOperand(Input, OpLoc); break; case UnaryOperator::Plus: case UnaryOperator::Minus: UsualUnaryConversions(Input); resultType = Input->getType(); if (resultType->isDependentType()) break; if (resultType->isArithmeticType()) // C99 6.5.3.3p1 break; else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 resultType->isEnumeralType()) break; else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 Opc == UnaryOperator::Plus && resultType->isPointerType()) break; return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) << resultType << Input->getSourceRange()); case UnaryOperator::Not: // bitwise complement UsualUnaryConversions(Input); resultType = Input->getType(); if (resultType->isDependentType()) break; // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. if (resultType->isComplexType() || resultType->isComplexIntegerType()) // C99 does not support '~' for complex conjugation. Diag(OpLoc, diag::ext_integer_complement_complex) << resultType << Input->getSourceRange(); else if (!resultType->isIntegerType()) return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) << resultType << Input->getSourceRange()); break; case UnaryOperator::LNot: // logical negation // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). DefaultFunctionArrayConversion(Input); resultType = Input->getType(); if (resultType->isDependentType()) break; if (!resultType->isScalarType()) // C99 6.5.3.3p1 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) << resultType << Input->getSourceRange()); // LNot always has type int. C99 6.5.3.3p5. // In C++, it's bool. C++ 5.3.1p8 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; break; case UnaryOperator::Real: case UnaryOperator::Imag: resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); break; case UnaryOperator::Extension: resultType = Input->getType(); break; } if (resultType.isNull()) return ExprError(); InputArg.release(); return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); } // Unary Operators. 'Tok' is the token for the operator. Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, ExprArg input) { Expr *Input = (Expr*)input.get(); UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) { // Find all of the overloaded operators visible from this // point. We perform both an operator-name lookup from the local // scope and an argument-dependent lookup based on the types of // the arguments. FunctionSet Functions; OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); if (OverOp != OO_None) { LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), Functions); DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OverOp); ArgumentDependentLookup(OpName, &Input, 1, Functions); } return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input)); } return CreateBuiltinUnaryOp(OpLoc, Opc, move(input)); } /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, IdentifierInfo *LabelII) { // Look up the record for this label identifier. LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] : LabelMap[LabelII]; // If we haven't seen this label yet, create a forward reference. It // will be validated and/or cleaned up in ActOnFinishFunctionBody. if (LabelDecl == 0) LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); // Create the AST node. The address of a label always has type 'void*'. return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, Context.getPointerType(Context.VoidTy))); } Sema::OwningExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt, SourceLocation RPLoc) { // "({..})" Stmt *SubStmt = static_cast<Stmt*>(substmt.get()); assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); bool isFileScope = getCurFunctionOrMethodDecl() == 0; if (isFileScope) { return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); } // FIXME: there are a variety of strange constraints to enforce here, for // example, it is not possible to goto into a stmt expression apparently. // More semantic analysis is needed. // FIXME: the last statement in the compount stmt has its value used. We // should not warn about it being unused. // If there are sub stmts in the compound stmt, take the type of the last one // as the type of the stmtexpr. QualType Ty = Context.VoidTy; if (!Compound->body_empty()) { Stmt *LastStmt = Compound->body_back(); // If LastStmt is a label, skip down through into the body. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) LastStmt = Label->getSubStmt(); if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) Ty = LastExpr->getType(); } // FIXME: Check that expression type is complete/non-abstract; statement // expressions are not lvalues. substmt.release(); return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc)); } Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, TypeTy *argty, OffsetOfComponent *CompPtr, unsigned NumComponents, SourceLocation RPLoc) { // FIXME: This function leaks all expressions in the offset components on // error. QualType ArgTy = QualType::getFromOpaquePtr(argty); assert(!ArgTy.isNull() && "Missing type argument!"); bool Dependent = ArgTy->isDependentType(); // We must have at least one component that refers to the type, and the first // one is known to be a field designator. Verify that the ArgTy represents // a struct/union/class. if (!Dependent && !ArgTy->isRecordType()) return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy); // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable // with an incomplete type would be illegal. // Otherwise, create a null pointer as the base, and iteratively process // the offsetof designators. QualType ArgTyPtr = Context.getPointerType(ArgTy); Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr); Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref, ArgTy, SourceLocation()); // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a // GCC extension, diagnose them. // FIXME: This diagnostic isn't actually visible because the location is in // a system header! if (NumComponents != 1) Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); if (!Dependent) { // FIXME: Dependent case loses a lot of information here. And probably // leaks like a sieve. for (unsigned i = 0; i != NumComponents; ++i) { const OffsetOfComponent &OC = CompPtr[i]; if (OC.isBrackets) { // Offset of an array sub-field. TODO: Should we allow vector elements? const ArrayType *AT = Context.getAsArrayType(Res->getType()); if (!AT) { Res->Destroy(Context); return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType()); } // FIXME: C++: Verify that operator[] isn't overloaded. // Promote the array so it looks more like a normal array subscript // expression. DefaultFunctionArrayConversion(Res); // C99 6.5.2.1p1 Expr *Idx = static_cast<Expr*>(OC.U.E); // FIXME: Leaks Res if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType()) return ExprError(Diag(Idx->getLocStart(), diag::err_typecheck_subscript) << Idx->getSourceRange()); Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd); continue; } const RecordType *RC = Res->getType()->getAsRecordType(); if (!RC) { Res->Destroy(Context); return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType()); } // Get the decl corresponding to this. RecordDecl *RD = RC->getDecl(); FieldDecl *MemberDecl = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo, LookupMemberName) .getAsDecl()); // FIXME: Leaks Res if (!MemberDecl) return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member) << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd)); // FIXME: C++: Verify that MemberDecl isn't a static field. // FIXME: Verify that MemberDecl isn't a bitfield. // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't // matter here. Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType().getNonReferenceType()); } } return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(), BuiltinLoc)); } Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, TypeTy *arg1,TypeTy *arg2, SourceLocation RPLoc) { QualType argT1 = QualType::getFromOpaquePtr(arg1); QualType argT2 = QualType::getFromOpaquePtr(arg2); assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc)); } Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprArg cond, ExprArg expr1, ExprArg expr2, SourceLocation RPLoc) { Expr *CondExpr = static_cast<Expr*>(cond.get()); Expr *LHSExpr = static_cast<Expr*>(expr1.get()); Expr *RHSExpr = static_cast<Expr*>(expr2.get()); assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); QualType resType; if (CondExpr->isValueDependent()) { resType = Context.DependentTy; } else { // The conditional expression is required to be a constant expression. llvm::APSInt condEval(32); SourceLocation ExpLoc; if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) return ExprError(Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant) << CondExpr->getSourceRange()); // If the condition is > zero, then the AST type is the same as the LSHExpr. resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); } cond.release(); expr1.release(); expr2.release(); return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc)); } //===----------------------------------------------------------------------===// // Clang Extensions. //===----------------------------------------------------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is started. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { // Analyze block parameters. BlockSemaInfo *BSI = new BlockSemaInfo(); // Add BSI to CurBlock. BSI->PrevBlockInfo = CurBlock; CurBlock = BSI; BSI->ReturnType = 0; BSI->TheScope = BlockScope; BSI->hasBlockDeclRefExprs = false; BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); PushDeclContext(BlockScope, BSI->TheDecl); } void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!"); if (ParamInfo.getNumTypeObjects() == 0 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) { QualType T = GetTypeForDeclarator(ParamInfo, CurScope); // The type is entirely optional as well, if none, use DependentTy. if (T.isNull()) T = Context.DependentTy; // The parameter list is optional, if there was none, assume (). if (!T->isFunctionType()) T = Context.getFunctionType(T, NULL, 0, 0, 0); CurBlock->hasPrototype = true; CurBlock->isVariadic = false; QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType(); // Do not allow returning a objc interface by-value. if (RetTy->isObjCInterfaceType()) { Diag(ParamInfo.getSourceRange().getBegin(), diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; return; } if (!RetTy->isDependentType()) CurBlock->ReturnType = RetTy.getTypePtr(); return; } // Analyze arguments to block. assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && "Not a function declarator!"); DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; CurBlock->hasPrototype = FTI.hasPrototype; CurBlock->isVariadic = true; // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes // no arguments, not a function that takes a single void argument. if (FTI.hasPrototype && FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&& FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) { // empty arg list, don't push any params. CurBlock->isVariadic = false; } else if (FTI.hasPrototype) { for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>()); CurBlock->isVariadic = FTI.isVariadic; } CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0], CurBlock->Params.size()); for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), E = CurBlock->TheDecl->param_end(); AI != E; ++AI) // If this has an identifier, add it to the scope stack. if ((*AI)->getIdentifier()) PushOnScopeChains(*AI, CurBlock->TheScope); // Analyze the return type. QualType T = GetTypeForDeclarator(ParamInfo, CurScope); QualType RetTy = T->getAsFunctionType()->getResultType(); // Do not allow returning a objc interface by-value. if (RetTy->isObjCInterfaceType()) { Diag(ParamInfo.getSourceRange().getBegin(), diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; } else if (!RetTy->isDependentType()) CurBlock->ReturnType = RetTy.getTypePtr(); } /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { // Ensure that CurBlock is deleted. llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); // Pop off CurBlock, handle nested blocks. CurBlock = CurBlock->PrevBlockInfo; // FIXME: Delete the ParmVarDecl objects as well??? } /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtArg body, Scope *CurScope) { // If blocks are disabled, emit an error. if (!LangOpts.Blocks) Diag(CaretLoc, diag::err_blocks_disable); // Ensure that CurBlock is deleted. llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); PopDeclContext(); // Pop off CurBlock, handle nested blocks. CurBlock = CurBlock->PrevBlockInfo; QualType RetTy = Context.VoidTy; if (BSI->ReturnType) RetTy = QualType(BSI->ReturnType, 0); llvm::SmallVector<QualType, 8> ArgTypes; for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) ArgTypes.push_back(BSI->Params[i]->getType()); QualType BlockTy; if (!BSI->hasPrototype) BlockTy = Context.getFunctionNoProtoType(RetTy); else BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(), BSI->isVariadic, 0); // FIXME: Check that return/parameter types are complete/non-abstract BlockTy = Context.getBlockPointerType(BlockTy); BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release())); return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs)); } Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, ExprArg expr, TypeTy *type, SourceLocation RPLoc) { QualType T = QualType::getFromOpaquePtr(type); Expr *E = static_cast<Expr*>(expr.get()); Expr *OrigExpr = E; InitBuiltinVaListType(); // Get the va_list type QualType VaListType = Context.getBuiltinVaListType(); // Deal with implicit array decay; for example, on x86-64, // va_list is an array, but it's supposed to decay to // a pointer for va_arg. if (VaListType->isArrayType()) VaListType = Context.getArrayDecayedType(VaListType); // Make sure the input expression also decays appropriately. UsualUnaryConversions(E); if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) { return ExprError(Diag(E->getLocStart(), diag::err_first_argument_to_va_arg_not_of_type_va_list) << OrigExpr->getType() << E->getSourceRange()); } // FIXME: Check that type is complete/non-abstract // FIXME: Warn if a non-POD type is passed in. expr.release(); return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc)); } Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { // The type of __null will be int or long, depending on the size of // pointers on the target. QualType Ty; if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) Ty = Context.IntTy; else Ty = Context.LongTy; return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); } bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, const char *Flavor) { // Decode the result (notice that AST's are still created for extensions). bool isInvalid = false; unsigned DiagKind; switch (ConvTy) { default: assert(0 && "Unknown conversion type"); case Compatible: return false; case PointerToInt: DiagKind = diag::ext_typecheck_convert_pointer_int; break; case IntToPointer: DiagKind = diag::ext_typecheck_convert_int_pointer; break; case IncompatiblePointer: DiagKind = diag::ext_typecheck_convert_incompatible_pointer; break; case IncompatiblePointerSign: DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; break; case FunctionVoidPointer: DiagKind = diag::ext_typecheck_convert_pointer_void_func; break; case CompatiblePointerDiscardsQualifiers: // If the qualifiers lost were because we were applying the // (deprecated) C++ conversion from a string literal to a char* // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: // Ideally, this check would be performed in // CheckPointerTypesForAssignment. However, that would require a // bit of refactoring (so that the second argument is an // expression, rather than a type), which should be done as part // of a larger effort to fix CheckPointerTypesForAssignment for // C++ semantics. if (getLangOptions().CPlusPlus && IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) return false; DiagKind = diag::ext_typecheck_convert_discards_qualifiers; break; case IntToBlockPointer: DiagKind = diag::err_int_to_block_pointer; break; case IncompatibleBlockPointer: DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer; break; case IncompatibleObjCQualifiedId: // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since // it can give a more specific diagnostic. DiagKind = diag::warn_incompatible_qualified_id; break; case IncompatibleVectors: DiagKind = diag::warn_incompatible_vectors; break; case Incompatible: DiagKind = diag::err_typecheck_convert_incompatible; isInvalid = true; break; } Diag(Loc, DiagKind) << DstType << SrcType << Flavor << SrcExpr->getSourceRange(); return isInvalid; } bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result) { Expr::EvalResult EvalResult; if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || EvalResult.HasSideEffects) { Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); if (EvalResult.Diag) { // We only show the note if it's not the usual "invalid subexpression" // or if it's actually in a subexpression. if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) Diag(EvalResult.DiagLoc, EvalResult.Diag); } return true; } if (EvalResult.Diag) { Diag(E->getExprLoc(), diag::ext_expr_not_ice) << E->getSourceRange(); // Print the reason it's not a constant. if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) Diag(EvalResult.DiagLoc, EvalResult.Diag); } if (Result) *Result = EvalResult.Val.getInt(); return false; } <file_sep>/lib/Parse/ParsePragma.h //===---- ParserPragmas.h - Language specific pragmas -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines #pragma handlers for language specific pragmas. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSEPRAGMA_H #define LLVM_CLANG_PARSE_PARSEPRAGMA_H #include "clang/Lex/Pragma.h" namespace clang { class Action; class Parser; class PragmaPackHandler : public PragmaHandler { Action &Actions; public: PragmaPackHandler(const IdentifierInfo *N, Action &A) : PragmaHandler(N), Actions(A) {} virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); }; class PragmaUnusedHandler : public PragmaHandler { Action &Actions; Parser &parser; public: PragmaUnusedHandler(const IdentifierInfo *N, Action &A, Parser& p) : PragmaHandler(N), Actions(A), parser(p) {} virtual void HandlePragma(Preprocessor &PP, Token &FirstToken); }; } // end namespace clang #endif <file_sep>/tools/ccc/ccclib/HostInfo.py import ToolChain import Types class HostInfo(object): """HostInfo - Config information about a particular host which may interact with driver behavior. This can be very different from the target(s) of a particular driver invocation.""" def __init__(self, driver): self.driver = driver def getArchName(self, args): abstract def useDriverDriver(self): abstract def lookupTypeForExtension(self, ext): abstract def getToolChain(self): abstract def getToolChainForArch(self, arch): raise RuntimeError,"getToolChainForArch() unsupported on this host." # Darwin class DarwinHostInfo(HostInfo): def __init__(self, driver): super(DarwinHostInfo, self).__init__(driver) # FIXME: Find right regex for this. import re m = re.match(r'([0-9]+)\.([0-9]+)\.([0-9]+)', driver.getHostReleaseName()) if not m: raise RuntimeError,"Unable to determine Darwin version." self.darwinVersion = tuple(map(int, m.groups())) self.gccVersion = (4,2,1) def useDriverDriver(self): return True def lookupTypeForExtension(self, ext): ty = Types.kTypeSuffixMap.get(ext) if ty is Types.AsmTypeNoPP: return Types.AsmType return ty def getToolChain(self): return self.getToolChainForArch(self.getArchName(None)) def getToolChainForArch(self, arch): if arch in ('i386', 'x86_64'): return ToolChain.Darwin_X86_ToolChain(self.driver, arch, self.darwinVersion, self.gccVersion) return ToolChain.Darwin_GCC_ToolChain(self.driver, arch) class DarwinPPCHostInfo(DarwinHostInfo): def getArchName(self, args): if args and args.getLastArg(args.parser.m_64Option): return 'ppc64' return 'ppc' class DarwinPPC_64HostInfo(DarwinHostInfo): def getArchName(self, args): if args and args.getLastArg(args.parser.m_32Option): return 'ppc' return 'ppc64' class DarwinX86HostInfo(DarwinHostInfo): def getArchName(self, args): if args and args.getLastArg(args.parser.m_64Option): return 'x86_64' return 'i386' class DarwinX86_64HostInfo(DarwinHostInfo): def getArchName(self, args): if args and args.getLastArg(args.parser.m_32Option): return 'i386' return 'x86_64' def getDarwinHostInfo(driver): machine = driver.getHostMachine() bits = driver.getHostBits() if machine == 'i386': if bits == '32': return DarwinX86HostInfo(driver) if bits == '64': return DarwinX86_64HostInfo(driver) elif machine == 'ppc': if bits == '32': return DarwinPPCHostInfo(driver) if bits == '64': return DarwinPPC_64HostInfo(driver) raise RuntimeError,'Unrecognized Darwin platform: %r:%r' % (machine, bits) # Unknown class UnknownHostInfo(HostInfo): def getArchName(self, args): raise RuntimeError,'getArchName() unsupported on unknown host.' def useDriverDriver(self): return False def lookupTypeForExtension(self, ext): return Types.kTypeSuffixMap.get(ext) def getToolChain(self): return ToolChain.Generic_GCC_ToolChain(self.driver, '') def getUnknownHostInfo(driver): return UnknownHostInfo(driver) #### kSystems = { 'darwin' : getDarwinHostInfo, 'unknown' : getUnknownHostInfo, } def getHostInfo(driver): system = driver.getHostSystemName() handler = kSystems.get(system) if handler: return handler(driver) return UnknownHostInfo(driver) <file_sep>/lib/Headers/stdint.h /*===---- stdint.h - Standard header for sized integer types --------------===*\ * * Copyright (c) 2009 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * \*===----------------------------------------------------------------------===*/ #ifndef __STDINT_H #define __STDINT_H /* We currently only support targets with power of two, 2s complement integers. */ /* C99 7.18.1.1 Exact-width integer types. * C99 7.18.1.2 Minimum-width integer types. * C99 7.18.1.3 Fastest minimum-width integer types. * Since we only support pow-2 targets, these map directly to exact width types. */ typedef signed __INT8_TYPE__ int8_t; typedef unsigned __INT8_TYPE__ uint8_t; typedef int8_t int_least8_t; typedef uint8_t uint_least8_t; typedef int8_t int_fast8_t; typedef uint8_t uint_fast8_t; typedef __INT16_TYPE__ int16_t; typedef unsigned __INT16_TYPE__ uint16_t; typedef int16_t int_least16_t; typedef uint16_t uint_least16_t; typedef int16_t int_fast16_t; typedef uint16_t uint_fast16_t; typedef __INT32_TYPE__ int32_t; typedef unsigned __INT32_TYPE__ uint32_t; typedef int32_t int_least32_t; typedef uint32_t uint_least32_t; typedef int32_t int_fast32_t; typedef uint32_t uint_fast32_t; /* Some 16-bit targets do not have a 64-bit datatype. Only define the 64-bit * typedefs if there is something to typedef them to. */ #ifdef __INT64_TYPE__ typedef __INT64_TYPE__ int64_t; typedef unsigned __INT64_TYPE__ uint64_t; typedef int64_t int_least64_t; typedef uint64_t uint_least64_t; typedef int64_t int_fast64_t; typedef uint64_t uint_fast64_t; #endif /* C99 7.18.1.4 Integer types capable of holding object pointers. */ #ifndef __intptr_t_defined typedef __INTPTR_TYPE__ intptr_t; #define __intptr_t_defined #endif typedef unsigned __INTPTR_TYPE__ uintptr_t; /* C99 7.18.1.5 Greatest-width integer types. */ typedef __INTMAX_TYPE__ intmax_t; typedef __UINTMAX_TYPE__ uintmax_t; /* C99 7.18.2.1 Limits of exact-width integer types. * Fixed sized values have fixed size max/min. * C99 7.18.2.2 Limits of minimum-width integer types. * Since we map these directly onto fixed-sized types, these values the same. * C99 7.18.2.3 Limits of fastest minimum-width integer types. * * Note that C++ should not check __STDC_LIMIT_MACROS here, contrary to the * claims of the C standard (see C++ 18.3.1p2, [cstdint.syn]). */ #define INT8_MAX 127 #define INT8_MIN (-128) #define UINT8_MAX 255 #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST8_MAX INT8_MAX #define UINT_LEAST8_MAX UINT8_MAX #define INT_FAST8_MIN INT8_MIN #define INT_FAST8_MAX INT8_MAX #define UINT_FAST8_MAX UINT8_MAX #define INT16_MAX 32767 #define INT16_MIN (-32768) #define UINT16_MAX 65535 #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST16_MAX INT16_MAX #define UINT_LEAST16_MAX UINT16_MAX #define INT_FAST16_MIN INT16_MIN #define INT_FAST16_MAX INT16_MAX #define UINT_FAST16_MAX UINT16_MAX #define INT32_MAX 2147483647 #define INT32_MIN (-2147483647-1) #define UINT32_MAX 4294967295U #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST32_MAX INT32_MAX #define UINT_LEAST32_MAX UINT32_MAX #define INT_FAST32_MIN INT32_MIN #define INT_FAST32_MAX INT32_MAX #define UINT_FAST32_MAX UINT32_MAX /* If we do not have 64-bit support, don't define the 64-bit size macros. */ #ifdef __INT64_TYPE__ #define INT64_MAX 9223372036854775807LL #define INT64_MIN (-9223372036854775807LL-1) #define UINT64_MAX 18446744073709551615ULL #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST64_MAX UINT64_MAX #define INT_FAST64_MIN INT64_MIN #define INT_FAST64_MAX INT64_MAX #define UINT_FAST64_MAX UINT64_MAX #endif /* C99 7.18.2.4 Limits of integer types capable of holding object pointers. */ /* C99 7.18.3 Limits of other integer types. */ #if __POINTER_WIDTH__ == 64 #define INTPTR_MIN INT64_MIN #define INTPTR_MAX INT64_MAX #define UINTPTR_MAX UINT64_MAX #define PTRDIFF_MIN INT64_MIN #define PTRDIFF_MAX INT64_MAX #define SIZE_MAX UINT64_MAX #elif __POINTER_WIDTH__ == 32 #define INTPTR_MIN INT32_MIN #define INTPTR_MAX INT32_MAX #define UINTPTR_MAX UINT32_MAX #define PTRDIFF_MIN INT32_MIN #define PTRDIFF_MAX INT32_MAX #define SIZE_MAX UINT32_MAX #elif __POINTER_WIDTH__ == 16 #define INTPTR_MIN INT16_MIN #define INTPTR_MAX INT16_MAX #define UINTPTR_MAX UINT16_MAX #define PTRDIFF_MIN INT16_MIN #define PTRDIFF_MAX INT16_MAX #define SIZE_MAX UINT16_MAX #else #error "unknown or unset pointer width!" #endif /* C99 7.18.2.5 Limits of greatest-width integer types. */ #define INTMAX_MIN (-__INTMAX_MAX__-1) #define INTMAX_MAX __INTMAX_MAX__ #define UINTMAX_MAX (__INTMAX_MAX__*2ULL+1ULL) /* C99 7.18.3 Limits of other integer types. */ #define SIG_ATOMIC_MIN INT32_MIN #define SIG_ATOMIC_MAX INT32_MAX #define WINT_MIN INT32_MIN #define WINT_MAX INT32_MAX /* FIXME: if we ever support a target with unsigned wchar_t, this should be * 0 .. Max. */ #ifndef WCHAR_MAX #define WCHAR_MAX __WCHAR_MAX__ #endif #ifndef WCHAR_MIN #define WCHAR_MIN (-__WCHAR_MAX__-1) #endif /* C99 7.18.4 Macros for minimum-width integer constants. * * Note that C++ should not check __STDC_CONSTANT_MACROS here, contrary to the * claims of the C standard (see C++ 18.3.1p2, [cstdint.syn]). */ #define INT8_C(v) (v) #define UINT8_C(v) (v##U) #define INT16_C(v) (v) #define UINT16_C(v) (v##U) #define INT32_C(v) (v) #define UINT32_C(v) (v##U) /* Only define the 64-bit size macros if we have 64-bit support. */ #ifdef __INT64_TYPE__ #define INT64_C(v) (v##LL) #define UINT64_C(v) (v##ULL) #endif /* 7.18.4.2 Macros for greatest-width integer constants. */ #define INTMAX_C(v) (v##LL) #define UINTMAX_C(v) (v##ULL) #endif /* __STDINT_H */ <file_sep>/lib/Parse/ParseExprCXX.cpp //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Expression parsing implementation for C++. // //===----------------------------------------------------------------------===// #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Parse/DeclSpec.h" #include "AstGuard.h" using namespace clang; /// ParseOptionalCXXScopeSpecifier - Parse global scope or /// nested-name-specifier if present. Returns true if a nested-name-specifier /// was parsed from the token stream. Note that this routine will not parse /// ::new or ::delete, it will just leave them in the token stream. /// /// '::'[opt] nested-name-specifier /// '::' /// /// nested-name-specifier: /// type-name '::' /// namespace-name '::' /// nested-name-specifier identifier '::' /// nested-name-specifier 'template'[opt] simple-template-id '::' [TODO] /// bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS) { assert(getLang().CPlusPlus && "Call sites of this function should be guarded by checking for C++"); if (Tok.is(tok::annot_cxxscope)) { SS.setScopeRep(Tok.getAnnotationValue()); SS.setRange(Tok.getAnnotationRange()); ConsumeToken(); return true; } bool HasScopeSpecifier = false; if (Tok.is(tok::coloncolon)) { // ::new and ::delete aren't nested-name-specifiers. tok::TokenKind NextKind = NextToken().getKind(); if (NextKind == tok::kw_new || NextKind == tok::kw_delete) return false; // '::' - Global scope qualifier. SourceLocation CCLoc = ConsumeToken(); SS.setBeginLoc(CCLoc); SS.setScopeRep(Actions.ActOnCXXGlobalScopeSpecifier(CurScope, CCLoc)); SS.setEndLoc(CCLoc); HasScopeSpecifier = true; } while (true) { // nested-name-specifier: // type-name '::' // namespace-name '::' // nested-name-specifier identifier '::' if (Tok.is(tok::identifier) && NextToken().is(tok::coloncolon)) { // We have an identifier followed by a '::'. Lookup this name // as the name in a nested-name-specifier. IdentifierInfo *II = Tok.getIdentifierInfo(); SourceLocation IdLoc = ConsumeToken(); assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); SourceLocation CCLoc = ConsumeToken(); if (!HasScopeSpecifier) { SS.setBeginLoc(IdLoc); HasScopeSpecifier = true; } if (SS.isInvalid()) continue; SS.setScopeRep( Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, IdLoc, CCLoc, *II)); SS.setEndLoc(CCLoc); continue; } // nested-name-specifier: // type-name '::' // nested-name-specifier 'template'[opt] simple-template-id '::' if ((Tok.is(tok::identifier) && NextToken().is(tok::less)) || Tok.is(tok::kw_template)) { // Parse the optional 'template' keyword, then make sure we have // 'identifier <' after it. if (Tok.is(tok::kw_template)) { SourceLocation TemplateKWLoc = ConsumeToken(); if (Tok.isNot(tok::identifier)) { Diag(Tok.getLocation(), diag::err_id_after_template_in_nested_name_spec) << SourceRange(TemplateKWLoc); break; } if (NextToken().isNot(tok::less)) { Diag(NextToken().getLocation(), diag::err_less_after_template_name_in_nested_name_spec) << Tok.getIdentifierInfo()->getName() << SourceRange(TemplateKWLoc, Tok.getLocation()); break; } TemplateTy Template = Actions.ActOnDependentTemplateName(TemplateKWLoc, *Tok.getIdentifierInfo(), Tok.getLocation(), SS); AnnotateTemplateIdToken(Template, TNK_Dependent_template_name, &SS, TemplateKWLoc, false); continue; } TemplateTy Template; TemplateNameKind TNK = Actions.isTemplateName(*Tok.getIdentifierInfo(), CurScope, Template, &SS); if (TNK) { // We have found a template name, so annotate this this token // with a template-id annotation. We do not permit the // template-id to be translated into a type annotation, // because some clients (e.g., the parsing of class template // specializations) still want to see the original template-id // token. AnnotateTemplateIdToken(Template, TNK, &SS, SourceLocation(), false); continue; } } if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) { // We have // // simple-template-id '::' // // So we need to check whether the simple-template-id is of the // right kind (it should name a type or be dependent), and then // convert it into a type within the nested-name-specifier. TemplateIdAnnotation *TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); if (TemplateId->Kind == TNK_Type_template || TemplateId->Kind == TNK_Dependent_template_name) { AnnotateTemplateIdTokenAsType(&SS); SS.clear(); assert(Tok.is(tok::annot_typename) && "AnnotateTemplateIdTokenAsType isn't working"); Token TypeToken = Tok; ConsumeToken(); assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); SourceLocation CCLoc = ConsumeToken(); if (!HasScopeSpecifier) { SS.setBeginLoc(TypeToken.getLocation()); HasScopeSpecifier = true; } if (TypeToken.getAnnotationValue()) SS.setScopeRep( Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, TypeToken.getAnnotationValue(), TypeToken.getAnnotationRange(), CCLoc)); else SS.setScopeRep(0); SS.setEndLoc(CCLoc); continue; } else assert(false && "FIXME: Only type template names supported here"); } // We don't have any tokens that form the beginning of a // nested-name-specifier, so we're done. break; } return HasScopeSpecifier; } /// ParseCXXIdExpression - Handle id-expression. /// /// id-expression: /// unqualified-id /// qualified-id /// /// unqualified-id: /// identifier /// operator-function-id /// conversion-function-id [TODO] /// '~' class-name [TODO] /// template-id [TODO] /// /// qualified-id: /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id /// '::' identifier /// '::' operator-function-id /// '::' template-id [TODO] /// /// nested-name-specifier: /// type-name '::' /// namespace-name '::' /// nested-name-specifier identifier '::' /// nested-name-specifier 'template'[opt] simple-template-id '::' [TODO] /// /// NOTE: The standard specifies that, for qualified-id, the parser does not /// expect: /// /// '::' conversion-function-id /// '::' '~' class-name /// /// This may cause a slight inconsistency on diagnostics: /// /// class C {}; /// namespace A {} /// void f() { /// :: A :: ~ C(); // Some Sema error about using destructor with a /// // namespace. /// :: ~ C(); // Some Parser error like 'unexpected ~'. /// } /// /// We simplify the parser a bit and make it work like: /// /// qualified-id: /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id /// '::' unqualified-id /// /// That way Sema can handle and report similar errors for namespaces and the /// global scope. /// /// The isAddressOfOperand parameter indicates that this id-expression is a /// direct operand of the address-of operator. This is, besides member contexts, /// the only place where a qualified-id naming a non-static class member may /// appear. /// Parser::OwningExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { // qualified-id: // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id // '::' unqualified-id // CXXScopeSpec SS; ParseOptionalCXXScopeSpecifier(SS); // unqualified-id: // identifier // operator-function-id // conversion-function-id // '~' class-name [TODO] // template-id [TODO] // switch (Tok.getKind()) { default: return ExprError(Diag(Tok, diag::err_expected_unqualified_id)); case tok::identifier: { // Consume the identifier so that we can see if it is followed by a '('. IdentifierInfo &II = *Tok.getIdentifierInfo(); SourceLocation L = ConsumeToken(); return Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren), &SS, isAddressOfOperand); } case tok::kw_operator: { SourceLocation OperatorLoc = Tok.getLocation(); if (OverloadedOperatorKind Op = TryParseOperatorFunctionId()) return Actions.ActOnCXXOperatorFunctionIdExpr( CurScope, OperatorLoc, Op, Tok.is(tok::l_paren), SS, isAddressOfOperand); if (TypeTy *Type = ParseConversionFunctionId()) return Actions.ActOnCXXConversionFunctionExpr(CurScope, OperatorLoc, Type, Tok.is(tok::l_paren), SS, isAddressOfOperand); // We already complained about a bad conversion-function-id, // above. return ExprError(); } } // switch. assert(0 && "The switch was supposed to take care everything."); } /// ParseCXXCasts - This handles the various ways to cast expressions to another /// type. /// /// postfix-expression: [C++ 5.2p1] /// 'dynamic_cast' '<' type-name '>' '(' expression ')' /// 'static_cast' '<' type-name '>' '(' expression ')' /// 'reinterpret_cast' '<' type-name '>' '(' expression ')' /// 'const_cast' '<' type-name '>' '(' expression ')' /// Parser::OwningExprResult Parser::ParseCXXCasts() { tok::TokenKind Kind = Tok.getKind(); const char *CastName = 0; // For error messages switch (Kind) { default: assert(0 && "Unknown C++ cast!"); abort(); case tok::kw_const_cast: CastName = "const_cast"; break; case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; case tok::kw_static_cast: CastName = "static_cast"; break; } SourceLocation OpLoc = ConsumeToken(); SourceLocation LAngleBracketLoc = Tok.getLocation(); if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) return ExprError(); TypeResult CastTy = ParseTypeName(); SourceLocation RAngleBracketLoc = Tok.getLocation(); if (ExpectAndConsume(tok::greater, diag::err_expected_greater)) return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<"); SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; if (Tok.isNot(tok::l_paren)) return ExprError(Diag(Tok, diag::err_expected_lparen_after) << CastName); OwningExprResult Result(ParseSimpleParenExpression(RParenLoc)); if (!Result.isInvalid() && !CastTy.isInvalid()) Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, LAngleBracketLoc, CastTy.get(), RAngleBracketLoc, LParenLoc, move(Result), RParenLoc); return move(Result); } /// ParseCXXTypeid - This handles the C++ typeid expression. /// /// postfix-expression: [C++ 5.2p1] /// 'typeid' '(' expression ')' /// 'typeid' '(' type-id ')' /// Parser::OwningExprResult Parser::ParseCXXTypeid() { assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!"); SourceLocation OpLoc = ConsumeToken(); SourceLocation LParenLoc = Tok.getLocation(); SourceLocation RParenLoc; // typeid expressions are always parenthesized. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "typeid")) return ExprError(); OwningExprResult Result(Actions); if (isTypeIdInParens()) { TypeResult Ty = ParseTypeName(); // Match the ')'. MatchRHSPunctuation(tok::r_paren, LParenLoc); if (Ty.isInvalid()) return ExprError(); Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, Ty.get(), RParenLoc); } else { Result = ParseExpression(); // Match the ')'. if (Result.isInvalid()) SkipUntil(tok::r_paren); else { MatchRHSPunctuation(tok::r_paren, LParenLoc); Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, Result.release(), RParenLoc); } } return move(Result); } /// ParseCXXBoolLiteral - This handles the C++ Boolean literals. /// /// boolean-literal: [C++ 2.13.5] /// 'true' /// 'false' Parser::OwningExprResult Parser::ParseCXXBoolLiteral() { tok::TokenKind Kind = Tok.getKind(); return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); } /// ParseThrowExpression - This handles the C++ throw expression. /// /// throw-expression: [C++ 15] /// 'throw' assignment-expression[opt] Parser::OwningExprResult Parser::ParseThrowExpression() { assert(Tok.is(tok::kw_throw) && "Not throw!"); SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. // If the current token isn't the start of an assignment-expression, // then the expression is not present. This handles things like: // "C ? throw : (void)42", which is crazy but legal. switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. case tok::semi: case tok::r_paren: case tok::r_square: case tok::r_brace: case tok::colon: case tok::comma: return Actions.ActOnCXXThrow(ThrowLoc, ExprArg(Actions)); default: OwningExprResult Expr(ParseAssignmentExpression()); if (Expr.isInvalid()) return move(Expr); return Actions.ActOnCXXThrow(ThrowLoc, move(Expr)); } } /// ParseCXXThis - This handles the C++ 'this' pointer. /// /// C++ 9.3.2: In the body of a non-static member function, the keyword this is /// a non-lvalue expression whose value is the address of the object for which /// the function is called. Parser::OwningExprResult Parser::ParseCXXThis() { assert(Tok.is(tok::kw_this) && "Not 'this'!"); SourceLocation ThisLoc = ConsumeToken(); return Actions.ActOnCXXThis(ThisLoc); } /// ParseCXXTypeConstructExpression - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). /// /// postfix-expression: [C++ 5.2p1] /// simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] /// typename-specifier '(' expression-list[opt] ')' [TODO] /// Parser::OwningExprResult Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); TypeTy *TypeRep = Actions.ActOnTypeName(CurScope, DeclaratorInfo).get(); assert(Tok.is(tok::l_paren) && "Expected '('!"); SourceLocation LParenLoc = ConsumeParen(); ExprVector Exprs(Actions); CommaLocsTy CommaLocs; if (Tok.isNot(tok::r_paren)) { if (ParseExpressionList(Exprs, CommaLocs)) { SkipUntil(tok::r_paren); return ExprError(); } } // Match the ')'. SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& "Unexpected number of commas!"); return Actions.ActOnCXXTypeConstructExpr(DS.getSourceRange(), TypeRep, LParenLoc, move_arg(Exprs), &CommaLocs[0], RParenLoc); } /// ParseCXXCondition - if/switch/while/for condition expression. /// /// condition: /// expression /// type-specifier-seq declarator '=' assignment-expression /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] /// '=' assignment-expression /// Parser::OwningExprResult Parser::ParseCXXCondition() { if (!isCXXConditionDeclaration()) return ParseExpression(); // expression SourceLocation StartLoc = Tok.getLocation(); // type-specifier-seq DeclSpec DS; ParseSpecifierQualifierList(DS); // declarator Declarator DeclaratorInfo(DS, Declarator::ConditionContext); ParseDeclarator(DeclaratorInfo); // simple-asm-expr[opt] if (Tok.is(tok::kw_asm)) { SourceLocation Loc; OwningExprResult AsmLabel(ParseSimpleAsm(&Loc)); if (AsmLabel.isInvalid()) { SkipUntil(tok::semi); return ExprError(); } DeclaratorInfo.setAsmLabel(AsmLabel.release()); DeclaratorInfo.SetRangeEnd(Loc); } // If attributes are present, parse them. if (Tok.is(tok::kw___attribute)) { SourceLocation Loc; AttributeList *AttrList = ParseAttributes(&Loc); DeclaratorInfo.AddAttributes(AttrList, Loc); } // '=' assignment-expression if (Tok.isNot(tok::equal)) return ExprError(Diag(Tok, diag::err_expected_equal_after_declarator)); SourceLocation EqualLoc = ConsumeToken(); OwningExprResult AssignExpr(ParseAssignmentExpression()); if (AssignExpr.isInvalid()) return ExprError(); return Actions.ActOnCXXConditionDeclarationExpr(CurScope, StartLoc, DeclaratorInfo,EqualLoc, move(AssignExpr)); } /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. /// /// simple-type-specifier: /// '::'[opt] nested-name-specifier[opt] type-name /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] /// char /// wchar_t /// bool /// short /// int /// long /// signed /// unsigned /// float /// double /// void /// [GNU] typeof-specifier /// [C++0x] auto [TODO] /// /// type-name: /// class-name /// enum-name /// typedef-name /// void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { DS.SetRangeStart(Tok.getLocation()); const char *PrevSpec; SourceLocation Loc = Tok.getLocation(); switch (Tok.getKind()) { case tok::identifier: // foo::bar case tok::coloncolon: // ::foo::bar assert(0 && "Annotation token should already be formed!"); default: assert(0 && "Not a simple-type-specifier token!"); abort(); // type-name case tok::annot_typename: { DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, Tok.getAnnotationValue()); break; } // builtin types case tok::kw_short: DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec); break; case tok::kw_long: DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec); break; case tok::kw_signed: DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec); break; case tok::kw_unsigned: DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec); break; case tok::kw_void: DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec); break; case tok::kw_char: DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec); break; case tok::kw_int: DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec); break; case tok::kw_float: DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec); break; case tok::kw_double: DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec); break; case tok::kw_wchar_t: DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec); break; case tok::kw_bool: DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec); break; // GNU typeof support. case tok::kw_typeof: ParseTypeofSpecifier(DS); DS.Finish(Diags, PP); return; } if (Tok.is(tok::annot_typename)) DS.SetRangeEnd(Tok.getAnnotationEndLoc()); else DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); DS.Finish(Diags, PP); } /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ /// [dcl.name]), which is a non-empty sequence of type-specifiers, /// e.g., "const short int". Note that the DeclSpec is *not* finished /// by parsing the type-specifier-seq, because these sequences are /// typically followed by some form of declarator. Returns true and /// emits diagnostics if this is not a type-specifier-seq, false /// otherwise. /// /// type-specifier-seq: [C++ 8.1] /// type-specifier type-specifier-seq[opt] /// bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { DS.SetRangeStart(Tok.getLocation()); const char *PrevSpec = 0; int isInvalid = 0; // Parse one or more of the type specifiers. if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec)) { Diag(Tok, diag::err_operator_missing_type_specifier); return true; } while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec)) ; return false; } /// TryParseOperatorFunctionId - Attempts to parse a C++ overloaded /// operator name (C++ [over.oper]). If successful, returns the /// predefined identifier that corresponds to that overloaded /// operator. Otherwise, returns NULL and does not consume any tokens. /// /// operator-function-id: [C++ 13.5] /// 'operator' operator /// /// operator: one of /// new delete new[] delete[] /// + - * / % ^ & | ~ /// ! = < > += -= *= /= %= /// ^= &= |= << >> >>= <<= == != /// <= >= && || ++ -- , ->* -> /// () [] OverloadedOperatorKind Parser::TryParseOperatorFunctionId(SourceLocation *EndLoc) { assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); SourceLocation Loc; OverloadedOperatorKind Op = OO_None; switch (NextToken().getKind()) { case tok::kw_new: ConsumeToken(); // 'operator' Loc = ConsumeToken(); // 'new' if (Tok.is(tok::l_square)) { ConsumeBracket(); // '[' Loc = Tok.getLocation(); ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' Op = OO_Array_New; } else { Op = OO_New; } if (EndLoc) *EndLoc = Loc; return Op; case tok::kw_delete: ConsumeToken(); // 'operator' Loc = ConsumeToken(); // 'delete' if (Tok.is(tok::l_square)) { ConsumeBracket(); // '[' Loc = Tok.getLocation(); ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' Op = OO_Array_Delete; } else { Op = OO_Delete; } if (EndLoc) *EndLoc = Loc; return Op; #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ case tok::Token: Op = OO_##Name; break; #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) #include "clang/Basic/OperatorKinds.def" case tok::l_paren: ConsumeToken(); // 'operator' ConsumeParen(); // '(' Loc = Tok.getLocation(); ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); // ')' if (EndLoc) *EndLoc = Loc; return OO_Call; case tok::l_square: ConsumeToken(); // 'operator' ConsumeBracket(); // '[' Loc = Tok.getLocation(); ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); // ']' if (EndLoc) *EndLoc = Loc; return OO_Subscript; default: return OO_None; } ConsumeToken(); // 'operator' Loc = ConsumeAnyToken(); // the operator itself if (EndLoc) *EndLoc = Loc; return Op; } /// ParseConversionFunctionId - Parse a C++ conversion-function-id, /// which expresses the name of a user-defined conversion operator /// (C++ [class.conv.fct]p1). Returns the type that this operator is /// specifying a conversion for, or NULL if there was an error. /// /// conversion-function-id: [C++ 12.3.2] /// operator conversion-type-id /// /// conversion-type-id: /// type-specifier-seq conversion-declarator[opt] /// /// conversion-declarator: /// ptr-operator conversion-declarator[opt] Parser::TypeTy *Parser::ParseConversionFunctionId(SourceLocation *EndLoc) { assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); ConsumeToken(); // 'operator' // Parse the type-specifier-seq. DeclSpec DS; if (ParseCXXTypeSpecifierSeq(DS)) return 0; // Parse the conversion-declarator, which is merely a sequence of // ptr-operators. Declarator D(DS, Declarator::TypeNameContext); ParseDeclaratorInternal(D, /*DirectDeclParser=*/0); if (EndLoc) *EndLoc = D.getSourceRange().getEnd(); // Finish up the type. Action::TypeResult Result = Actions.ActOnTypeName(CurScope, D); if (Result.isInvalid()) return 0; else return Result.get(); } /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate /// memory in a typesafe manner and call constructors. /// /// This method is called to parse the new expression after the optional :: has /// been already parsed. If the :: was present, "UseGlobal" is true and "Start" /// is its location. Otherwise, "Start" is the location of the 'new' token. /// /// new-expression: /// '::'[opt] 'new' new-placement[opt] new-type-id /// new-initializer[opt] /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' /// new-initializer[opt] /// /// new-placement: /// '(' expression-list ')' /// /// new-type-id: /// type-specifier-seq new-declarator[opt] /// /// new-declarator: /// ptr-operator new-declarator[opt] /// direct-new-declarator /// /// new-initializer: /// '(' expression-list[opt] ')' /// [C++0x] braced-init-list [TODO] /// Parser::OwningExprResult Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { assert(Tok.is(tok::kw_new) && "expected 'new' token"); ConsumeToken(); // Consume 'new' // A '(' now can be a new-placement or the '(' wrapping the type-id in the // second form of new-expression. It can't be a new-type-id. ExprVector PlacementArgs(Actions); SourceLocation PlacementLParen, PlacementRParen; bool ParenTypeId; DeclSpec DS; Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); if (Tok.is(tok::l_paren)) { // If it turns out to be a placement, we change the type location. PlacementLParen = ConsumeParen(); if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) { SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); return ExprError(); } PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen); if (PlacementRParen.isInvalid()) { SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); return ExprError(); } if (PlacementArgs.empty()) { // Reset the placement locations. There was no placement. PlacementLParen = PlacementRParen = SourceLocation(); ParenTypeId = true; } else { // We still need the type. if (Tok.is(tok::l_paren)) { SourceLocation LParen = ConsumeParen(); ParseSpecifierQualifierList(DS); DeclaratorInfo.SetSourceRange(DS.getSourceRange()); ParseDeclarator(DeclaratorInfo); MatchRHSPunctuation(tok::r_paren, LParen); ParenTypeId = true; } else { if (ParseCXXTypeSpecifierSeq(DS)) DeclaratorInfo.setInvalidType(true); else { DeclaratorInfo.SetSourceRange(DS.getSourceRange()); ParseDeclaratorInternal(DeclaratorInfo, &Parser::ParseDirectNewDeclarator); } ParenTypeId = false; } } } else { // A new-type-id is a simplified type-id, where essentially the // direct-declarator is replaced by a direct-new-declarator. if (ParseCXXTypeSpecifierSeq(DS)) DeclaratorInfo.setInvalidType(true); else { DeclaratorInfo.SetSourceRange(DS.getSourceRange()); ParseDeclaratorInternal(DeclaratorInfo, &Parser::ParseDirectNewDeclarator); } ParenTypeId = false; } if (DeclaratorInfo.getInvalidType()) { SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); return ExprError(); } ExprVector ConstructorArgs(Actions); SourceLocation ConstructorLParen, ConstructorRParen; if (Tok.is(tok::l_paren)) { ConstructorLParen = ConsumeParen(); if (Tok.isNot(tok::r_paren)) { CommaLocsTy CommaLocs; if (ParseExpressionList(ConstructorArgs, CommaLocs)) { SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); return ExprError(); } } ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen); if (ConstructorRParen.isInvalid()) { SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true); return ExprError(); } } return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen, move_arg(PlacementArgs), PlacementRParen, ParenTypeId, DeclaratorInfo, ConstructorLParen, move_arg(ConstructorArgs), ConstructorRParen); } /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be /// passed to ParseDeclaratorInternal. /// /// direct-new-declarator: /// '[' expression ']' /// direct-new-declarator '[' constant-expression ']' /// void Parser::ParseDirectNewDeclarator(Declarator &D) { // Parse the array dimensions. bool first = true; while (Tok.is(tok::l_square)) { SourceLocation LLoc = ConsumeBracket(); OwningExprResult Size(first ? ParseExpression() : ParseConstantExpression()); if (Size.isInvalid()) { // Recover SkipUntil(tok::r_square); return; } first = false; SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc); D.AddTypeInfo(DeclaratorChunk::getArray(0, /*static=*/false, /*star=*/false, Size.release(), LLoc), RLoc); if (RLoc.isInvalid()) return; } } /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id. /// This ambiguity appears in the syntax of the C++ new operator. /// /// new-expression: /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' /// new-initializer[opt] /// /// new-placement: /// '(' expression-list ')' /// bool Parser::ParseExpressionListOrTypeId(ExprListTy &PlacementArgs, Declarator &D) { // The '(' was already consumed. if (isTypeIdInParens()) { ParseSpecifierQualifierList(D.getMutableDeclSpec()); D.SetSourceRange(D.getDeclSpec().getSourceRange()); ParseDeclarator(D); return D.getInvalidType(); } // It's not a type, it has to be an expression list. // Discard the comma locations - ActOnCXXNew has enough parameters. CommaLocsTy CommaLocs; return ParseExpressionList(PlacementArgs, CommaLocs); } /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used /// to free memory allocated by new. /// /// This method is called to parse the 'delete' expression after the optional /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true /// and "Start" is its location. Otherwise, "Start" is the location of the /// 'delete' token. /// /// delete-expression: /// '::'[opt] 'delete' cast-expression /// '::'[opt] 'delete' '[' ']' cast-expression Parser::OwningExprResult Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword"); ConsumeToken(); // Consume 'delete' // Array delete? bool ArrayDelete = false; if (Tok.is(tok::l_square)) { ArrayDelete = true; SourceLocation LHS = ConsumeBracket(); SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS); if (RHS.isInvalid()) return ExprError(); } OwningExprResult Operand(ParseCastExpression(false)); if (Operand.isInvalid()) return move(Operand); return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, move(Operand)); } static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) { switch(kind) { default: assert(false && "Not a known unary type trait."); case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign; case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy; case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor; case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign; case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy; case tok::kw___has_trivial_constructor: return UTT_HasTrivialConstructor; case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor; case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor; case tok::kw___is_abstract: return UTT_IsAbstract; case tok::kw___is_class: return UTT_IsClass; case tok::kw___is_empty: return UTT_IsEmpty; case tok::kw___is_enum: return UTT_IsEnum; case tok::kw___is_pod: return UTT_IsPOD; case tok::kw___is_polymorphic: return UTT_IsPolymorphic; case tok::kw___is_union: return UTT_IsUnion; } } /// ParseUnaryTypeTrait - Parse the built-in unary type-trait /// pseudo-functions that allow implementation of the TR1/C++0x type traits /// templates. /// /// primary-expression: /// [GNU] unary-type-trait '(' type-id ')' /// Parser::OwningExprResult Parser::ParseUnaryTypeTrait() { UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind()); SourceLocation Loc = ConsumeToken(); SourceLocation LParen = Tok.getLocation(); if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen)) return ExprError(); // FIXME: Error reporting absolutely sucks! If the this fails to parse a type // there will be cryptic errors about mismatched parentheses and missing // specifiers. TypeResult Ty = ParseTypeName(); SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); if (Ty.isInvalid()) return ExprError(); return Actions.ActOnUnaryTypeTrait(UTT, Loc, LParen, Ty.get(), RParen); } <file_sep>/test/Sema/scope-check.c // RUN: clang-cc -fsyntax-only -verify %s int test1(int x) { goto L; // expected-error{{illegal jump}} int a[x]; L: return sizeof a; } int test2(int x) { goto L; // expected-error{{illegal jump}} typedef int a[x]; L: return sizeof(a); } void test3clean(int*); int test3() { goto L; // expected-error{{illegal jump}} int a __attribute((cleanup(test3clean))); L: return a; } int test4(int x) { goto L; // expected-error{{illegal jump}} int a[x]; test4(x); L: return sizeof a; } <file_sep>/test/SemaTemplate/typename-specifier-2.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename MetaFun, typename T> struct bind_metafun { typedef typename MetaFun::template apply<T> type; }; struct add_pointer { template<typename T> struct apply { typedef T* type; }; }; int i; // FIXME: if we make the declarator below a pointer (e.g., with *ip), // the error message isn't so good because we don't get the handy // 'aka' telling us that we're dealing with an int**. Should we fix // getDesugaredType to dig through pointers and such? bind_metafun<add_pointer, int>::type::type ip = &i; bind_metafun<add_pointer, float>::type::type fp = &i; // expected-error{{incompatible type initializing 'int *', expected 'bind_metafun<struct add_pointer, float>::type::type' (aka 'float *')}} template<typename T> struct extract_type_type { typedef typename T::type::type t; }; double d; extract_type_type<bind_metafun<add_pointer, double> >::t dp = &d; <file_sep>/test/CodeGen/regparm.c // RUN: clang-cc -triple i386-unknown-unknown %s -emit-llvm -o - | grep inreg | count 2 #define FASTCALL __attribute__((regparm(2))) typedef struct { int aaa; double bbbb; int ccc[200]; } foo; static void FASTCALL reduced(char b, double c, foo* d, double e, int f) { } int main(void) { reduced(0, 0.0, 0, 0.0, 0); } <file_sep>/include/clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h //= CFGRecStmtDeclVisitor - Recursive visitor of CFG stmts/decls -*- C++ --*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the template class CFGRecStmtDeclVisitor, which extends // CFGRecStmtVisitor by implementing (typed) visitation of decls. // // FIXME: This may not be fully complete. We currently explore only subtypes // of ScopedDecl. //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_CFG_REC_STMT_DECL_VISITOR_H #define LLVM_CLANG_ANALYSIS_CFG_REC_STMT_DECL_VISITOR_H #include "clang/Analysis/Visitors/CFGRecStmtVisitor.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #define DISPATCH_CASE(CASE,CLASS) \ case Decl::CASE: \ static_cast<ImplClass*>(this)->Visit##CLASS(static_cast<CLASS*>(D));\ break; #define DEFAULT_DISPATCH(CLASS) void Visit##CLASS(CLASS* D) {} #define DEFAULT_DISPATCH_VARDECL(CLASS) void Visit##CLASS(CLASS* D)\ { static_cast<ImplClass*>(this)->VisitVarDecl(D); } namespace clang { template <typename ImplClass> class CFGRecStmtDeclVisitor : public CFGRecStmtVisitor<ImplClass> { public: void VisitDeclRefExpr(DeclRefExpr* DR) { static_cast<ImplClass*>(this)->VisitDecl(DR->getDecl()); } void VisitDeclStmt(DeclStmt* DS) { for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { Decl* D = *DI; static_cast<ImplClass*>(this)->VisitDecl(D); // Visit the initializer. if (VarDecl* VD = dyn_cast<VarDecl>(D)) if (Expr* I = VD->getInit()) static_cast<ImplClass*>(this)->Visit(I); } } void VisitDecl(Decl* D) { switch (D->getKind()) { DISPATCH_CASE(Function,FunctionDecl) DISPATCH_CASE(Var,VarDecl) DISPATCH_CASE(ParmVar,ParmVarDecl) // FIXME: (same) DISPATCH_CASE(OriginalParmVar,OriginalParmVarDecl) // FIXME: (same) DISPATCH_CASE(ImplicitParam,ImplicitParamDecl) DISPATCH_CASE(EnumConstant,EnumConstantDecl) DISPATCH_CASE(Typedef,TypedefDecl) DISPATCH_CASE(Record,RecordDecl) // FIXME: Refine. VisitStructDecl? DISPATCH_CASE(Enum,EnumDecl) default: assert(false && "Subtype of ScopedDecl not handled."); } } DEFAULT_DISPATCH(VarDecl) DEFAULT_DISPATCH(FunctionDecl) DEFAULT_DISPATCH_VARDECL(OriginalParmVarDecl) DEFAULT_DISPATCH_VARDECL(ParmVarDecl) DEFAULT_DISPATCH(ImplicitParamDecl) DEFAULT_DISPATCH(EnumConstantDecl) DEFAULT_DISPATCH(TypedefDecl) DEFAULT_DISPATCH(RecordDecl) DEFAULT_DISPATCH(EnumDecl) DEFAULT_DISPATCH(ObjCInterfaceDecl) DEFAULT_DISPATCH(ObjCClassDecl) DEFAULT_DISPATCH(ObjCMethodDecl) DEFAULT_DISPATCH(ObjCProtocolDecl) DEFAULT_DISPATCH(ObjCCategoryDecl) }; } // end namespace clang #undef DISPATCH_CASE #undef DEFAULT_DISPATCH #endif <file_sep>/lib/Driver/Tools.h //===--- Tools.h - Tool Implementations -------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef CLANG_LIB_DRIVER_TOOLS_H_ #define CLANG_LIB_DRIVER_TOOLS_H_ #include "clang/Driver/Tool.h" #include "clang/Driver/Types.h" #include "clang/Driver/Util.h" #include "llvm/Support/Compiler.h" namespace clang { namespace driver { namespace toolchains { class Darwin_X86; } namespace tools { class VISIBILITY_HIDDEN Clang : public Tool { void AddPreprocessingOptions(const ArgList &Args, ArgStringList &CmdArgs, const InputInfo &Output, const InputInfoList &Inputs) const; public: Clang(const ToolChain &TC) : Tool("clang", TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return true; } virtual bool hasIntegratedCPP() const { return true; } virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; }; /// gcc - Generic GCC tool implementations. namespace gcc { class VISIBILITY_HIDDEN Common : public Tool { public: Common(const char *Name, const ToolChain &TC) : Tool(Name, TC) {} virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; /// RenderExtraToolArgs - Render any arguments necessary to force /// the particular tool mode. virtual void RenderExtraToolArgs(ArgStringList &CmdArgs) const = 0; }; class VISIBILITY_HIDDEN Preprocess : public Common { public: Preprocess(const ToolChain &TC) : Common("gcc::Preprocess", TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return true; } virtual bool hasIntegratedCPP() const { return false; } virtual void RenderExtraToolArgs(ArgStringList &CmdArgs) const; }; class VISIBILITY_HIDDEN Precompile : public Common { public: Precompile(const ToolChain &TC) : Common("gcc::Precompile", TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return false; } virtual bool hasIntegratedCPP() const { return true; } virtual void RenderExtraToolArgs(ArgStringList &CmdArgs) const; }; class VISIBILITY_HIDDEN Compile : public Common { public: Compile(const ToolChain &TC) : Common("gcc::Compile", TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return true; } virtual bool hasIntegratedCPP() const { return true; } virtual void RenderExtraToolArgs(ArgStringList &CmdArgs) const; }; class VISIBILITY_HIDDEN Assemble : public Common { public: Assemble(const ToolChain &TC) : Common("gcc::Assemble", TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return false; } virtual bool hasIntegratedCPP() const { return false; } virtual void RenderExtraToolArgs(ArgStringList &CmdArgs) const; }; class VISIBILITY_HIDDEN Link : public Common { public: Link(const ToolChain &TC) : Common("gcc::Link", TC) {} virtual bool acceptsPipedInput() const { return false; } virtual bool canPipeOutput() const { return false; } virtual bool hasIntegratedCPP() const { return false; } virtual void RenderExtraToolArgs(ArgStringList &CmdArgs) const; }; } // end namespace gcc namespace darwin { class VISIBILITY_HIDDEN CC1 : public Tool { public: static const char *getBaseInputName(const ArgList &Args, const InputInfoList &Input); static const char *getBaseInputStem(const ArgList &Args, const InputInfoList &Input); static const char *getDependencyFileName(const ArgList &Args, const InputInfoList &Inputs); protected: const char *getCC1Name(types::ID Type) const; void AddCC1Args(const ArgList &Args, ArgStringList &CmdArgs) const; void AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, const InputInfoList &Inputs, const ArgStringList &OutputArgs) const; void AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, const InputInfoList &Inputs, const ArgStringList &OutputArgs) const; void AddCPPUniqueOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, const InputInfoList &Inputs) const; void AddCPPArgs(const ArgList &Args, ArgStringList &CmdArgs) const; public: CC1(const char *Name, const ToolChain &TC) : Tool(Name, TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return true; } virtual bool hasIntegratedCPP() const { return true; } }; class VISIBILITY_HIDDEN Preprocess : public CC1 { public: Preprocess(const ToolChain &TC) : CC1("darwin::Preprocess", TC) {} virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Compile : public CC1 { public: Compile(const ToolChain &TC) : CC1("darwin::Compile", TC) {} virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Assemble : public Tool { public: Assemble(const ToolChain &TC) : Tool("darwin::Assemble", TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return false; } virtual bool hasIntegratedCPP() const { return false; } virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Link : public Tool { void AddDarwinArch(const ArgList &Args, ArgStringList &CmdArgs) const; void AddDarwinSubArch(const ArgList &Args, ArgStringList &CmdArgs) const; void AddLinkArgs(const ArgList &Args, ArgStringList &CmdArgs) const; /// The default macosx-version-min. const char *MacosxVersionMin; const toolchains::Darwin_X86 &getDarwinToolChain() const; public: Link(const ToolChain &TC, const char *_MacosxVersionMin) : Tool("darwin::Link", TC), MacosxVersionMin(_MacosxVersionMin) { } virtual bool acceptsPipedInput() const { return false; } virtual bool canPipeOutput() const { return false; } virtual bool hasIntegratedCPP() const { return false; } virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Lipo : public Tool { public: Lipo(const ToolChain &TC) : Tool("darwin::Lipo", TC) {} virtual bool acceptsPipedInput() const { return false; } virtual bool canPipeOutput() const { return false; } virtual bool hasIntegratedCPP() const { return false; } virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; }; } /// freebsd -- Directly call GNU Binutils assembler and linker namespace freebsd { class VISIBILITY_HIDDEN Assemble : public Tool { public: Assemble(const ToolChain &TC) : Tool("freebsd::Assemble", TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return true; } virtual bool hasIntegratedCPP() const { return false; } virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; }; class VISIBILITY_HIDDEN Link : public Tool { public: Link(const ToolChain &TC) : Tool("freebsd::Link", TC) {} virtual bool acceptsPipedInput() const { return true; } virtual bool canPipeOutput() const { return true; } virtual bool hasIntegratedCPP() const { return false; } virtual void ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &TCArgs, const char *LinkingOutput) const; }; } } // end namespace toolchains } // end namespace driver } // end namespace clang #endif <file_sep>/test/Preprocessor/include-directive2.c // RUN: clang-cc -Eonly %s # define HEADER <float.h> # include HEADER <file_sep>/include/clang/Frontend/PCHWriter.h //===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PCHWriter class, which writes a precompiled // header containing a serialized representation of a translation // unit. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_PCH_WRITER_H #define LLVM_CLANG_FRONTEND_PCH_WRITER_H #include "clang/AST/Decl.h" #include "clang/AST/DeclarationName.h" #include "clang/Frontend/PCHBitCodes.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include <queue> namespace llvm { class APFloat; class APInt; class BitstreamWriter; } namespace clang { class ASTContext; class Preprocessor; class SourceManager; class TargetInfo; /// \brief Writes a precompiled header containing the contents of a /// translation unit. /// /// The PCHWriter class produces a bitstream containing the serialized /// representation of a given abstract syntax tree and its supporting /// data structures. This bitstream can be de-serialized via an /// instance of the PCHReader class. class PCHWriter { public: typedef llvm::SmallVector<uint64_t, 64> RecordData; private: /// \brief The bitstream writer used to emit this precompiled header. llvm::BitstreamWriter &S; /// \brief Map that provides the ID numbers of each declaration within /// the output stream. /// /// The ID numbers of declarations are consecutive (in order of /// discovery) and start at 2. 1 is reserved for the translation /// unit, while 0 is reserved for NULL. llvm::DenseMap<const Decl *, pch::DeclID> DeclIDs; /// \brief Offset of each declaration in the bitstream, indexed by /// the declaration's ID. llvm::SmallVector<uint64_t, 16> DeclOffsets; /// \brief Queue containing the declarations that we still need to /// emit. std::queue<Decl *> DeclsToEmit; /// \brief Map that provides the ID numbers of each type within the /// output stream. /// /// The ID numbers of types are consecutive (in order of discovery) /// and start at 1. 0 is reserved for NULL. When types are actually /// stored in the stream, the ID number is shifted by 3 bits to /// allow for the const/volatile/restrict qualifiers. llvm::DenseMap<const Type *, pch::TypeID> TypeIDs; /// \brief Offset of each type in the bitstream, indexed by /// the type's ID. llvm::SmallVector<uint64_t, 16> TypeOffsets; /// \brief The type ID that will be assigned to the next new type. pch::TypeID NextTypeID; /// \brief Map that provides the ID numbers of each identifier in /// the output stream. /// /// The ID numbers for identifiers are consecutive (in order of /// discovery), starting at 1. An ID of zero refers to a NULL /// IdentifierInfo. llvm::DenseMap<const IdentifierInfo *, pch::IdentID> IdentifierIDs; /// \brief Declarations encountered that might be external /// definitions. /// /// We keep track of external definitions (as well as tentative /// definitions) as we are emitting declarations to the PCH /// file. The PCH file contains a separate record for these external /// definitions, which are provided to the AST consumer by the PCH /// reader. This is behavior is required to properly cope with, /// e.g., tentative variable definitions that occur within /// headers. The declarations themselves are stored as declaration /// IDs, since they will be written out to an EXTERNAL_DEFINITIONS /// record. llvm::SmallVector<uint64_t, 16> ExternalDefinitions; /// \brief Expressions that we've encountered while serializing a /// declaration or type. llvm::SmallVector<Expr *, 8> ExprsToEmit; void WriteTargetTriple(const TargetInfo &Target); void WriteLanguageOptions(const LangOptions &LangOpts); void WriteSourceManagerBlock(SourceManager &SourceMgr); void WritePreprocessor(const Preprocessor &PP); void WriteType(const Type *T); void WriteTypesBlock(ASTContext &Context); uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC); uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC); void WriteDeclsBlock(ASTContext &Context); void WriteIdentifierTable(); void WriteAttributeRecord(const Attr *Attr); void AddString(const std::string &Str, RecordData &Record); public: /// \brief Create a new precompiled header writer that outputs to /// the given bitstream. PCHWriter(llvm::BitstreamWriter &S); /// \brief Write a precompiled header for the given AST context. void WritePCH(ASTContext &Context, const Preprocessor &PP); /// \brief Emit a source location. void AddSourceLocation(SourceLocation Loc, RecordData &Record); /// \brief Emit an integral value. void AddAPInt(const llvm::APInt &Value, RecordData &Record); /// \brief Emit a signed integral value. void AddAPSInt(const llvm::APSInt &Value, RecordData &Record); /// \brief Emit a floating-point value. void AddAPFloat(const llvm::APFloat &Value, RecordData &Record); /// \brief Emit a reference to an identifier void AddIdentifierRef(const IdentifierInfo *II, RecordData &Record); /// \brief Emit a reference to a type. void AddTypeRef(QualType T, RecordData &Record); /// \brief Emit a reference to a declaration. void AddDeclRef(const Decl *D, RecordData &Record); /// \brief Emit a declaration name. void AddDeclarationName(DeclarationName Name, RecordData &Record); /// \brief Add the given expression to the queue of expressions to /// emit. /// /// This routine should be used when emitting types and declarations /// that have expressions as part of their formulation. Once the /// type or declaration has been written, call FlushExprs() to write /// the corresponding expressions just after the type or /// declaration. void AddExpr(Expr *E) { ExprsToEmit.push_back(E); } /// \brief Write the given subexpression to the bitstream. void WriteSubExpr(Expr *E); /// \brief Flush all of the expressions that have been added to the /// queue via AddExpr(). void FlushExprs(); }; } // end namespace clang #endif <file_sep>/test/SemaCXX/type-convert-construct.cpp // RUN: clang-cc -fsyntax-only -verify %s void f() { float v1 = float(1); int v2 = typeof(int)(1,2); // expected-error {{function-style cast to a builtin type can only take one argument}} typedef int arr[]; int v3 = arr(); // expected-error {{array types cannot be value-initialized}} int v4 = int(); int v5 = int; // expected-error {{expected '(' for function-style cast or type construction}} typedef int T; int *p; bool v6 = T(0) == p; char *str; str = "a string"; wchar_t *wstr; wstr = L"a wide string"; } <file_sep>/test/CodeGen/PR3869-indirect-goto-long.c // RUN: clang-cc -emit-llvm-bc -o - %s // PR3869 int a(long long b) { goto *b; } <file_sep>/lib/AST/StmtSerialization.cpp //===--- StmtSerialization.cpp - Serialization of Statements --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the type-specific methods for serializing statements // and expressions. // //===----------------------------------------------------------------------===// #include "clang/Basic/TypeTraits.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ASTContext.h" #include "llvm/Bitcode/Serialize.h" #include "llvm/Bitcode/Deserialize.h" using namespace clang; using llvm::Serializer; using llvm::Deserializer; void Stmt::Emit(Serializer& S) const { S.FlushRecord(); S.EmitInt(getStmtClass()); EmitImpl(S); S.FlushRecord(); } Stmt* Stmt::Create(Deserializer& D, ASTContext& C) { StmtClass SC = static_cast<StmtClass>(D.ReadInt()); switch (SC) { default: assert (false && "Not implemented."); return NULL; case AddrLabelExprClass: return AddrLabelExpr::CreateImpl(D, C); case ArraySubscriptExprClass: return ArraySubscriptExpr::CreateImpl(D, C); case AsmStmtClass: return AsmStmt::CreateImpl(D, C); case BinaryOperatorClass: return BinaryOperator::CreateImpl(D, C); case BreakStmtClass: return BreakStmt::CreateImpl(D, C); case CallExprClass: return CallExpr::CreateImpl(D, C, CallExprClass); case CaseStmtClass: return CaseStmt::CreateImpl(D, C); case CharacterLiteralClass: return CharacterLiteral::CreateImpl(D, C); case ChooseExprClass: return ChooseExpr::CreateImpl(D, C); case CompoundAssignOperatorClass: return CompoundAssignOperator::CreateImpl(D, C); case CompoundLiteralExprClass: return CompoundLiteralExpr::CreateImpl(D, C); case CompoundStmtClass: return CompoundStmt::CreateImpl(D, C); case ConditionalOperatorClass: return ConditionalOperator::CreateImpl(D, C); case ContinueStmtClass: return ContinueStmt::CreateImpl(D, C); case DeclRefExprClass: return DeclRefExpr::CreateImpl(D, C); case DeclStmtClass: return DeclStmt::CreateImpl(D, C); case DefaultStmtClass: return DefaultStmt::CreateImpl(D, C); case DoStmtClass: return DoStmt::CreateImpl(D, C); case FloatingLiteralClass: return FloatingLiteral::CreateImpl(D, C); case ForStmtClass: return ForStmt::CreateImpl(D, C); case GNUNullExprClass: return GNUNullExpr::CreateImpl(D, C); case GotoStmtClass: return GotoStmt::CreateImpl(D, C); case IfStmtClass: return IfStmt::CreateImpl(D, C); case ImaginaryLiteralClass: return ImaginaryLiteral::CreateImpl(D, C); case ImplicitCastExprClass: return ImplicitCastExpr::CreateImpl(D, C); case CStyleCastExprClass: return CStyleCastExpr::CreateImpl(D, C); case IndirectGotoStmtClass: return IndirectGotoStmt::CreateImpl(D, C); case InitListExprClass: return InitListExpr::CreateImpl(D, C); case IntegerLiteralClass: return IntegerLiteral::CreateImpl(D, C); case LabelStmtClass: return LabelStmt::CreateImpl(D, C); case MemberExprClass: return MemberExpr::CreateImpl(D, C); case NullStmtClass: return NullStmt::CreateImpl(D, C); case ParenExprClass: return ParenExpr::CreateImpl(D, C); case PredefinedExprClass: return PredefinedExpr::CreateImpl(D, C); case ReturnStmtClass: return ReturnStmt::CreateImpl(D, C); case SizeOfAlignOfExprClass: return SizeOfAlignOfExpr::CreateImpl(D, C); case StmtExprClass: return StmtExpr::CreateImpl(D, C); case StringLiteralClass: return StringLiteral::CreateImpl(D, C); case SwitchStmtClass: return SwitchStmt::CreateImpl(D, C); case UnaryOperatorClass: return UnaryOperator::CreateImpl(D, C); case WhileStmtClass: return WhileStmt::CreateImpl(D, C); //==--------------------------------------==// // Objective C //==--------------------------------------==// case ObjCAtCatchStmtClass: return ObjCAtCatchStmt::CreateImpl(D, C); case ObjCAtFinallyStmtClass: return ObjCAtFinallyStmt::CreateImpl(D, C); case ObjCAtSynchronizedStmtClass: return ObjCAtSynchronizedStmt::CreateImpl(D, C); case ObjCAtThrowStmtClass: return ObjCAtThrowStmt::CreateImpl(D, C); case ObjCAtTryStmtClass: return ObjCAtTryStmt::CreateImpl(D, C); case ObjCEncodeExprClass: return ObjCEncodeExpr::CreateImpl(D, C); case ObjCForCollectionStmtClass: return ObjCForCollectionStmt::CreateImpl(D, C); case ObjCIvarRefExprClass: return ObjCIvarRefExpr::CreateImpl(D, C); case ObjCMessageExprClass: return ObjCMessageExpr::CreateImpl(D, C); case ObjCSelectorExprClass: return ObjCSelectorExpr::CreateImpl(D, C); case ObjCStringLiteralClass: return ObjCStringLiteral::CreateImpl(D, C); case ObjCSuperExprClass: return ObjCSuperExpr::CreateImpl(D, C); //==--------------------------------------==// // C++ //==--------------------------------------==// case CXXOperatorCallExprClass: return CXXOperatorCallExpr::CreateImpl(D, C, CXXOperatorCallExprClass); case CXXDefaultArgExprClass: return CXXDefaultArgExpr::CreateImpl(D, C); case CXXFunctionalCastExprClass: return CXXFunctionalCastExpr::CreateImpl(D, C); case CXXStaticCastExprClass: return CXXStaticCastExpr::CreateImpl(D, C, SC); case CXXDynamicCastExprClass: return CXXDynamicCastExpr::CreateImpl(D, C, SC); case CXXReinterpretCastExprClass: return CXXReinterpretCastExpr::CreateImpl(D, C, SC); case CXXConstCastExprClass: return CXXConstCastExpr::CreateImpl(D, C, SC); case CXXTypeidExprClass: return CXXTypeidExpr::CreateImpl(D, C); case CXXThisExprClass: return CXXThisExpr::CreateImpl(D, C); case CXXTemporaryObjectExprClass: return CXXTemporaryObjectExpr::CreateImpl(D, C); case CXXZeroInitValueExprClass: return CXXZeroInitValueExpr::CreateImpl(D, C); case CXXNewExprClass: return CXXNewExpr::CreateImpl(D, C); case CXXDeleteExprClass: return CXXDeleteExpr::CreateImpl(D, C); case UnresolvedFunctionNameExprClass: return UnresolvedFunctionNameExpr::CreateImpl(D, C); case CXXCatchStmtClass: return CXXCatchStmt::CreateImpl(D, C); case CXXTryStmtClass: return CXXTryStmt::CreateImpl(D, C); case QualifiedDeclRefExprClass: return QualifiedDeclRefExpr::CreateImpl(D, C); } } //===----------------------------------------------------------------------===// // C Serialization //===----------------------------------------------------------------------===// void AddrLabelExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(AmpAmpLoc); S.Emit(LabelLoc); S.EmitPtr(Label); } AddrLabelExpr* AddrLabelExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); SourceLocation AALoc = SourceLocation::ReadVal(D); SourceLocation LLoc = SourceLocation::ReadVal(D); AddrLabelExpr* expr = new (C, llvm::alignof<AddrLabelExpr>()) AddrLabelExpr(AALoc,LLoc,NULL,t); D.ReadPtr(expr->Label); // Pointer may be backpatched. return expr; } void ArraySubscriptExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(RBracketLoc); S.BatchEmitOwnedPtrs(getLHS(),getRHS()); } ArraySubscriptExpr* ArraySubscriptExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); SourceLocation L = SourceLocation::ReadVal(D); Expr *LHS, *RHS; D.BatchReadOwnedPtrs(LHS, RHS, C); return new (C, llvm::alignof<ArraySubscriptExpr>()) ArraySubscriptExpr(LHS,RHS,t,L); } void AsmStmt::EmitImpl(Serializer& S) const { S.Emit(AsmLoc); getAsmString()->EmitImpl(S); S.Emit(RParenLoc); S.EmitBool(IsVolatile); S.EmitBool(IsSimple); S.EmitInt(NumOutputs); S.EmitInt(NumInputs); unsigned size = NumOutputs + NumInputs; for (unsigned i = 0; i < size; ++i) S.EmitCStr(Names[i].c_str()); for (unsigned i = 0; i < size; ++i) Constraints[i]->EmitImpl(S); for (unsigned i = 0; i < size; ++i) S.EmitOwnedPtr(Exprs[i]); S.EmitInt(Clobbers.size()); for (unsigned i = 0, e = Clobbers.size(); i != e; ++i) Clobbers[i]->EmitImpl(S); } AsmStmt* AsmStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation ALoc = SourceLocation::ReadVal(D); StringLiteral *AsmStr = StringLiteral::CreateImpl(D, C); SourceLocation PLoc = SourceLocation::ReadVal(D); bool IsVolatile = D.ReadBool(); bool IsSimple = D.ReadBool(); AsmStmt *Stmt = new (C, llvm::alignof<AsmStmt>()) AsmStmt(ALoc, IsSimple, IsVolatile, 0, 0, 0, 0, 0, AsmStr, 0, 0, PLoc); Stmt->NumOutputs = D.ReadInt(); Stmt->NumInputs = D.ReadInt(); unsigned size = Stmt->NumOutputs + Stmt->NumInputs; Stmt->Names.reserve(size); for (unsigned i = 0; i < size; ++i) { std::vector<char> data; D.ReadCStr(data, false); Stmt->Names.push_back(std::string(data.begin(), data.end())); } Stmt->Constraints.reserve(size); for (unsigned i = 0; i < size; ++i) Stmt->Constraints.push_back(StringLiteral::CreateImpl(D, C)); Stmt->Exprs.reserve(size); for (unsigned i = 0; i < size; ++i) Stmt->Exprs.push_back(D.ReadOwnedPtr<Expr>(C)); unsigned NumClobbers = D.ReadInt(); Stmt->Clobbers.reserve(NumClobbers); for (unsigned i = 0; i < NumClobbers; ++i) Stmt->Clobbers.push_back(StringLiteral::CreateImpl(D, C)); return Stmt; } void BinaryOperator::EmitImpl(Serializer& S) const { S.EmitInt(Opc); S.Emit(OpLoc);; S.Emit(getType()); S.BatchEmitOwnedPtrs(getLHS(),getRHS()); } BinaryOperator* BinaryOperator::CreateImpl(Deserializer& D, ASTContext& C) { Opcode Opc = static_cast<Opcode>(D.ReadInt()); SourceLocation OpLoc = SourceLocation::ReadVal(D); QualType Result = QualType::ReadVal(D); Expr *LHS, *RHS; D.BatchReadOwnedPtrs(LHS, RHS, C); return new (C, llvm::alignof<BinaryOperator>()) BinaryOperator(LHS,RHS,Opc,Result,OpLoc); } void BreakStmt::EmitImpl(Serializer& S) const { S.Emit(BreakLoc); } BreakStmt* BreakStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); return new (C, llvm::alignof<BreakStmt>()) BreakStmt(Loc); } void CallExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(RParenLoc); S.EmitInt(NumArgs); S.BatchEmitOwnedPtrs(NumArgs+1, SubExprs); } CallExpr* CallExpr::CreateImpl(Deserializer& D, ASTContext& C, StmtClass SC) { QualType t = QualType::ReadVal(D); SourceLocation L = SourceLocation::ReadVal(D); unsigned NumArgs = D.ReadInt(); Stmt** SubExprs = new (C, llvm::alignof<Stmt*>()) Stmt*[NumArgs+1]; D.BatchReadOwnedPtrs(NumArgs+1, SubExprs, C); return new (C, llvm::alignof<CallExpr>()) CallExpr(SC, SubExprs,NumArgs,t,L); } void CaseStmt::EmitImpl(Serializer& S) const { S.Emit(CaseLoc); S.EmitPtr(getNextSwitchCase()); S.BatchEmitOwnedPtrs((unsigned) END_EXPR,&SubExprs[0]); } CaseStmt* CaseStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation CaseLoc = SourceLocation::ReadVal(D); CaseStmt* stmt = new (C, llvm::alignof<CaseStmt>()) CaseStmt(NULL,NULL,CaseLoc); D.ReadPtr(stmt->NextSwitchCase); D.BatchReadOwnedPtrs((unsigned) END_EXPR, &stmt->SubExprs[0], C); return stmt; } void CStyleCastExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(getTypeAsWritten()); S.Emit(LPLoc); S.Emit(RPLoc); S.EmitOwnedPtr(getSubExpr()); } CStyleCastExpr* CStyleCastExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); QualType writtenTy = QualType::ReadVal(D); SourceLocation LPLoc = SourceLocation::ReadVal(D); SourceLocation RPLoc = SourceLocation::ReadVal(D); Expr* Op = D.ReadOwnedPtr<Expr>(C); return new (C, llvm::alignof<CStyleCastExpr>()) CStyleCastExpr(t,Op,writtenTy,LPLoc,RPLoc); } void CharacterLiteral::EmitImpl(Serializer& S) const { S.Emit(Value); S.Emit(Loc); S.EmitBool(IsWide); S.Emit(getType()); } CharacterLiteral* CharacterLiteral::CreateImpl(Deserializer& D, ASTContext& C) { unsigned value = D.ReadInt(); SourceLocation Loc = SourceLocation::ReadVal(D); bool iswide = D.ReadBool(); QualType T = QualType::ReadVal(D); return new (C, llvm::alignof<CharacterLiteral>()) CharacterLiteral(value,iswide,T,Loc); } void CompoundAssignOperator::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(ComputationLHSType); S.Emit(ComputationResultType); S.Emit(getOperatorLoc()); S.EmitInt(getOpcode()); S.BatchEmitOwnedPtrs(getLHS(),getRHS()); } CompoundAssignOperator* CompoundAssignOperator::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); QualType cl = QualType::ReadVal(D); QualType cr = QualType::ReadVal(D); SourceLocation L = SourceLocation::ReadVal(D); Opcode Opc = static_cast<Opcode>(D.ReadInt()); Expr* LHS, *RHS; D.BatchReadOwnedPtrs(LHS, RHS, C); return new (C, llvm::alignof<CompoundAssignOperator>()) CompoundAssignOperator(LHS,RHS,Opc,t,cl,cr,L); } void CompoundLiteralExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(getLParenLoc()); S.EmitBool(isFileScope()); S.EmitOwnedPtr(Init); } CompoundLiteralExpr* CompoundLiteralExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType Q = QualType::ReadVal(D); SourceLocation L = SourceLocation::ReadVal(D); bool fileScope = D.ReadBool(); Expr* Init = D.ReadOwnedPtr<Expr>(C); return new (C, llvm::alignof<CompoundLiteralExpr>()) CompoundLiteralExpr(L, Q, Init, fileScope); } void CompoundStmt::EmitImpl(Serializer& S) const { S.Emit(LBracLoc); S.Emit(RBracLoc); S.Emit(NumStmts); if (NumStmts) S.BatchEmitOwnedPtrs(NumStmts, &Body[0]); } CompoundStmt* CompoundStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation LB = SourceLocation::ReadVal(D); SourceLocation RB = SourceLocation::ReadVal(D); unsigned size = D.ReadInt(); CompoundStmt* stmt = new (C, llvm::alignof<CompoundStmt>()) CompoundStmt(C, NULL, 0, LB, RB); stmt->NumStmts = size; if (size) { stmt->Body = new (C) Stmt*[size]; D.BatchReadOwnedPtrs(size, &stmt->Body[0], C); } return stmt; } void ConditionalOperator::EmitImpl(Serializer& S) const { S.Emit(getType()); S.BatchEmitOwnedPtrs((unsigned) END_EXPR, SubExprs); } ConditionalOperator* ConditionalOperator::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); ConditionalOperator* c = new (C, llvm::alignof<ConditionalOperator>()) ConditionalOperator(NULL,NULL,NULL,t); D.BatchReadOwnedPtrs((unsigned) END_EXPR, c->SubExprs, C); return c; } void ContinueStmt::EmitImpl(Serializer& S) const { S.Emit(ContinueLoc); } ContinueStmt* ContinueStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); return new ContinueStmt(Loc); } void DeclStmt::EmitImpl(Serializer& S) const { S.Emit(StartLoc); S.Emit(EndLoc); S.Emit(DG); } DeclStmt* DeclStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation StartLoc = SourceLocation::ReadVal(D); SourceLocation EndLoc = SourceLocation::ReadVal(D); return new DeclStmt(DeclGroupRef::ReadVal(D), StartLoc, EndLoc); } void DeclRefExpr::EmitImpl(Serializer& S) const { S.Emit(Loc); S.Emit(getType()); S.EmitPtr(getDecl()); } DeclRefExpr* DeclRefExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); QualType T = QualType::ReadVal(D); DeclRefExpr *DRE = new DeclRefExpr(0, T, Loc); D.ReadPtr(DRE->D); return DRE; } void DefaultStmt::EmitImpl(Serializer& S) const { S.Emit(DefaultLoc); S.EmitOwnedPtr(getSubStmt()); S.EmitPtr(getNextSwitchCase()); } DefaultStmt* DefaultStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); Stmt* SubStmt = D.ReadOwnedPtr<Stmt>(C); DefaultStmt* stmt = new DefaultStmt(Loc,SubStmt); stmt->setNextSwitchCase(D.ReadPtr<SwitchCase>()); return stmt; } void DoStmt::EmitImpl(Serializer& S) const { S.Emit(DoLoc); S.EmitOwnedPtr(getCond()); S.EmitOwnedPtr(getBody()); } DoStmt* DoStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation DoLoc = SourceLocation::ReadVal(D); Expr* Cond = D.ReadOwnedPtr<Expr>(C); Stmt* Body = D.ReadOwnedPtr<Stmt>(C); return new DoStmt(Body,Cond,DoLoc); } void FloatingLiteral::EmitImpl(Serializer& S) const { S.Emit(Loc); S.Emit(getType()); S.EmitBool(isExact()); S.Emit(Value); } FloatingLiteral* FloatingLiteral::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); QualType t = QualType::ReadVal(D); bool isExact = D.ReadBool(); llvm::APFloat Val = llvm::APFloat::ReadVal(D); FloatingLiteral* expr = new FloatingLiteral(Val,&isExact,t,Loc); return expr; } void ForStmt::EmitImpl(Serializer& S) const { S.Emit(ForLoc); S.EmitOwnedPtr(getInit()); S.EmitOwnedPtr(getCond()); S.EmitOwnedPtr(getInc()); S.EmitOwnedPtr(getBody()); } ForStmt* ForStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation ForLoc = SourceLocation::ReadVal(D); Stmt* Init = D.ReadOwnedPtr<Stmt>(C); Expr* Cond = D.ReadOwnedPtr<Expr>(C); Expr* Inc = D.ReadOwnedPtr<Expr>(C); Stmt* Body = D.ReadOwnedPtr<Stmt>(C); return new ForStmt(Init,Cond,Inc,Body,ForLoc); } void GotoStmt::EmitImpl(Serializer& S) const { S.Emit(GotoLoc); S.Emit(LabelLoc); S.EmitPtr(Label); } GotoStmt* GotoStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation GotoLoc = SourceLocation::ReadVal(D); SourceLocation LabelLoc = SourceLocation::ReadVal(D); GotoStmt* stmt = new GotoStmt(NULL,GotoLoc,LabelLoc); D.ReadPtr(stmt->Label); // This pointer may be backpatched later. return stmt; } void IfStmt::EmitImpl(Serializer& S) const { S.Emit(IfLoc); S.EmitOwnedPtr(getCond()); S.EmitOwnedPtr(getThen()); S.EmitOwnedPtr(getElse()); } IfStmt* IfStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation L = SourceLocation::ReadVal(D); Expr* Cond = D.ReadOwnedPtr<Expr>(C); Stmt* Then = D.ReadOwnedPtr<Stmt>(C); Stmt* Else = D.ReadOwnedPtr<Stmt>(C); return new IfStmt(L,Cond,Then,Else); } void ImaginaryLiteral::EmitImpl(Serializer& S) const { S.Emit(getType()); S.EmitOwnedPtr(Val); } ImaginaryLiteral* ImaginaryLiteral::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); Expr* expr = D.ReadOwnedPtr<Expr>(C); assert (isa<FloatingLiteral>(expr) || isa<IntegerLiteral>(expr)); return new ImaginaryLiteral(expr,t); } void ImplicitCastExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.EmitOwnedPtr(getSubExpr()); S.Emit(LvalueCast); } ImplicitCastExpr* ImplicitCastExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); Expr* Op = D.ReadOwnedPtr<Expr>(C); bool isLvalue = D.ReadBool(); return new ImplicitCastExpr(t,Op,isLvalue); } void IndirectGotoStmt::EmitImpl(Serializer& S) const { S.EmitOwnedPtr(Target); } IndirectGotoStmt* IndirectGotoStmt::CreateImpl(Deserializer& D, ASTContext& C) { Expr* Target = D.ReadOwnedPtr<Expr>(C); return new IndirectGotoStmt(Target); } void InitListExpr::EmitImpl(Serializer& S) const { S.Emit(LBraceLoc); S.Emit(RBraceLoc); S.EmitInt(InitExprs.size()); if (!InitExprs.empty()) S.BatchEmitOwnedPtrs(InitExprs.size(), &InitExprs[0]); } InitListExpr* InitListExpr::CreateImpl(Deserializer& D, ASTContext& C) { InitListExpr* expr = new InitListExpr(); expr->LBraceLoc = SourceLocation::ReadVal(D); expr->RBraceLoc = SourceLocation::ReadVal(D); unsigned size = D.ReadInt(); assert(size); expr->InitExprs.reserve(size); for (unsigned i = 0 ; i < size; ++i) expr->InitExprs.push_back(0); D.BatchReadOwnedPtrs(size, &expr->InitExprs[0], C); return expr; } void IntegerLiteral::EmitImpl(Serializer& S) const { S.Emit(Loc); S.Emit(getType()); S.Emit(getValue()); } IntegerLiteral* IntegerLiteral::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); QualType T = QualType::ReadVal(D); // Create a dummy APInt because it is more efficient to deserialize // it in place with the deserialized IntegerLiteral. (fewer copies) llvm::APInt temp; IntegerLiteral* expr = new IntegerLiteral(temp,T,Loc); D.Read(expr->Value); return expr; } void LabelStmt::EmitImpl(Serializer& S) const { S.EmitPtr(Label); S.Emit(IdentLoc); S.EmitOwnedPtr(SubStmt); } LabelStmt* LabelStmt::CreateImpl(Deserializer& D, ASTContext& C) { IdentifierInfo* Label = D.ReadPtr<IdentifierInfo>(); SourceLocation IdentLoc = SourceLocation::ReadVal(D); Stmt* SubStmt = D.ReadOwnedPtr<Stmt>(C); return new LabelStmt(IdentLoc,Label,SubStmt); } void MemberExpr::EmitImpl(Serializer& S) const { S.Emit(MemberLoc); S.EmitPtr(MemberDecl); S.EmitBool(IsArrow); S.Emit(getType()); S.EmitOwnedPtr(Base); } MemberExpr* MemberExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation L = SourceLocation::ReadVal(D); NamedDecl* MemberDecl = cast<NamedDecl>(D.ReadPtr<Decl>()); bool IsArrow = D.ReadBool(); QualType T = QualType::ReadVal(D); Expr* base = D.ReadOwnedPtr<Expr>(C); return new MemberExpr(base,IsArrow,MemberDecl,L,T); } void NullStmt::EmitImpl(Serializer& S) const { S.Emit(SemiLoc); } NullStmt* NullStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation SemiLoc = SourceLocation::ReadVal(D); return new NullStmt(SemiLoc); } void ParenExpr::EmitImpl(Serializer& S) const { S.Emit(L); S.Emit(R); S.EmitOwnedPtr(Val); } ParenExpr* ParenExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation L = SourceLocation::ReadVal(D); SourceLocation R = SourceLocation::ReadVal(D); Expr* val = D.ReadOwnedPtr<Expr>(C); return new ParenExpr(L,R,val); } void PredefinedExpr::EmitImpl(Serializer& S) const { S.Emit(Loc); S.EmitInt(getIdentType()); S.Emit(getType()); } PredefinedExpr* PredefinedExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); IdentType it = static_cast<IdentType>(D.ReadInt()); QualType Q = QualType::ReadVal(D); return new PredefinedExpr(Loc,Q,it); } void ReturnStmt::EmitImpl(Serializer& S) const { S.Emit(RetLoc); S.EmitOwnedPtr(RetExpr); } ReturnStmt* ReturnStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation RetLoc = SourceLocation::ReadVal(D); Expr* RetExpr = D.ReadOwnedPtr<Expr>(C); return new ReturnStmt(RetLoc,RetExpr); } void SizeOfAlignOfExpr::EmitImpl(Serializer& S) const { S.EmitBool(isSizeof); S.EmitBool(isType); if (isType) S.Emit(getArgumentType()); else S.EmitOwnedPtr(getArgumentExpr()); S.Emit(getType()); S.Emit(OpLoc); S.Emit(RParenLoc); } SizeOfAlignOfExpr* SizeOfAlignOfExpr::CreateImpl(Deserializer& D, ASTContext& C) { bool isSizeof = D.ReadBool(); bool isType = D.ReadBool(); void *Argument; if (isType) Argument = QualType::ReadVal(D).getAsOpaquePtr(); else Argument = D.ReadOwnedPtr<Expr>(C); QualType Res = QualType::ReadVal(D); SourceLocation OpLoc = SourceLocation::ReadVal(D); SourceLocation RParenLoc = SourceLocation::ReadVal(D); if (isType) return new (C) SizeOfAlignOfExpr(isSizeof, QualType::getFromOpaquePtr(Argument), Res, OpLoc, RParenLoc); return new (C) SizeOfAlignOfExpr(isSizeof, (Expr *)Argument, Res, OpLoc, RParenLoc); } void StmtExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(LParenLoc); S.Emit(RParenLoc); S.EmitOwnedPtr(SubStmt); } StmtExpr* StmtExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); SourceLocation L = SourceLocation::ReadVal(D); SourceLocation R = SourceLocation::ReadVal(D); CompoundStmt* SubStmt = cast<CompoundStmt>(D.ReadOwnedPtr<Stmt>(C)); return new StmtExpr(SubStmt,t,L,R); } void TypesCompatibleExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.Emit(BuiltinLoc); S.Emit(RParenLoc); S.Emit(Type1); S.Emit(Type2); } TypesCompatibleExpr* TypesCompatibleExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType RT = QualType::ReadVal(D); SourceLocation BL = SourceLocation::ReadVal(D); SourceLocation RP = SourceLocation::ReadVal(D); QualType T1 = QualType::ReadVal(D); QualType T2 = QualType::ReadVal(D); return new TypesCompatibleExpr(RT, BL, T1, T2, RP); } void ShuffleVectorExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.Emit(BuiltinLoc); S.Emit(RParenLoc); S.EmitInt(NumExprs); S.BatchEmitOwnedPtrs(NumExprs, &SubExprs[0]); } ShuffleVectorExpr* ShuffleVectorExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType T = QualType::ReadVal(D); SourceLocation BL = SourceLocation::ReadVal(D); SourceLocation RP = SourceLocation::ReadVal(D); unsigned NumExprs = D.ReadInt(); // FIXME: Avoid extra allocation. llvm::SmallVector<Expr*, 4> Exprs(NumExprs); D.BatchReadOwnedPtrs(NumExprs, Exprs.begin(), C); return new ShuffleVectorExpr(Exprs.begin(), NumExprs, T, BL, RP); } void ChooseExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.Emit(BuiltinLoc); S.Emit(RParenLoc); S.BatchEmitOwnedPtrs((unsigned) END_EXPR, &SubExprs[0]); } ChooseExpr* ChooseExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType T = QualType::ReadVal(D); SourceLocation BL = SourceLocation::ReadVal(D); SourceLocation RP = SourceLocation::ReadVal(D); ChooseExpr *CE = new ChooseExpr(BL, 0, 0, 0, T, RP); D.BatchReadOwnedPtrs((unsigned) END_EXPR, &CE->SubExprs[0], C); return CE; } void GNUNullExpr::EmitImpl(llvm::Serializer &S) const { S.Emit(getType()); S.Emit(TokenLoc); } GNUNullExpr *GNUNullExpr::CreateImpl(llvm::Deserializer &D, ASTContext &C) { QualType T = QualType::ReadVal(D); SourceLocation TL = SourceLocation::ReadVal(D); return new GNUNullExpr(T, TL); } void VAArgExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.Emit(BuiltinLoc); S.Emit(RParenLoc); S.EmitOwnedPtr(getSubExpr()); } VAArgExpr* VAArgExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType T = QualType::ReadVal(D); SourceLocation BL = SourceLocation::ReadVal(D); SourceLocation RP = SourceLocation::ReadVal(D); Expr *E = D.ReadOwnedPtr<Expr>(C); return new VAArgExpr(BL, E, T, RP); } void StringLiteral::EmitImpl(Serializer& S) const { S.Emit(getType()); assert(0 && "Unimpl loc serialization"); S.EmitBool(isWide()); S.Emit(getByteLength()); for (unsigned i = 0 ; i < ByteLength; ++i) S.EmitInt(StrData[i]); } StringLiteral* StringLiteral::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); assert(0 && "Unimpl loc serialization"); //SourceLocation firstTokLoc = SourceLocation::ReadVal(D); //SourceLocation lastTokLoc = SourceLocation::ReadVal(D); bool isWide = D.ReadBool(); unsigned ByteLength = D.ReadInt(); StringLiteral* sl = StringLiteral::Create(C, NULL, 0, isWide, t, SourceLocation()); char* StrData = new (C, llvm::alignof<char>()) char[ByteLength]; for (unsigned i = 0; i < ByteLength; ++i) StrData[i] = (char) D.ReadInt(); sl->ByteLength = ByteLength; sl->StrData = StrData; return sl; } void SwitchStmt::EmitImpl(Serializer& S) const { S.Emit(SwitchLoc); S.EmitOwnedPtr(getCond()); S.EmitOwnedPtr(getBody()); S.EmitPtr(FirstCase); } SwitchStmt* SwitchStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); Stmt* Cond = D.ReadOwnedPtr<Stmt>(C); Stmt* Body = D.ReadOwnedPtr<Stmt>(C); SwitchCase* FirstCase = cast<SwitchCase>(D.ReadPtr<Stmt>()); SwitchStmt* stmt = new SwitchStmt(cast<Expr>(Cond)); stmt->setBody(Body,Loc); stmt->FirstCase = FirstCase; return stmt; } void UnaryOperator::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(Loc); S.EmitInt(Opc); S.EmitOwnedPtr(Val); } UnaryOperator* UnaryOperator::CreateImpl(Deserializer& D, ASTContext& C) { QualType t = QualType::ReadVal(D); SourceLocation L = SourceLocation::ReadVal(D); Opcode Opc = static_cast<Opcode>(D.ReadInt()); Expr* Val = D.ReadOwnedPtr<Expr>(C); return new UnaryOperator(Val,Opc,t,L); } void WhileStmt::EmitImpl(Serializer& S) const { S.Emit(WhileLoc); S.EmitOwnedPtr(getCond()); S.EmitOwnedPtr(getBody()); } WhileStmt* WhileStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation WhileLoc = SourceLocation::ReadVal(D); Expr* Cond = D.ReadOwnedPtr<Expr>(C); Stmt* Body = D.ReadOwnedPtr<Stmt>(C); return new WhileStmt(Cond,Body,WhileLoc); } //===----------------------------------------------------------------------===// // Objective C Serialization //===----------------------------------------------------------------------===// void ObjCAtCatchStmt::EmitImpl(Serializer& S) const { S.Emit(AtCatchLoc); S.Emit(RParenLoc); S.BatchEmitOwnedPtrs((unsigned) END_EXPR, &SubExprs[0]); } ObjCAtCatchStmt* ObjCAtCatchStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation AtCatchLoc = SourceLocation::ReadVal(D); SourceLocation RParenLoc = SourceLocation::ReadVal(D); ObjCAtCatchStmt* stmt = new ObjCAtCatchStmt(AtCatchLoc,RParenLoc); D.BatchReadOwnedPtrs((unsigned) END_EXPR, &stmt->SubExprs[0], C); return stmt; } void ObjCAtFinallyStmt::EmitImpl(Serializer& S) const { S.Emit(AtFinallyLoc); S.EmitOwnedPtr(AtFinallyStmt); } ObjCAtFinallyStmt* ObjCAtFinallyStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); Stmt* AtFinallyStmt = D.ReadOwnedPtr<Stmt>(C); return new ObjCAtFinallyStmt(Loc,AtFinallyStmt); } void ObjCAtSynchronizedStmt::EmitImpl(Serializer& S) const { S.Emit(AtSynchronizedLoc); S.BatchEmitOwnedPtrs((unsigned) END_EXPR,&SubStmts[0]); } ObjCAtSynchronizedStmt* ObjCAtSynchronizedStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation L = SourceLocation::ReadVal(D); ObjCAtSynchronizedStmt* stmt = new ObjCAtSynchronizedStmt(L,0,0); D.BatchReadOwnedPtrs((unsigned) END_EXPR, &stmt->SubStmts[0], C); return stmt; } void ObjCAtThrowStmt::EmitImpl(Serializer& S) const { S.Emit(AtThrowLoc); S.EmitOwnedPtr(Throw); } ObjCAtThrowStmt* ObjCAtThrowStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation L = SourceLocation::ReadVal(D); Stmt* Throw = D.ReadOwnedPtr<Stmt>(C); return new ObjCAtThrowStmt(L,Throw); } void ObjCAtTryStmt::EmitImpl(Serializer& S) const { S.Emit(AtTryLoc); S.BatchEmitOwnedPtrs((unsigned) END_EXPR, &SubStmts[0]); } ObjCAtTryStmt* ObjCAtTryStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation L = SourceLocation::ReadVal(D); ObjCAtTryStmt* stmt = new ObjCAtTryStmt(L,NULL,NULL,NULL); D.BatchReadOwnedPtrs((unsigned) END_EXPR, &stmt->SubStmts[0], C); return stmt; } void ObjCEncodeExpr::EmitImpl(Serializer& S) const { S.Emit(AtLoc); S.Emit(RParenLoc); S.Emit(getType()); S.Emit(EncType); } ObjCEncodeExpr* ObjCEncodeExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation AtLoc = SourceLocation::ReadVal(D); SourceLocation RParenLoc = SourceLocation::ReadVal(D); QualType T = QualType::ReadVal(D); QualType ET = QualType::ReadVal(D); return new ObjCEncodeExpr(T,ET,AtLoc,RParenLoc); } void ObjCForCollectionStmt::EmitImpl(Serializer& S) const { S.Emit(ForLoc); S.Emit(RParenLoc); S.BatchEmitOwnedPtrs(getElement(),getCollection(),getBody()); } ObjCForCollectionStmt* ObjCForCollectionStmt::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation ForLoc = SourceLocation::ReadVal(D); SourceLocation RParenLoc = SourceLocation::ReadVal(D); Stmt* Element; Expr* Collection; Stmt* Body; D.BatchReadOwnedPtrs(Element, Collection, Body, C); return new ObjCForCollectionStmt(Element,Collection,Body,ForLoc, RParenLoc); } void ObjCProtocolExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.EmitPtr(Protocol); S.Emit(AtLoc); S.Emit(RParenLoc); } ObjCProtocolExpr* ObjCProtocolExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType T = QualType::ReadVal(D); ObjCProtocolDecl *PD = D.ReadPtr<ObjCProtocolDecl>(); SourceLocation AL = SourceLocation::ReadVal(D); SourceLocation RP = SourceLocation::ReadVal(D); return new ObjCProtocolExpr(T, PD, AL, RP); } void ObjCIvarRefExpr::EmitImpl(Serializer& S) const { S.Emit(Loc); S.Emit(getType()); S.EmitPtr(getDecl()); } ObjCIvarRefExpr* ObjCIvarRefExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); QualType T = QualType::ReadVal(D); ObjCIvarRefExpr* dr = new ObjCIvarRefExpr(NULL,T,Loc); D.ReadPtr(dr->D,false); return dr; } void ObjCPropertyRefExpr::EmitImpl(Serializer& S) const { S.Emit(IdLoc); S.Emit(getType()); S.EmitPtr(getProperty()); } void ObjCKVCRefExpr::EmitImpl(Serializer& S) const { S.Emit(Loc); S.Emit(getType()); S.EmitPtr(getGetterMethod()); S.EmitPtr(getSetterMethod()); } ObjCPropertyRefExpr* ObjCPropertyRefExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); QualType T = QualType::ReadVal(D); ObjCPropertyRefExpr* dr = new ObjCPropertyRefExpr(NULL,T,Loc,0); D.ReadPtr(dr->AsProperty,false); return dr; } ObjCKVCRefExpr* ObjCKVCRefExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation Loc = SourceLocation::ReadVal(D); QualType T = QualType::ReadVal(D); ObjCKVCRefExpr* dr = new ObjCKVCRefExpr(NULL,T,NULL,Loc,0); D.ReadPtr(dr->Setter,false); D.ReadPtr(dr->Getter,false); return dr; } void ObjCMessageExpr::EmitImpl(Serializer& S) const { S.EmitInt(getFlag()); S.Emit(getType()); S.Emit(SelName); S.Emit(LBracloc); S.Emit(RBracloc); S.EmitInt(NumArgs); S.EmitPtr(MethodProto); if (getReceiver()) S.BatchEmitOwnedPtrs(NumArgs+1, SubExprs); else { ClassInfo Info = getClassInfo(); if (Info.first) S.EmitPtr(Info.first); else S.EmitPtr(Info.second); S.BatchEmitOwnedPtrs(NumArgs, &SubExprs[ARGS_START]); } } ObjCMessageExpr* ObjCMessageExpr::CreateImpl(Deserializer& D, ASTContext& C) { unsigned flags = D.ReadInt(); QualType t = QualType::ReadVal(D); Selector S = Selector::ReadVal(D); SourceLocation L = SourceLocation::ReadVal(D); SourceLocation R = SourceLocation::ReadVal(D); // Construct an array for the subexpressions. unsigned NumArgs = D.ReadInt(); Stmt** SubExprs = new Stmt*[NumArgs+1]; // Construct the ObjCMessageExpr object using the special ctor. ObjCMessageExpr* ME = new ObjCMessageExpr(S, t, L, R, SubExprs, NumArgs); // Read in the MethodProto. Read the instance variable directly // allows it to be backpatched. D.ReadPtr(ME->MethodProto); // Now read in the arguments. if ((flags & Flags) == IsInstMeth) D.BatchReadOwnedPtrs(NumArgs+1, SubExprs, C); else { // Read the pointer for Cls/ClassName. The Deserializer will handle the // bit-mangling automatically. SubExprs[RECEIVER] = (Stmt*) ((uintptr_t) flags); D.ReadUIntPtr((uintptr_t&) SubExprs[RECEIVER]); // Read the arguments. D.BatchReadOwnedPtrs(NumArgs, &SubExprs[ARGS_START], C); } return ME; } void ObjCSelectorExpr::EmitImpl(Serializer& S) const { S.Emit(AtLoc); S.Emit(RParenLoc); S.Emit(getType()); S.Emit(SelName); } ObjCSelectorExpr* ObjCSelectorExpr::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation AtLoc = SourceLocation::ReadVal(D); SourceLocation RParenLoc = SourceLocation::ReadVal(D); QualType T = QualType::ReadVal(D); Selector SelName = Selector::ReadVal(D); return new ObjCSelectorExpr(T,SelName,AtLoc,RParenLoc); } void ObjCStringLiteral::EmitImpl(Serializer& S) const { S.Emit(AtLoc); S.Emit(getType()); S.EmitOwnedPtr(String); } ObjCStringLiteral* ObjCStringLiteral::CreateImpl(Deserializer& D, ASTContext& C) { SourceLocation L = SourceLocation::ReadVal(D); QualType T = QualType::ReadVal(D); StringLiteral* String = cast<StringLiteral>(D.ReadOwnedPtr<Stmt>(C)); return new ObjCStringLiteral(String,T,L); } void ObjCSuperExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.Emit(Loc); } ObjCSuperExpr* ObjCSuperExpr::CreateImpl(llvm::Deserializer& D, ASTContext&) { QualType Ty = QualType::ReadVal(D); SourceLocation Loc = SourceLocation::ReadVal(D); return new ObjCSuperExpr(Loc, Ty); } //===----------------------------------------------------------------------===// // Serialization for Clang Extensions. //===----------------------------------------------------------------------===// void ExtVectorElementExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.EmitOwnedPtr(getBase()); S.EmitPtr(&Accessor); S.Emit(AccessorLoc); } ExtVectorElementExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType T = QualType::ReadVal(D); Expr *B = D.ReadOwnedPtr<Expr>(C); IdentifierInfo *A = D.ReadPtr<IdentifierInfo>(); SourceLocation AL = SourceLocation::ReadVal(D); return new (C) ExtVectorElementExpr(T, B, *A, AL); } void BlockExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.EmitOwnedPtr(TheBlock); S.EmitBool(HasBlockDeclRefExprs); } BlockExpr* BlockExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType T = QualType::ReadVal(D); BlockDecl *B = cast<BlockDecl>(D.ReadOwnedPtr<Decl>(C)); bool H = D.ReadBool(); return new BlockExpr(B,T,H); } void BlockDeclRefExpr::EmitImpl(Serializer& S) const { S.Emit(Loc); S.Emit(getType()); S.EmitBool(false); S.EmitPtr(getDecl()); } BlockDeclRefExpr* BlockDeclRefExpr::CreateImpl(Deserializer& D, ASTContext& C) { assert(0 && "Cannot deserialize BlockDeclRefExpr yet"); return 0; } //===----------------------------------------------------------------------===// // C++ Serialization //===----------------------------------------------------------------------===// void CXXDefaultArgExpr::EmitImpl(Serializer& S) const { S.EmitPtr(Param); } CXXDefaultArgExpr *CXXDefaultArgExpr::CreateImpl(Deserializer& D, ASTContext& C) { ParmVarDecl* Param = 0; D.ReadPtr(Param, false); return new CXXDefaultArgExpr(Param); } void CXXFunctionalCastExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(getTypeAsWritten()); S.Emit(TyBeginLoc); S.Emit(RParenLoc); S.EmitOwnedPtr(getSubExpr()); } CXXFunctionalCastExpr * CXXFunctionalCastExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType Ty = QualType::ReadVal(D); QualType WrittenTy = QualType::ReadVal(D); SourceLocation TyBeginLoc = SourceLocation::ReadVal(D); SourceLocation RParenLoc = SourceLocation::ReadVal(D); Expr* SubExpr = D.ReadOwnedPtr<Expr>(C); return new CXXFunctionalCastExpr(Ty, WrittenTy, TyBeginLoc, SubExpr, RParenLoc); } void CXXNamedCastExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(getTypeAsWritten()); S.Emit(Loc); S.EmitOwnedPtr(getSubExpr()); } CXXNamedCastExpr * CXXNamedCastExpr::CreateImpl(Deserializer& D, ASTContext& C, StmtClass SC) { QualType Ty = QualType::ReadVal(D); QualType WrittenTy = QualType::ReadVal(D); SourceLocation Loc = SourceLocation::ReadVal(D); Expr* SubExpr = D.ReadOwnedPtr<Expr>(C); switch (SC) { case CXXStaticCastExprClass: return new CXXStaticCastExpr(Ty, SubExpr, WrittenTy, Loc); case CXXDynamicCastExprClass: return new CXXDynamicCastExpr(Ty, SubExpr, WrittenTy, Loc); case CXXReinterpretCastExprClass: return new CXXReinterpretCastExpr(Ty, SubExpr, WrittenTy, Loc); case CXXConstCastExprClass: return new CXXConstCastExpr(Ty, SubExpr, WrittenTy, Loc); default: assert(false && "Unknown cast type!"); return 0; } } void CXXTypeidExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.EmitBool(isTypeOperand()); if (isTypeOperand()) { S.Emit(getTypeOperand()); } else { S.EmitOwnedPtr(getExprOperand()); } S.Emit(Range); } CXXTypeidExpr* CXXTypeidExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType Ty = QualType::ReadVal(D); bool isTypeOp = D.ReadBool(); void *Operand; if (isTypeOp) { Operand = QualType::ReadVal(D).getAsOpaquePtr(); } else { Operand = D.ReadOwnedPtr<Expr>(C); } SourceRange Range = SourceRange::ReadVal(D); return new CXXTypeidExpr(isTypeOp, Operand, Ty, Range); } void CXXThisExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.Emit(Loc); } CXXThisExpr* CXXThisExpr::CreateImpl(llvm::Deserializer& D, ASTContext&) { QualType Ty = QualType::ReadVal(D); SourceLocation Loc = SourceLocation::ReadVal(D); return new CXXThisExpr(Loc, Ty); } void CXXTemporaryObjectExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.Emit(TyBeginLoc); S.Emit(RParenLoc); S.EmitPtr(cast<Decl>(Constructor)); S.EmitInt(NumArgs); if (NumArgs > 0) S.BatchEmitOwnedPtrs(NumArgs, Args); } CXXTemporaryObjectExpr * CXXTemporaryObjectExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType writtenTy = QualType::ReadVal(D); SourceLocation tyBeginLoc = SourceLocation::ReadVal(D); SourceLocation rParenLoc = SourceLocation::ReadVal(D); CXXConstructorDecl * Cons = cast_or_null<CXXConstructorDecl>(D.ReadPtr<Decl>()); unsigned NumArgs = D.ReadInt(); Stmt** Args = 0; if (NumArgs > 0) { Args = new Stmt*[NumArgs]; D.BatchReadOwnedPtrs(NumArgs, Args, C); } CXXTemporaryObjectExpr * Result = new CXXTemporaryObjectExpr(Cons, writtenTy, tyBeginLoc, (Expr**)Args, NumArgs, rParenLoc); if (NumArgs > 0) delete [] Args; return Result; } void CXXZeroInitValueExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.Emit(TyBeginLoc); S.Emit(RParenLoc); } CXXZeroInitValueExpr * CXXZeroInitValueExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType Ty = QualType::ReadVal(D); SourceLocation TyBeginLoc = SourceLocation::ReadVal(D); SourceLocation RParenLoc = SourceLocation::ReadVal(D); return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc); } void CXXNewExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.EmitBool(GlobalNew); S.EmitBool(ParenTypeId); S.EmitBool(Initializer); S.EmitBool(Array); S.EmitInt(NumPlacementArgs); S.EmitInt(NumConstructorArgs); S.BatchEmitOwnedPtrs(NumPlacementArgs + NumConstructorArgs, SubExprs); assert((OperatorNew == 0 || S.isRegistered(OperatorNew)) && (OperatorDelete == 0 || S.isRegistered(OperatorDelete)) && (Constructor == 0 || S.isRegistered(Constructor)) && "CXXNewExpr cannot own declarations"); S.EmitPtr(OperatorNew); S.EmitPtr(OperatorDelete); S.EmitPtr(Constructor); S.Emit(StartLoc); S.Emit(EndLoc); } CXXNewExpr * CXXNewExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType T = QualType::ReadVal(D); bool GlobalNew = D.ReadBool(); bool ParenTypeId = D.ReadBool(); bool Initializer = D.ReadBool(); bool Array = D.ReadBool(); unsigned NumPlacementArgs = D.ReadInt(); unsigned NumConstructorArgs = D.ReadInt(); unsigned TotalExprs = Array + NumPlacementArgs + NumConstructorArgs; Stmt** SubExprs = new Stmt*[TotalExprs]; D.BatchReadOwnedPtrs(TotalExprs, SubExprs, C); FunctionDecl *OperatorNew = D.ReadPtr<FunctionDecl>(); FunctionDecl *OperatorDelete = D.ReadPtr<FunctionDecl>(); CXXConstructorDecl *Constructor = D.ReadPtr<CXXConstructorDecl>(); SourceLocation StartLoc = SourceLocation::ReadVal(D); SourceLocation EndLoc = SourceLocation::ReadVal(D); return new CXXNewExpr(T, GlobalNew, ParenTypeId, Initializer, Array, NumPlacementArgs, NumConstructorArgs, SubExprs, OperatorNew, OperatorDelete, Constructor, StartLoc, EndLoc); } void CXXDeleteExpr::EmitImpl(Serializer& S) const { S.Emit(getType()); S.EmitBool(GlobalDelete); S.EmitBool(ArrayForm); S.EmitPtr(OperatorDelete); S.EmitOwnedPtr(Argument); S.Emit(Loc); } CXXDeleteExpr * CXXDeleteExpr::CreateImpl(Deserializer& D, ASTContext& C) { QualType Ty = QualType::ReadVal(D); bool GlobalDelete = D.ReadBool(); bool ArrayForm = D.ReadBool(); FunctionDecl *OperatorDelete = D.ReadPtr<FunctionDecl>(); Stmt *Argument = D.ReadOwnedPtr<Stmt>(C); SourceLocation Loc = SourceLocation::ReadVal(D); return new CXXDeleteExpr(Ty, GlobalDelete, ArrayForm, OperatorDelete, cast<Expr>(Argument), Loc); } void UnresolvedFunctionNameExpr::EmitImpl(llvm::Serializer& S) const { S.Emit(getType()); S.EmitPtr(Name.getAsIdentifierInfo()); // FIXME: WRONG! S.Emit(Loc); } UnresolvedFunctionNameExpr * UnresolvedFunctionNameExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { QualType Ty = QualType::ReadVal(D); IdentifierInfo *N = D.ReadPtr<IdentifierInfo>(); SourceLocation L = SourceLocation::ReadVal(D); return new UnresolvedFunctionNameExpr(N, Ty, L); } void UnaryTypeTraitExpr::EmitImpl(llvm::Serializer& S) const { S.EmitInt(UTT); S.Emit(Loc); S.Emit(RParen); S.Emit(QueriedType); S.Emit(getType()); } UnaryTypeTraitExpr * UnaryTypeTraitExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { UnaryTypeTrait UTT = static_cast<UnaryTypeTrait>(D.ReadInt()); SourceLocation Loc = SourceLocation::ReadVal(D); SourceLocation RParen = SourceLocation::ReadVal(D); QualType QueriedType = QualType::ReadVal(D); QualType Ty = QualType::ReadVal(D); return new UnaryTypeTraitExpr(Loc, UTT, QueriedType, RParen, Ty); } void CXXCatchStmt::EmitImpl(llvm::Serializer& S) const { S.Emit(CatchLoc); S.EmitOwnedPtr(ExceptionDecl); S.EmitOwnedPtr(HandlerBlock); } CXXCatchStmt * CXXCatchStmt::CreateImpl(llvm::Deserializer& D, ASTContext& C) { SourceLocation CatchLoc = SourceLocation::ReadVal(D); Decl *ExDecl = D.ReadOwnedPtr<Decl>(C); Stmt *HandlerBlock = D.ReadOwnedPtr<Stmt>(C); return new CXXCatchStmt(CatchLoc, ExDecl, HandlerBlock); } void CXXTryStmt::EmitImpl(llvm::Serializer& S) const { S.Emit(TryLoc); S.EmitInt(Stmts.size()); S.BatchEmitOwnedPtrs(Stmts.size(), &Stmts[0]); } CXXTryStmt * CXXTryStmt::CreateImpl(llvm::Deserializer& D, ASTContext& C) { SourceLocation TryLoc = SourceLocation::ReadVal(D); unsigned size = D.ReadInt(); llvm::SmallVector<Stmt*, 4> Stmts(size); D.BatchReadOwnedPtrs<Stmt>(size, &Stmts[0], C); return new CXXTryStmt(TryLoc, Stmts[0], &Stmts[1], size - 1); } void QualifiedDeclRefExpr::EmitImpl(llvm::Serializer& S) const { DeclRefExpr::EmitImpl(S); S.Emit(QualifierRange); // FIXME: Serialize nested-name-specifiers } QualifiedDeclRefExpr* QualifiedDeclRefExpr::CreateImpl(llvm::Deserializer& D, ASTContext& C) { assert(false && "Cannot deserialize qualified decl references"); return 0; } <file_sep>/lib/CodeGen/CGBuiltin.cpp //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This contains code to emit Builtin calls as LLVM code. // //===----------------------------------------------------------------------===// #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "clang/Basic/TargetInfo.h" #include "clang/AST/APValue.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/TargetBuiltins.h" #include "llvm/Intrinsics.h" using namespace clang; using namespace CodeGen; using namespace llvm; /// Utility to insert an atomic instruction based on Instrinsic::ID /// and the expression node. static RValue EmitBinaryAtomic(CodeGenFunction& CGF, Intrinsic::ID Id, const CallExpr *E) { const llvm::Type *ResType[2]; ResType[0] = CGF.ConvertType(E->getType()); ResType[1] = CGF.ConvertType(E->getArg(0)->getType()); Value *AtomF = CGF.CGM.getIntrinsic(Id, ResType, 2); return RValue::get(CGF.Builder.CreateCall2(AtomF, CGF.EmitScalarExpr(E->getArg(0)), CGF.EmitScalarExpr(E->getArg(1)))); } /// Utility to insert an atomic instruction based Instrinsic::ID and // the expression node, where the return value is the result of the // operation. static RValue EmitBinaryAtomicPost(CodeGenFunction& CGF, Intrinsic::ID Id, const CallExpr *E, Instruction::BinaryOps Op) { const llvm::Type *ResType[2]; ResType[0] = CGF.ConvertType(E->getType()); ResType[1] = CGF.ConvertType(E->getArg(0)->getType()); Value *AtomF = CGF.CGM.getIntrinsic(Id, ResType, 2); Value *Ptr = CGF.EmitScalarExpr(E->getArg(0)); Value *Operand = CGF.EmitScalarExpr(E->getArg(1)); Value *Result = CGF.Builder.CreateCall2(AtomF, Ptr, Operand); return RValue::get(CGF.Builder.CreateBinOp(Op, Result, Operand)); } RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD, unsigned BuiltinID, const CallExpr *E) { // See if we can constant fold this builtin. If so, don't emit it at all. Expr::EvalResult Result; if (E->Evaluate(Result, CGM.getContext())) { if (Result.Val.isInt()) return RValue::get(llvm::ConstantInt::get(Result.Val.getInt())); else if (Result.Val.isFloat()) return RValue::get(llvm::ConstantFP::get(Result.Val.getFloat())); } switch (BuiltinID) { default: break; // Handle intrinsics and libm functions below. case Builtin::BI__builtin___CFStringMakeConstantString: return RValue::get(CGM.EmitConstantExpr(E, E->getType(), 0)); case Builtin::BI__builtin_stdarg_start: case Builtin::BI__builtin_va_start: case Builtin::BI__builtin_va_end: { Value *ArgValue = EmitVAListRef(E->getArg(0)); const llvm::Type *DestType = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); if (ArgValue->getType() != DestType) ArgValue = Builder.CreateBitCast(ArgValue, DestType, ArgValue->getNameStart()); Intrinsic::ID inst = (BuiltinID == Builtin::BI__builtin_va_end) ? Intrinsic::vaend : Intrinsic::vastart; return RValue::get(Builder.CreateCall(CGM.getIntrinsic(inst), ArgValue)); } case Builtin::BI__builtin_va_copy: { Value *DstPtr = EmitVAListRef(E->getArg(0)); Value *SrcPtr = EmitVAListRef(E->getArg(1)); const llvm::Type *Type = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); DstPtr = Builder.CreateBitCast(DstPtr, Type); SrcPtr = Builder.CreateBitCast(SrcPtr, Type); return RValue::get(Builder.CreateCall2(CGM.getIntrinsic(Intrinsic::vacopy), DstPtr, SrcPtr)); } case Builtin::BI__builtin_abs: { Value *ArgValue = EmitScalarExpr(E->getArg(0)); Value *NegOp = Builder.CreateNeg(ArgValue, "neg"); Value *CmpResult = Builder.CreateICmpSGE(ArgValue, Constant::getNullValue(ArgValue->getType()), "abscond"); Value *Result = Builder.CreateSelect(CmpResult, ArgValue, NegOp, "abs"); return RValue::get(Result); } case Builtin::BI__builtin_ctz: case Builtin::BI__builtin_ctzl: case Builtin::BI__builtin_ctzll: { Value *ArgValue = EmitScalarExpr(E->getArg(0)); const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::cttz, &ArgType, 1); const llvm::Type *ResultType = ConvertType(E->getType()); Value *Result = Builder.CreateCall(F, ArgValue, "tmp"); if (Result->getType() != ResultType) Result = Builder.CreateIntCast(Result, ResultType, "cast"); return RValue::get(Result); } case Builtin::BI__builtin_clz: case Builtin::BI__builtin_clzl: case Builtin::BI__builtin_clzll: { Value *ArgValue = EmitScalarExpr(E->getArg(0)); const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::ctlz, &ArgType, 1); const llvm::Type *ResultType = ConvertType(E->getType()); Value *Result = Builder.CreateCall(F, ArgValue, "tmp"); if (Result->getType() != ResultType) Result = Builder.CreateIntCast(Result, ResultType, "cast"); return RValue::get(Result); } case Builtin::BI__builtin_ffs: case Builtin::BI__builtin_ffsl: case Builtin::BI__builtin_ffsll: { // ffs(x) -> x ? cttz(x) + 1 : 0 Value *ArgValue = EmitScalarExpr(E->getArg(0)); const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::cttz, &ArgType, 1); const llvm::Type *ResultType = ConvertType(E->getType()); Value *Tmp = Builder.CreateAdd(Builder.CreateCall(F, ArgValue, "tmp"), ConstantInt::get(ArgType, 1), "tmp"); Value *Zero = llvm::Constant::getNullValue(ArgType); Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero"); Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp, "ffs"); if (Result->getType() != ResultType) Result = Builder.CreateIntCast(Result, ResultType, "cast"); return RValue::get(Result); } case Builtin::BI__builtin_parity: case Builtin::BI__builtin_parityl: case Builtin::BI__builtin_parityll: { // parity(x) -> ctpop(x) & 1 Value *ArgValue = EmitScalarExpr(E->getArg(0)); const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::ctpop, &ArgType, 1); const llvm::Type *ResultType = ConvertType(E->getType()); Value *Tmp = Builder.CreateCall(F, ArgValue, "tmp"); Value *Result = Builder.CreateAnd(Tmp, ConstantInt::get(ArgType, 1), "tmp"); if (Result->getType() != ResultType) Result = Builder.CreateIntCast(Result, ResultType, "cast"); return RValue::get(Result); } case Builtin::BI__builtin_popcount: case Builtin::BI__builtin_popcountl: case Builtin::BI__builtin_popcountll: { Value *ArgValue = EmitScalarExpr(E->getArg(0)); const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::ctpop, &ArgType, 1); const llvm::Type *ResultType = ConvertType(E->getType()); Value *Result = Builder.CreateCall(F, ArgValue, "tmp"); if (Result->getType() != ResultType) Result = Builder.CreateIntCast(Result, ResultType, "cast"); return RValue::get(Result); } case Builtin::BI__builtin_expect: // FIXME: pass expect through to LLVM return RValue::get(EmitScalarExpr(E->getArg(0))); case Builtin::BI__builtin_bswap32: case Builtin::BI__builtin_bswap64: { Value *ArgValue = EmitScalarExpr(E->getArg(0)); const llvm::Type *ArgType = ArgValue->getType(); Value *F = CGM.getIntrinsic(Intrinsic::bswap, &ArgType, 1); return RValue::get(Builder.CreateCall(F, ArgValue, "tmp")); } case Builtin::BI__builtin_object_size: { // FIXME: Implement. For now we just always fail and pretend we // don't know the object size. llvm::APSInt TypeArg = E->getArg(1)->getIntegerConstantExprValue(CGM.getContext()); const llvm::Type *ResType = ConvertType(E->getType()); // bool UseSubObject = TypeArg.getZExtValue() & 1; bool UseMinimum = TypeArg.getZExtValue() & 2; return RValue::get(ConstantInt::get(ResType, UseMinimum ? 0 : -1LL)); } case Builtin::BI__builtin_prefetch: { Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0)); // FIXME: Technically these constants should of type 'int', yes? RW = (E->getNumArgs() > 1) ? EmitScalarExpr(E->getArg(1)) : ConstantInt::get(llvm::Type::Int32Ty, 0); Locality = (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : ConstantInt::get(llvm::Type::Int32Ty, 3); Value *F = CGM.getIntrinsic(Intrinsic::prefetch, 0, 0); return RValue::get(Builder.CreateCall3(F, Address, RW, Locality)); } case Builtin::BI__builtin_trap: { Value *F = CGM.getIntrinsic(Intrinsic::trap, 0, 0); return RValue::get(Builder.CreateCall(F)); } case Builtin::BI__builtin_powi: case Builtin::BI__builtin_powif: case Builtin::BI__builtin_powil: { Value *Base = EmitScalarExpr(E->getArg(0)); Value *Exponent = EmitScalarExpr(E->getArg(1)); const llvm::Type *ArgType = Base->getType(); Value *F = CGM.getIntrinsic(Intrinsic::powi, &ArgType, 1); return RValue::get(Builder.CreateCall2(F, Base, Exponent, "tmp")); } case Builtin::BI__builtin_isgreater: case Builtin::BI__builtin_isgreaterequal: case Builtin::BI__builtin_isless: case Builtin::BI__builtin_islessequal: case Builtin::BI__builtin_islessgreater: case Builtin::BI__builtin_isunordered: { // Ordered comparisons: we know the arguments to these are matching scalar // floating point values. Value *LHS = EmitScalarExpr(E->getArg(0)); Value *RHS = EmitScalarExpr(E->getArg(1)); switch (BuiltinID) { default: assert(0 && "Unknown ordered comparison"); case Builtin::BI__builtin_isgreater: LHS = Builder.CreateFCmpOGT(LHS, RHS, "cmp"); break; case Builtin::BI__builtin_isgreaterequal: LHS = Builder.CreateFCmpOGE(LHS, RHS, "cmp"); break; case Builtin::BI__builtin_isless: LHS = Builder.CreateFCmpOLT(LHS, RHS, "cmp"); break; case Builtin::BI__builtin_islessequal: LHS = Builder.CreateFCmpOLE(LHS, RHS, "cmp"); break; case Builtin::BI__builtin_islessgreater: LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp"); break; case Builtin::BI__builtin_isunordered: LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp"); break; } // ZExt bool to int type. return RValue::get(Builder.CreateZExt(LHS, ConvertType(E->getType()), "tmp")); } case Builtin::BI__builtin_alloca: { // FIXME: LLVM IR Should allow alloca with an i64 size! Value *Size = EmitScalarExpr(E->getArg(0)); Size = Builder.CreateIntCast(Size, llvm::Type::Int32Ty, false, "tmp"); return RValue::get(Builder.CreateAlloca(llvm::Type::Int8Ty, Size, "tmp")); } case Builtin::BI__builtin_bzero: { Value *Address = EmitScalarExpr(E->getArg(0)); Builder.CreateCall4(CGM.getMemSetFn(), Address, llvm::ConstantInt::get(llvm::Type::Int8Ty, 0), EmitScalarExpr(E->getArg(1)), llvm::ConstantInt::get(llvm::Type::Int32Ty, 1)); return RValue::get(Address); } case Builtin::BI__builtin_memcpy: { Value *Address = EmitScalarExpr(E->getArg(0)); Builder.CreateCall4(CGM.getMemCpyFn(), Address, EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2)), llvm::ConstantInt::get(llvm::Type::Int32Ty, 1)); return RValue::get(Address); } case Builtin::BI__builtin_memmove: { Value *Address = EmitScalarExpr(E->getArg(0)); Builder.CreateCall4(CGM.getMemMoveFn(), Address, EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2)), llvm::ConstantInt::get(llvm::Type::Int32Ty, 1)); return RValue::get(Address); } case Builtin::BI__builtin_memset: { Value *Address = EmitScalarExpr(E->getArg(0)); Builder.CreateCall4(CGM.getMemSetFn(), Address, Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)), llvm::Type::Int8Ty), EmitScalarExpr(E->getArg(2)), llvm::ConstantInt::get(llvm::Type::Int32Ty, 1)); return RValue::get(Address); } case Builtin::BI__builtin_return_address: { Value *F = CGM.getIntrinsic(Intrinsic::returnaddress, 0, 0); return RValue::get(Builder.CreateCall(F, EmitScalarExpr(E->getArg(0)))); } case Builtin::BI__builtin_frame_address: { Value *F = CGM.getIntrinsic(Intrinsic::frameaddress, 0, 0); return RValue::get(Builder.CreateCall(F, EmitScalarExpr(E->getArg(0)))); } case Builtin::BI__sync_fetch_and_add: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_add, E); case Builtin::BI__sync_fetch_and_sub: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_sub, E); case Builtin::BI__sync_fetch_and_min: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_min, E); case Builtin::BI__sync_fetch_and_max: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_max, E); case Builtin::BI__sync_fetch_and_umin: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_umin, E); case Builtin::BI__sync_fetch_and_umax: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_umax, E); case Builtin::BI__sync_fetch_and_and: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_and, E); case Builtin::BI__sync_fetch_and_or: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_or, E); case Builtin::BI__sync_fetch_and_xor: return EmitBinaryAtomic(*this, Intrinsic::atomic_load_xor, E); case Builtin::BI__sync_add_and_fetch: return EmitBinaryAtomicPost(*this, Intrinsic::atomic_load_add, E, llvm::Instruction::Add); case Builtin::BI__sync_sub_and_fetch: return EmitBinaryAtomicPost(*this, Intrinsic::atomic_load_sub, E, llvm::Instruction::Sub); case Builtin::BI__sync_and_and_fetch: return EmitBinaryAtomicPost(*this, Intrinsic::atomic_load_and, E, llvm::Instruction::And); case Builtin::BI__sync_or_and_fetch: return EmitBinaryAtomicPost(*this, Intrinsic::atomic_load_or, E, llvm::Instruction::Or); case Builtin::BI__sync_xor_and_fetch: return EmitBinaryAtomicPost(*this, Intrinsic::atomic_load_xor, E, llvm::Instruction::Xor); case Builtin::BI__sync_val_compare_and_swap: { const llvm::Type *ResType[2]; ResType[0]= ConvertType(E->getType()); ResType[1] = ConvertType(E->getArg(0)->getType()); Value *AtomF = CGM.getIntrinsic(Intrinsic::atomic_cmp_swap, ResType, 2); return RValue::get(Builder.CreateCall3(AtomF, EmitScalarExpr(E->getArg(0)), EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2)))); } case Builtin::BI__sync_bool_compare_and_swap: { const llvm::Type *ResType[2]; ResType[0]= ConvertType(E->getType()); ResType[1] = ConvertType(E->getArg(0)->getType()); Value *AtomF = CGM.getIntrinsic(Intrinsic::atomic_cmp_swap, ResType, 2); Value *OldVal = EmitScalarExpr(E->getArg(1)); Value *PrevVal = Builder.CreateCall3(AtomF, EmitScalarExpr(E->getArg(0)), OldVal, EmitScalarExpr(E->getArg(2))); Value *Result = Builder.CreateICmpEQ(PrevVal, OldVal); // zext bool to int. return RValue::get(Builder.CreateZExt(Result, ConvertType(E->getType()))); } case Builtin::BI__sync_lock_test_and_set: return EmitBinaryAtomic(*this, Intrinsic::atomic_swap, E); // Library functions with special handling. case Builtin::BIsqrt: case Builtin::BIsqrtf: case Builtin::BIsqrtl: { // Rewrite sqrt to intrinsic if allowed. if (!FD->hasAttr<ConstAttr>()) break; Value *Arg0 = EmitScalarExpr(E->getArg(0)); const llvm::Type *ArgType = Arg0->getType(); Value *F = CGM.getIntrinsic(Intrinsic::sqrt, &ArgType, 1); return RValue::get(Builder.CreateCall(F, Arg0, "tmp")); } case Builtin::BIpow: case Builtin::BIpowf: case Builtin::BIpowl: { // Rewrite sqrt to intrinsic if allowed. if (!FD->hasAttr<ConstAttr>()) break; Value *Base = EmitScalarExpr(E->getArg(0)); Value *Exponent = EmitScalarExpr(E->getArg(1)); const llvm::Type *ArgType = Base->getType(); Value *F = CGM.getIntrinsic(Intrinsic::pow, &ArgType, 1); return RValue::get(Builder.CreateCall2(F, Base, Exponent, "tmp")); } } // If this is an alias for a libm function (e.g. __builtin_sin) turn it into // that function. if (getContext().BuiltinInfo.isLibFunction(BuiltinID) || getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID)) return EmitCallExpr(CGM.getBuiltinLibFunction(BuiltinID), E->getCallee()->getType(), E->arg_begin(), E->arg_end()); // See if we have a target specific intrinsic. const char *Name = getContext().BuiltinInfo.GetName(BuiltinID); Intrinsic::ID IntrinsicID = Intrinsic::getIntrinsicForGCCBuiltin(Target.getTargetPrefix(), Name); if (IntrinsicID != Intrinsic::not_intrinsic) { SmallVector<Value*, 16> Args; Function *F = CGM.getIntrinsic(IntrinsicID); const llvm::FunctionType *FTy = F->getFunctionType(); for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { Value *ArgValue = EmitScalarExpr(E->getArg(i)); // If the intrinsic arg type is different from the builtin arg type // we need to do a bit cast. const llvm::Type *PTy = FTy->getParamType(i); if (PTy != ArgValue->getType()) { assert(PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) && "Must be able to losslessly bit cast to param"); ArgValue = Builder.CreateBitCast(ArgValue, PTy); } Args.push_back(ArgValue); } Value *V = Builder.CreateCall(F, &Args[0], &Args[0] + Args.size()); QualType BuiltinRetType = E->getType(); const llvm::Type *RetTy = llvm::Type::VoidTy; if (!BuiltinRetType->isVoidType()) RetTy = ConvertType(BuiltinRetType); if (RetTy != V->getType()) { assert(V->getType()->canLosslesslyBitCastTo(RetTy) && "Must be able to losslessly bit cast result type"); V = Builder.CreateBitCast(V, RetTy); } return RValue::get(V); } // See if we have a target specific builtin that needs to be lowered. if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E)) return RValue::get(V); ErrorUnsupported(E, "builtin function"); // Unknown builtin, for now just dump it out and return undef. if (hasAggregateLLVMType(E->getType())) return RValue::getAggregate(CreateTempAlloca(ConvertType(E->getType()))); return RValue::get(UndefValue::get(ConvertType(E->getType()))); } Value *CodeGenFunction::EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E) { const char *TargetPrefix = Target.getTargetPrefix(); if (strcmp(TargetPrefix, "x86") == 0) return EmitX86BuiltinExpr(BuiltinID, E); else if (strcmp(TargetPrefix, "ppc") == 0) return EmitPPCBuiltinExpr(BuiltinID, E); return 0; } Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E) { llvm::SmallVector<Value*, 4> Ops; for (unsigned i = 0, e = E->getNumArgs(); i != e; i++) Ops.push_back(EmitScalarExpr(E->getArg(i))); switch (BuiltinID) { default: return 0; case X86::BI__builtin_ia32_mulps: return Builder.CreateMul(Ops[0], Ops[1], "mulps"); case X86::BI__builtin_ia32_mulpd: return Builder.CreateMul(Ops[0], Ops[1], "mulpd"); case X86::BI__builtin_ia32_pand: case X86::BI__builtin_ia32_pand128: return Builder.CreateAnd(Ops[0], Ops[1], "pand"); case X86::BI__builtin_ia32_por: case X86::BI__builtin_ia32_por128: return Builder.CreateOr(Ops[0], Ops[1], "por"); case X86::BI__builtin_ia32_pxor: case X86::BI__builtin_ia32_pxor128: return Builder.CreateXor(Ops[0], Ops[1], "pxor"); case X86::BI__builtin_ia32_pandn: case X86::BI__builtin_ia32_pandn128: Ops[0] = Builder.CreateNot(Ops[0], "tmp"); return Builder.CreateAnd(Ops[0], Ops[1], "pandn"); case X86::BI__builtin_ia32_paddb: case X86::BI__builtin_ia32_paddb128: case X86::BI__builtin_ia32_paddd: case X86::BI__builtin_ia32_paddd128: case X86::BI__builtin_ia32_paddq: case X86::BI__builtin_ia32_paddq128: case X86::BI__builtin_ia32_paddw: case X86::BI__builtin_ia32_paddw128: case X86::BI__builtin_ia32_addps: case X86::BI__builtin_ia32_addpd: return Builder.CreateAdd(Ops[0], Ops[1], "add"); case X86::BI__builtin_ia32_psubb: case X86::BI__builtin_ia32_psubb128: case X86::BI__builtin_ia32_psubd: case X86::BI__builtin_ia32_psubd128: case X86::BI__builtin_ia32_psubq: case X86::BI__builtin_ia32_psubq128: case X86::BI__builtin_ia32_psubw: case X86::BI__builtin_ia32_psubw128: case X86::BI__builtin_ia32_subps: case X86::BI__builtin_ia32_subpd: return Builder.CreateSub(Ops[0], Ops[1], "sub"); case X86::BI__builtin_ia32_divps: return Builder.CreateFDiv(Ops[0], Ops[1], "divps"); case X86::BI__builtin_ia32_divpd: return Builder.CreateFDiv(Ops[0], Ops[1], "divpd"); case X86::BI__builtin_ia32_pmullw: case X86::BI__builtin_ia32_pmullw128: return Builder.CreateMul(Ops[0], Ops[1], "pmul"); case X86::BI__builtin_ia32_punpckhbw: return EmitShuffleVector(Ops[0], Ops[1], 4, 12, 5, 13, 6, 14, 7, 15, "punpckhbw"); case X86::BI__builtin_ia32_punpckhbw128: return EmitShuffleVector(Ops[0], Ops[1], 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31, "punpckhbw"); case X86::BI__builtin_ia32_punpckhwd: return EmitShuffleVector(Ops[0], Ops[1], 2, 6, 3, 7, "punpckhwd"); case X86::BI__builtin_ia32_punpckhwd128: return EmitShuffleVector(Ops[0], Ops[1], 4, 12, 5, 13, 6, 14, 7, 15, "punpckhwd"); case X86::BI__builtin_ia32_punpckhdq: return EmitShuffleVector(Ops[0], Ops[1], 1, 3, "punpckhdq"); case X86::BI__builtin_ia32_punpckhdq128: return EmitShuffleVector(Ops[0], Ops[1], 2, 6, 3, 7, "punpckhdq"); case X86::BI__builtin_ia32_punpckhqdq128: return EmitShuffleVector(Ops[0], Ops[1], 1, 3, "punpckhqdq"); case X86::BI__builtin_ia32_punpcklbw: return EmitShuffleVector(Ops[0], Ops[1], 0, 8, 1, 9, 2, 10, 3, 11, "punpcklbw"); case X86::BI__builtin_ia32_punpcklwd: return EmitShuffleVector(Ops[0], Ops[1], 0, 4, 1, 5, "punpcklwd"); case X86::BI__builtin_ia32_punpckldq: return EmitShuffleVector(Ops[0], Ops[1], 0, 2, "punpckldq"); case X86::BI__builtin_ia32_punpckldq128: return EmitShuffleVector(Ops[0], Ops[1], 0, 4, 1, 5, "punpckldq"); case X86::BI__builtin_ia32_punpcklqdq128: return EmitShuffleVector(Ops[0], Ops[1], 0, 2, "punpcklqdq"); case X86::BI__builtin_ia32_pslldi128: case X86::BI__builtin_ia32_psllqi128: case X86::BI__builtin_ia32_psllwi128: case X86::BI__builtin_ia32_psradi128: case X86::BI__builtin_ia32_psrawi128: case X86::BI__builtin_ia32_psrldi128: case X86::BI__builtin_ia32_psrlqi128: case X86::BI__builtin_ia32_psrlwi128: { Ops[1] = Builder.CreateZExt(Ops[1], llvm::Type::Int64Ty, "zext"); const llvm::Type *Ty = llvm::VectorType::get(llvm::Type::Int64Ty, 2); llvm::Value *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0); Ops[1] = Builder.CreateInsertElement(llvm::UndefValue::get(Ty), Ops[1], Zero, "insert"); Ops[1] = Builder.CreateBitCast(Ops[1], Ops[0]->getType(), "bitcast"); const char *name = 0; Intrinsic::ID ID = Intrinsic::not_intrinsic; switch (BuiltinID) { default: assert(0 && "Unsupported shift intrinsic!"); case X86::BI__builtin_ia32_pslldi128: name = "pslldi"; ID = Intrinsic::x86_sse2_psll_d; break; case X86::BI__builtin_ia32_psllqi128: name = "psllqi"; ID = Intrinsic::x86_sse2_psll_q; break; case X86::BI__builtin_ia32_psllwi128: name = "psllwi"; ID = Intrinsic::x86_sse2_psll_w; break; case X86::BI__builtin_ia32_psradi128: name = "psradi"; ID = Intrinsic::x86_sse2_psra_d; break; case X86::BI__builtin_ia32_psrawi128: name = "psrawi"; ID = Intrinsic::x86_sse2_psra_w; break; case X86::BI__builtin_ia32_psrldi128: name = "psrldi"; ID = Intrinsic::x86_sse2_psrl_d; break; case X86::BI__builtin_ia32_psrlqi128: name = "psrlqi"; ID = Intrinsic::x86_sse2_psrl_q; break; case X86::BI__builtin_ia32_psrlwi128: name = "psrlwi"; ID = Intrinsic::x86_sse2_psrl_w; break; } llvm::Function *F = CGM.getIntrinsic(ID); return Builder.CreateCall(F, &Ops[0], &Ops[0] + Ops.size(), name); } case X86::BI__builtin_ia32_pslldi: case X86::BI__builtin_ia32_psllqi: case X86::BI__builtin_ia32_psllwi: case X86::BI__builtin_ia32_psradi: case X86::BI__builtin_ia32_psrawi: case X86::BI__builtin_ia32_psrldi: case X86::BI__builtin_ia32_psrlqi: case X86::BI__builtin_ia32_psrlwi: { Ops[1] = Builder.CreateZExt(Ops[1], llvm::Type::Int64Ty, "zext"); const llvm::Type *Ty = llvm::VectorType::get(llvm::Type::Int64Ty, 1); Ops[1] = Builder.CreateBitCast(Ops[1], Ty, "bitcast"); const char *name = 0; Intrinsic::ID ID = Intrinsic::not_intrinsic; switch (BuiltinID) { default: assert(0 && "Unsupported shift intrinsic!"); case X86::BI__builtin_ia32_pslldi: name = "pslldi"; ID = Intrinsic::x86_mmx_psll_d; break; case X86::BI__builtin_ia32_psllqi: name = "psllqi"; ID = Intrinsic::x86_mmx_psll_q; break; case X86::BI__builtin_ia32_psllwi: name = "psllwi"; ID = Intrinsic::x86_mmx_psll_w; break; case X86::BI__builtin_ia32_psradi: name = "psradi"; ID = Intrinsic::x86_mmx_psra_d; break; case X86::BI__builtin_ia32_psrawi: name = "psrawi"; ID = Intrinsic::x86_mmx_psra_w; break; case X86::BI__builtin_ia32_psrldi: name = "psrldi"; ID = Intrinsic::x86_mmx_psrl_d; break; case X86::BI__builtin_ia32_psrlqi: name = "psrlqi"; ID = Intrinsic::x86_mmx_psrl_q; break; case X86::BI__builtin_ia32_psrlwi: name = "psrlwi"; ID = Intrinsic::x86_mmx_psrl_w; break; } llvm::Function *F = CGM.getIntrinsic(ID); return Builder.CreateCall(F, &Ops[0], &Ops[0] + Ops.size(), name); } case X86::BI__builtin_ia32_pshufw: { unsigned i = cast<ConstantInt>(Ops[1])->getZExtValue(); return EmitShuffleVector(Ops[0], Ops[0], i & 0x3, (i & 0xc) >> 2, (i & 0x30) >> 4, (i & 0xc0) >> 6, "pshufw"); } case X86::BI__builtin_ia32_pshuflw: { unsigned i = cast<ConstantInt>(Ops[1])->getZExtValue(); return EmitShuffleVector(Ops[0], Ops[0], i & 0x3, (i & 0xc) >> 2, (i & 0x30) >> 4, (i & 0xc0) >> 6, 4, 5, 6, 7, "pshuflw"); } case X86::BI__builtin_ia32_pshufhw: { unsigned i = cast<ConstantInt>(Ops[1])->getZExtValue(); return EmitShuffleVector(Ops[0], Ops[0], 0, 1, 2, 3, 4 + (i & 0x3), 4 + ((i & 0xc) >> 2), 4 + ((i & 0x30) >> 4), 4 + ((i & 0xc0) >> 6), "pshufhw"); } case X86::BI__builtin_ia32_pshufd: { unsigned i = cast<ConstantInt>(Ops[1])->getZExtValue(); return EmitShuffleVector(Ops[0], Ops[0], i & 0x3, (i & 0xc) >> 2, (i & 0x30) >> 4, (i & 0xc0) >> 6, "pshufd"); } case X86::BI__builtin_ia32_vec_init_v4hi: case X86::BI__builtin_ia32_vec_init_v8qi: case X86::BI__builtin_ia32_vec_init_v2si: return EmitVector(&Ops[0], Ops.size()); case X86::BI__builtin_ia32_vec_ext_v2si: case X86::BI__builtin_ia32_vec_ext_v2di: case X86::BI__builtin_ia32_vec_ext_v4sf: case X86::BI__builtin_ia32_vec_ext_v4si: case X86::BI__builtin_ia32_vec_ext_v8hi: case X86::BI__builtin_ia32_vec_ext_v4hi: case X86::BI__builtin_ia32_vec_ext_v2df: return Builder.CreateExtractElement(Ops[0], Ops[1], "result"); case X86::BI__builtin_ia32_cmpordss: case X86::BI__builtin_ia32_cmpordsd: case X86::BI__builtin_ia32_cmpunordss: case X86::BI__builtin_ia32_cmpunordsd: case X86::BI__builtin_ia32_cmpeqss: case X86::BI__builtin_ia32_cmpeqsd: case X86::BI__builtin_ia32_cmpltss: case X86::BI__builtin_ia32_cmpltsd: case X86::BI__builtin_ia32_cmpless: case X86::BI__builtin_ia32_cmplesd: case X86::BI__builtin_ia32_cmpneqss: case X86::BI__builtin_ia32_cmpneqsd: case X86::BI__builtin_ia32_cmpnltss: case X86::BI__builtin_ia32_cmpnltsd: case X86::BI__builtin_ia32_cmpnless: case X86::BI__builtin_ia32_cmpnlesd: { unsigned i = 0; const char *name = 0; switch (BuiltinID) { default: assert(0 && "Unknown compare builtin!"); case X86::BI__builtin_ia32_cmpeqss: case X86::BI__builtin_ia32_cmpeqsd: i = 0; name = "cmpeq"; break; case X86::BI__builtin_ia32_cmpltss: case X86::BI__builtin_ia32_cmpltsd: i = 1; name = "cmplt"; break; case X86::BI__builtin_ia32_cmpless: case X86::BI__builtin_ia32_cmplesd: i = 2; name = "cmple"; break; case X86::BI__builtin_ia32_cmpunordss: case X86::BI__builtin_ia32_cmpunordsd: i = 3; name = "cmpunord"; break; case X86::BI__builtin_ia32_cmpneqss: case X86::BI__builtin_ia32_cmpneqsd: i = 4; name = "cmpneq"; break; case X86::BI__builtin_ia32_cmpnltss: case X86::BI__builtin_ia32_cmpnltsd: i = 5; name = "cmpntl"; break; case X86::BI__builtin_ia32_cmpnless: case X86::BI__builtin_ia32_cmpnlesd: i = 6; name = "cmpnle"; break; case X86::BI__builtin_ia32_cmpordss: case X86::BI__builtin_ia32_cmpordsd: i = 7; name = "cmpord"; break; } llvm::Function *F; if (cast<llvm::VectorType>(Ops[0]->getType())->getElementType() == llvm::Type::FloatTy) F = CGM.getIntrinsic(Intrinsic::x86_sse_cmp_ss); else F = CGM.getIntrinsic(Intrinsic::x86_sse2_cmp_sd); Ops.push_back(llvm::ConstantInt::get(llvm::Type::Int8Ty, i)); return Builder.CreateCall(F, &Ops[0], &Ops[0] + Ops.size(), name); } case X86::BI__builtin_ia32_ldmxcsr: { llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); Value *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1); Value *Tmp = Builder.CreateAlloca(llvm::Type::Int32Ty, One, "tmp"); Builder.CreateStore(Ops[0], Tmp); return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse_ldmxcsr), Builder.CreateBitCast(Tmp, PtrTy)); } case X86::BI__builtin_ia32_stmxcsr: { llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); Value *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1); Value *Tmp = Builder.CreateAlloca(llvm::Type::Int32Ty, One, "tmp"); One = Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse_stmxcsr), Builder.CreateBitCast(Tmp, PtrTy)); return Builder.CreateLoad(Tmp, "stmxcsr"); } case X86::BI__builtin_ia32_cmpordps: case X86::BI__builtin_ia32_cmpordpd: case X86::BI__builtin_ia32_cmpunordps: case X86::BI__builtin_ia32_cmpunordpd: case X86::BI__builtin_ia32_cmpeqps: case X86::BI__builtin_ia32_cmpeqpd: case X86::BI__builtin_ia32_cmpltps: case X86::BI__builtin_ia32_cmpltpd: case X86::BI__builtin_ia32_cmpleps: case X86::BI__builtin_ia32_cmplepd: case X86::BI__builtin_ia32_cmpneqps: case X86::BI__builtin_ia32_cmpneqpd: case X86::BI__builtin_ia32_cmpngtps: case X86::BI__builtin_ia32_cmpngtpd: case X86::BI__builtin_ia32_cmpnltps: case X86::BI__builtin_ia32_cmpnltpd: case X86::BI__builtin_ia32_cmpgtps: case X86::BI__builtin_ia32_cmpgtpd: case X86::BI__builtin_ia32_cmpgeps: case X86::BI__builtin_ia32_cmpgepd: case X86::BI__builtin_ia32_cmpngeps: case X86::BI__builtin_ia32_cmpngepd: case X86::BI__builtin_ia32_cmpnleps: case X86::BI__builtin_ia32_cmpnlepd: { unsigned i = 0; const char *name = 0; bool ShouldSwap = false; switch (BuiltinID) { default: assert(0 && "Unknown compare builtin!"); case X86::BI__builtin_ia32_cmpeqps: case X86::BI__builtin_ia32_cmpeqpd: i = 0; name = "cmpeq"; break; case X86::BI__builtin_ia32_cmpltps: case X86::BI__builtin_ia32_cmpltpd: i = 1; name = "cmplt"; break; case X86::BI__builtin_ia32_cmpleps: case X86::BI__builtin_ia32_cmplepd: i = 2; name = "cmple"; break; case X86::BI__builtin_ia32_cmpunordps: case X86::BI__builtin_ia32_cmpunordpd: i = 3; name = "cmpunord"; break; case X86::BI__builtin_ia32_cmpneqps: case X86::BI__builtin_ia32_cmpneqpd: i = 4; name = "cmpneq"; break; case X86::BI__builtin_ia32_cmpnltps: case X86::BI__builtin_ia32_cmpnltpd: i = 5; name = "cmpntl"; break; case X86::BI__builtin_ia32_cmpnleps: case X86::BI__builtin_ia32_cmpnlepd: i = 6; name = "cmpnle"; break; case X86::BI__builtin_ia32_cmpordps: case X86::BI__builtin_ia32_cmpordpd: i = 7; name = "cmpord"; break; case X86::BI__builtin_ia32_cmpgtps: case X86::BI__builtin_ia32_cmpgtpd: ShouldSwap = true; i = 1; name = "cmpgt"; break; case X86::BI__builtin_ia32_cmpgeps: case X86::BI__builtin_ia32_cmpgepd: i = 2; name = "cmpge"; ShouldSwap = true; break; case X86::BI__builtin_ia32_cmpngtps: case X86::BI__builtin_ia32_cmpngtpd: i = 5; name = "cmpngt"; ShouldSwap = true; break; case X86::BI__builtin_ia32_cmpngeps: case X86::BI__builtin_ia32_cmpngepd: i = 6; name = "cmpnge"; ShouldSwap = true; break; } if (ShouldSwap) std::swap(Ops[0], Ops[1]); llvm::Function *F; if (cast<llvm::VectorType>(Ops[0]->getType())->getElementType() == llvm::Type::FloatTy) F = CGM.getIntrinsic(Intrinsic::x86_sse_cmp_ps); else F = CGM.getIntrinsic(Intrinsic::x86_sse2_cmp_pd); Ops.push_back(llvm::ConstantInt::get(llvm::Type::Int8Ty, i)); return Builder.CreateCall(F, &Ops[0], &Ops[0] + Ops.size(), name); } case X86::BI__builtin_ia32_movss: return EmitShuffleVector(Ops[0], Ops[1], 4, 1, 2, 3, "movss"); case X86::BI__builtin_ia32_shufps: { unsigned i = cast<ConstantInt>(Ops[2])->getZExtValue(); return EmitShuffleVector(Ops[0], Ops[1], i & 0x3, (i & 0xc) >> 2, ((i & 0x30) >> 4) + 4, ((i & 0xc0) >> 6) + 4, "shufps"); } case X86::BI__builtin_ia32_shufpd: { unsigned i = cast<ConstantInt>(Ops[2])->getZExtValue(); return EmitShuffleVector(Ops[0], Ops[1], i & 1, (i & 2) + 2, "shufpd"); } case X86::BI__builtin_ia32_punpcklbw128: return EmitShuffleVector(Ops[0], Ops[1], 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23, "punpcklbw"); case X86::BI__builtin_ia32_punpcklwd128: return EmitShuffleVector(Ops[0], Ops[1], 0, 8, 1, 9, 2, 10, 3, 11, "punpcklwd"); case X86::BI__builtin_ia32_movlhps: return EmitShuffleVector(Ops[0], Ops[1], 0, 1, 4, 5, "movlhps"); case X86::BI__builtin_ia32_movhlps: return EmitShuffleVector(Ops[0], Ops[1], 6, 7, 2, 3, "movhlps"); case X86::BI__builtin_ia32_unpckhps: return EmitShuffleVector(Ops[0], Ops[1], 2, 6, 3, 7, "unpckhps"); case X86::BI__builtin_ia32_unpcklps: return EmitShuffleVector(Ops[0], Ops[1], 0, 4, 1, 5, "unpcklps"); case X86::BI__builtin_ia32_unpckhpd: return EmitShuffleVector(Ops[0], Ops[1], 1, 3, "unpckhpd"); case X86::BI__builtin_ia32_unpcklpd: return EmitShuffleVector(Ops[0], Ops[1], 0, 2, "unpcklpd"); case X86::BI__builtin_ia32_movsd: return EmitShuffleVector(Ops[0], Ops[1], 2, 1, "movsd"); case X86::BI__builtin_ia32_movqv4si: { llvm::Type *Ty = llvm::VectorType::get(llvm::Type::Int64Ty, 2); return Builder.CreateBitCast(Ops[0], Ty); } case X86::BI__builtin_ia32_loadlps: case X86::BI__builtin_ia32_loadhps: { // FIXME: This should probably be represented as // shuffle (dst, (v4f32 (insert undef, (load i64), 0)), shuf mask hi/lo) const llvm::Type *EltTy = llvm::Type::DoubleTy; const llvm::Type *VecTy = llvm::VectorType::get(EltTy, 2); const llvm::Type *OrigTy = Ops[0]->getType(); unsigned Index = BuiltinID == X86::BI__builtin_ia32_loadlps ? 0 : 1; llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Index); Ops[1] = Builder.CreateBitCast(Ops[1], llvm::PointerType::getUnqual(EltTy)); Ops[1] = Builder.CreateLoad(Ops[1], "tmp"); Ops[0] = Builder.CreateBitCast(Ops[0], VecTy, "cast"); Ops[0] = Builder.CreateInsertElement(Ops[0], Ops[1], Idx, "loadps"); return Builder.CreateBitCast(Ops[0], OrigTy, "loadps"); } case X86::BI__builtin_ia32_loadlpd: case X86::BI__builtin_ia32_loadhpd: { Ops[1] = Builder.CreateLoad(Ops[1], "tmp"); unsigned Index = BuiltinID == X86::BI__builtin_ia32_loadlpd ? 0 : 1; llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Index); return Builder.CreateInsertElement(Ops[0], Ops[1], Idx, "loadpd"); } case X86::BI__builtin_ia32_storehps: case X86::BI__builtin_ia32_storelps: { const llvm::Type *EltTy = llvm::Type::Int64Ty; llvm::Type *PtrTy = llvm::PointerType::getUnqual(EltTy); llvm::Type *VecTy = llvm::VectorType::get(EltTy, 2); // cast val v2i64 Ops[1] = Builder.CreateBitCast(Ops[1], VecTy, "cast"); // extract (0, 1) unsigned Index = BuiltinID == X86::BI__builtin_ia32_storelps ? 0 : 1; llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Index); Ops[1] = Builder.CreateExtractElement(Ops[1], Idx, "extract"); // cast pointer to i64 & store Ops[0] = Builder.CreateBitCast(Ops[0], PtrTy); return Builder.CreateStore(Ops[1], Ops[0]); } case X86::BI__builtin_ia32_loadlv4si: { // load i64 const llvm::Type *EltTy = llvm::Type::Int64Ty; llvm::Type *PtrTy = llvm::PointerType::getUnqual(EltTy); Ops[0] = Builder.CreateBitCast(Ops[0], PtrTy); Ops[0] = Builder.CreateLoad(Ops[0], "load"); // scalar to vector: insert i64 into 2 x i64 undef llvm::Type *VecTy = llvm::VectorType::get(EltTy, 2); llvm::Value *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0); Ops[0] = Builder.CreateInsertElement(llvm::UndefValue::get(VecTy), Ops[0], Zero, "s2v"); // shuffle into zero vector. std::vector<llvm::Constant *>Elts; Elts.resize(2, llvm::ConstantInt::get(EltTy, 0)); llvm::Value *ZV = ConstantVector::get(Elts); Ops[0] = EmitShuffleVector(ZV, Ops[0], 2, 1, "loadl"); // bitcast to result. return Builder.CreateBitCast(Ops[0], llvm::VectorType::get(llvm::Type::Int32Ty, 4)); } case X86::BI__builtin_ia32_vec_set_v4hi: case X86::BI__builtin_ia32_vec_set_v8hi: return Builder.CreateInsertElement(Ops[0], Ops[1], Ops[2], "pinsrw"); case X86::BI__builtin_ia32_vec_set_v4si: return Builder.CreateInsertElement(Ops[0], Ops[1], Ops[2], "pinsrd"); case X86::BI__builtin_ia32_vec_set_v2di: return Builder.CreateInsertElement(Ops[0], Ops[1], Ops[2], "pinsrq"); case X86::BI__builtin_ia32_andps: case X86::BI__builtin_ia32_andpd: case X86::BI__builtin_ia32_andnps: case X86::BI__builtin_ia32_andnpd: case X86::BI__builtin_ia32_orps: case X86::BI__builtin_ia32_orpd: case X86::BI__builtin_ia32_xorpd: case X86::BI__builtin_ia32_xorps: { const llvm::Type *ITy = llvm::VectorType::get(llvm::Type::Int32Ty, 4); const llvm::Type *FTy = Ops[0]->getType(); Ops[0] = Builder.CreateBitCast(Ops[0], ITy, "bitcast"); Ops[1] = Builder.CreateBitCast(Ops[1], ITy, "bitcast"); switch (BuiltinID) { case X86::BI__builtin_ia32_andps: Ops[0] = Builder.CreateAnd(Ops[0], Ops[1], "andps"); break; case X86::BI__builtin_ia32_andpd: Ops[0] = Builder.CreateAnd(Ops[0], Ops[1], "andpd"); break; case X86::BI__builtin_ia32_andnps: Ops[0] = Builder.CreateNot(Ops[0], "not"); Ops[0] = Builder.CreateAnd(Ops[0], Ops[1], "andnps"); break; case X86::BI__builtin_ia32_andnpd: Ops[0] = Builder.CreateNot(Ops[0], "not"); Ops[0] = Builder.CreateAnd(Ops[0], Ops[1], "andnpd"); break; case X86::BI__builtin_ia32_orps: Ops[0] = Builder.CreateOr(Ops[0], Ops[1], "orps"); break; case X86::BI__builtin_ia32_orpd: Ops[0] = Builder.CreateOr(Ops[0], Ops[1], "orpd"); break; case X86::BI__builtin_ia32_xorps: Ops[0] = Builder.CreateXor(Ops[0], Ops[1], "xorps"); break; case X86::BI__builtin_ia32_xorpd: Ops[0] = Builder.CreateXor(Ops[0], Ops[1], "xorpd"); break; } return Builder.CreateBitCast(Ops[0], FTy, "bitcast"); } } } Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E) { switch (BuiltinID) { default: return 0; } } <file_sep>/test/SemaTemplate/instantiate-field.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T> struct X { int x; T y; // expected-error{{data member instantiated with function type}} T* z; T bitfield : 12; // expected-error{{bit-field 'bitfield' has non-integral type 'float'}} \ // expected-error{{data member instantiated with function type}} mutable T x2; // expected-error{{data member instantiated with function type}} }; void test1(const X<int> *xi) { int i1 = xi->x; const int &i2 = xi->y; int* ip1 = xi->z; int i3 = xi->bitfield; xi->x2 = 17; } void test2(const X<float> *xf) { (void)xf->x; // expected-note{{in instantiation of template class 'struct X<float>' requested here}} } void test3(const X<int(int)> *xf) { (void)xf->x; // expected-note{{in instantiation of template class 'struct X<int (int)>' requested here}} } <file_sep>/test/Analysis/rdar-6541136.c // RUN: clang-cc -verify -analyze -checker-cfref -analyzer-store=basic %s struct tea_cheese { unsigned magic; }; typedef struct tea_cheese kernel_tea_cheese_t; extern kernel_tea_cheese_t _wonky_gesticulate_cheese; // This test case exercises the ElementRegion::getRValueType() logic. // All it tests is that it does not crash or do anything weird. // The out-of-bounds-access on line 19 is caught using the region store variant. void foo( void ) { kernel_tea_cheese_t *wonky = &_wonky_gesticulate_cheese; struct load_wine *cmd = (void*) &wonky[1]; cmd = cmd; char *p = (void*) &wonky[1]; *p = 1; kernel_tea_cheese_t *q = &wonky[1]; kernel_tea_cheese_t r = *q; // no-warning } <file_sep>/lib/CodeGen/CGObjCMac.cpp //===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This provides Objective-C code generation targetting the Apple runtime. // //===----------------------------------------------------------------------===// #include "CGObjCRuntime.h" #include "CodeGenModule.h" #include "CodeGenFunction.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/Basic/LangOptions.h" #include "llvm/Intrinsics.h" #include "llvm/Module.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Target/TargetData.h" #include <sstream> using namespace clang; using namespace CodeGen; namespace { typedef std::vector<llvm::Constant*> ConstantVector; // FIXME: We should find a nicer way to make the labels for // metadata, string concatenation is lame. class ObjCCommonTypesHelper { protected: CodeGen::CodeGenModule &CGM; public: const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy; const llvm::Type *Int8PtrTy; /// ObjectPtrTy - LLVM type for object handles (typeof(id)) const llvm::Type *ObjectPtrTy; /// PtrObjectPtrTy - LLVM type for id * const llvm::Type *PtrObjectPtrTy; /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) const llvm::Type *SelectorPtrTy; /// ProtocolPtrTy - LLVM type for external protocol handles /// (typeof(Protocol)) const llvm::Type *ExternalProtocolPtrTy; // SuperCTy - clang type for struct objc_super. QualType SuperCTy; // SuperPtrCTy - clang type for struct objc_super *. QualType SuperPtrCTy; /// SuperTy - LLVM type for struct objc_super. const llvm::StructType *SuperTy; /// SuperPtrTy - LLVM type for struct objc_super *. const llvm::Type *SuperPtrTy; /// PropertyTy - LLVM type for struct objc_property (struct _prop_t /// in GCC parlance). const llvm::StructType *PropertyTy; /// PropertyListTy - LLVM type for struct objc_property_list /// (_prop_list_t in GCC parlance). const llvm::StructType *PropertyListTy; /// PropertyListPtrTy - LLVM type for struct objc_property_list*. const llvm::Type *PropertyListPtrTy; // MethodTy - LLVM type for struct objc_method. const llvm::StructType *MethodTy; /// CacheTy - LLVM type for struct objc_cache. const llvm::Type *CacheTy; /// CachePtrTy - LLVM type for struct objc_cache *. const llvm::Type *CachePtrTy; llvm::Constant *GetPropertyFn, *SetPropertyFn; llvm::Constant *EnumerationMutationFn; /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function. llvm::Constant *GcReadWeakFn; /// GcAssignWeakFn -- LLVM objc_assign_weak function. llvm::Constant *GcAssignWeakFn; /// GcAssignGlobalFn -- LLVM objc_assign_global function. llvm::Constant *GcAssignGlobalFn; /// GcAssignIvarFn -- LLVM objc_assign_ivar function. llvm::Constant *GcAssignIvarFn; /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function. llvm::Constant *GcAssignStrongCastFn; /// ExceptionThrowFn - LLVM objc_exception_throw function. llvm::Constant *ExceptionThrowFn; /// SyncEnterFn - LLVM object_sync_enter function. llvm::Constant *getSyncEnterFn() { // void objc_sync_enter (id) std::vector<const llvm::Type*> Args(1, ObjectPtrTy); llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); } /// SyncExitFn - LLVM object_sync_exit function. llvm::Constant *SyncExitFn; ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm); ~ObjCCommonTypesHelper(){} }; /// ObjCTypesHelper - Helper class that encapsulates lazy /// construction of varies types used during ObjC generation. class ObjCTypesHelper : public ObjCCommonTypesHelper { private: llvm::Constant *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn; llvm::Constant *MessageSendSuperFn, *MessageSendSuperStretFn, *MessageSendSuperFpretFn; public: /// SymtabTy - LLVM type for struct objc_symtab. const llvm::StructType *SymtabTy; /// SymtabPtrTy - LLVM type for struct objc_symtab *. const llvm::Type *SymtabPtrTy; /// ModuleTy - LLVM type for struct objc_module. const llvm::StructType *ModuleTy; /// ProtocolTy - LLVM type for struct objc_protocol. const llvm::StructType *ProtocolTy; /// ProtocolPtrTy - LLVM type for struct objc_protocol *. const llvm::Type *ProtocolPtrTy; /// ProtocolExtensionTy - LLVM type for struct /// objc_protocol_extension. const llvm::StructType *ProtocolExtensionTy; /// ProtocolExtensionTy - LLVM type for struct /// objc_protocol_extension *. const llvm::Type *ProtocolExtensionPtrTy; /// MethodDescriptionTy - LLVM type for struct /// objc_method_description. const llvm::StructType *MethodDescriptionTy; /// MethodDescriptionListTy - LLVM type for struct /// objc_method_description_list. const llvm::StructType *MethodDescriptionListTy; /// MethodDescriptionListPtrTy - LLVM type for struct /// objc_method_description_list *. const llvm::Type *MethodDescriptionListPtrTy; /// ProtocolListTy - LLVM type for struct objc_property_list. const llvm::Type *ProtocolListTy; /// ProtocolListPtrTy - LLVM type for struct objc_property_list*. const llvm::Type *ProtocolListPtrTy; /// CategoryTy - LLVM type for struct objc_category. const llvm::StructType *CategoryTy; /// ClassTy - LLVM type for struct objc_class. const llvm::StructType *ClassTy; /// ClassPtrTy - LLVM type for struct objc_class *. const llvm::Type *ClassPtrTy; /// ClassExtensionTy - LLVM type for struct objc_class_ext. const llvm::StructType *ClassExtensionTy; /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *. const llvm::Type *ClassExtensionPtrTy; // IvarTy - LLVM type for struct objc_ivar. const llvm::StructType *IvarTy; /// IvarListTy - LLVM type for struct objc_ivar_list. const llvm::Type *IvarListTy; /// IvarListPtrTy - LLVM type for struct objc_ivar_list *. const llvm::Type *IvarListPtrTy; /// MethodListTy - LLVM type for struct objc_method_list. const llvm::Type *MethodListTy; /// MethodListPtrTy - LLVM type for struct objc_method_list *. const llvm::Type *MethodListPtrTy; /// ExceptionDataTy - LLVM type for struct _objc_exception_data. const llvm::Type *ExceptionDataTy; /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. llvm::Constant *ExceptionTryEnterFn; /// ExceptionTryExitFn - LLVM objc_exception_try_exit function. llvm::Constant *ExceptionTryExitFn; /// ExceptionExtractFn - LLVM objc_exception_extract function. llvm::Constant *ExceptionExtractFn; /// ExceptionMatchFn - LLVM objc_exception_match function. llvm::Constant *ExceptionMatchFn; /// SetJmpFn - LLVM _setjmp function. llvm::Constant *SetJmpFn; public: ObjCTypesHelper(CodeGen::CodeGenModule &cgm); ~ObjCTypesHelper() {} llvm::Constant *getSendFn(bool IsSuper) { return IsSuper ? MessageSendSuperFn : MessageSendFn; } llvm::Constant *getSendStretFn(bool IsSuper) { return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn; } llvm::Constant *getSendFpretFn(bool IsSuper) { return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn; } }; /// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's /// modern abi class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper { public: llvm::Constant *MessageSendFixupFn, *MessageSendFpretFixupFn, *MessageSendStretFixupFn, *MessageSendIdFixupFn, *MessageSendIdStretFixupFn, *MessageSendSuper2FixupFn, *MessageSendSuper2StretFixupFn; // MethodListnfABITy - LLVM for struct _method_list_t const llvm::StructType *MethodListnfABITy; // MethodListnfABIPtrTy - LLVM for struct _method_list_t* const llvm::Type *MethodListnfABIPtrTy; // ProtocolnfABITy = LLVM for struct _protocol_t const llvm::StructType *ProtocolnfABITy; // ProtocolnfABIPtrTy = LLVM for struct _protocol_t* const llvm::Type *ProtocolnfABIPtrTy; // ProtocolListnfABITy - LLVM for struct _objc_protocol_list const llvm::StructType *ProtocolListnfABITy; // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list* const llvm::Type *ProtocolListnfABIPtrTy; // ClassnfABITy - LLVM for struct _class_t const llvm::StructType *ClassnfABITy; // ClassnfABIPtrTy - LLVM for struct _class_t* const llvm::Type *ClassnfABIPtrTy; // IvarnfABITy - LLVM for struct _ivar_t const llvm::StructType *IvarnfABITy; // IvarListnfABITy - LLVM for struct _ivar_list_t const llvm::StructType *IvarListnfABITy; // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t* const llvm::Type *IvarListnfABIPtrTy; // ClassRonfABITy - LLVM for struct _class_ro_t const llvm::StructType *ClassRonfABITy; // ImpnfABITy - LLVM for id (*)(id, SEL, ...) const llvm::Type *ImpnfABITy; // CategorynfABITy - LLVM for struct _category_t const llvm::StructType *CategorynfABITy; // New types for nonfragile abi messaging. // MessageRefTy - LLVM for: // struct _message_ref_t { // IMP messenger; // SEL name; // }; const llvm::StructType *MessageRefTy; // MessageRefCTy - clang type for struct _message_ref_t QualType MessageRefCTy; // MessageRefPtrTy - LLVM for struct _message_ref_t* const llvm::Type *MessageRefPtrTy; // MessageRefCPtrTy - clang type for struct _message_ref_t* QualType MessageRefCPtrTy; // MessengerTy - Type of the messenger (shown as IMP above) const llvm::FunctionType *MessengerTy; // SuperMessageRefTy - LLVM for: // struct _super_message_ref_t { // SUPER_IMP messenger; // SEL name; // }; const llvm::StructType *SuperMessageRefTy; // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* const llvm::Type *SuperMessageRefPtrTy; /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C /// exception personality function. llvm::Value *getEHPersonalityPtr() { llvm::Constant *Personality = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, std::vector<const llvm::Type*>(), true), "__objc_personality_v0"); return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy); } llvm::Constant *UnwindResumeOrRethrowFn, *ObjCBeginCatchFn, *ObjCEndCatchFn; const llvm::StructType *EHTypeTy; const llvm::Type *EHTypePtrTy; ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); ~ObjCNonFragileABITypesHelper(){} }; class CGObjCCommonMac : public CodeGen::CGObjCRuntime { public: // FIXME - accessibility class GC_IVAR { public: unsigned int ivar_bytepos; unsigned int ivar_size; GC_IVAR() : ivar_bytepos(0), ivar_size(0) {} }; class SKIP_SCAN { public: unsigned int skip; unsigned int scan; SKIP_SCAN() : skip(0), scan(0) {} }; protected: CodeGen::CodeGenModule &CGM; // FIXME! May not be needing this after all. unsigned ObjCABI; // gc ivar layout bitmap calculation helper caches. llvm::SmallVector<GC_IVAR, 16> SkipIvars; llvm::SmallVector<GC_IVAR, 16> IvarsInfo; llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars; /// LazySymbols - Symbols to generate a lazy reference for. See /// DefinedSymbols and FinishModule(). std::set<IdentifierInfo*> LazySymbols; /// DefinedSymbols - External symbols which are defined by this /// module. The symbols in this list and LazySymbols are used to add /// special linker symbols which ensure that Objective-C modules are /// linked properly. std::set<IdentifierInfo*> DefinedSymbols; /// ClassNames - uniqued class names. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames; /// MethodVarNames - uniqued method variable names. llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames; /// MethodVarTypes - uniqued method type signatures. We have to use /// a StringMap here because have no other unique reference. llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes; /// MethodDefinitions - map of methods which have been defined in /// this translation unit. llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions; /// PropertyNames - uniqued method variable names. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames; /// ClassReferences - uniqued class references. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences; /// SelectorReferences - uniqued selector references. llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences; /// Protocols - Protocols for which an objc_protocol structure has /// been emitted. Forward declarations are handled by creating an /// empty structure whose initializer is filled in when/if defined. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols; /// DefinedProtocols - Protocols which have actually been /// defined. We should not need this, see FIXME in GenerateProtocol. llvm::DenseSet<IdentifierInfo*> DefinedProtocols; /// DefinedClasses - List of defined classes. std::vector<llvm::GlobalValue*> DefinedClasses; /// DefinedCategories - List of defined categories. std::vector<llvm::GlobalValue*> DefinedCategories; /// UsedGlobals - List of globals to pack into the llvm.used metadata /// to prevent them from being clobbered. std::vector<llvm::GlobalVariable*> UsedGlobals; /// GetNameForMethod - Return a name for the given method. /// \param[out] NameOut - The return value. void GetNameForMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD, std::string &NameOut); /// GetMethodVarName - Return a unique constant for the given /// selector's name. The return value has type char *. llvm::Constant *GetMethodVarName(Selector Sel); llvm::Constant *GetMethodVarName(IdentifierInfo *Ident); llvm::Constant *GetMethodVarName(const std::string &Name); /// GetMethodVarType - Return a unique constant for the given /// selector's name. The return value has type char *. // FIXME: This is a horrible name. llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D); llvm::Constant *GetMethodVarType(FieldDecl *D); /// GetPropertyName - Return a unique constant for the given /// name. The return value has type char *. llvm::Constant *GetPropertyName(IdentifierInfo *Ident); // FIXME: This can be dropped once string functions are unified. llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD, const Decl *Container); /// GetClassName - Return a unique constant for the given selector's /// name. The return value has type char *. llvm::Constant *GetClassName(IdentifierInfo *Ident); /// GetInterfaceDeclStructLayout - Get layout for ivars of given /// interface declaration. const llvm::StructLayout *GetInterfaceDeclStructLayout( const ObjCInterfaceDecl *ID) const; /// BuildIvarLayout - Builds ivar layout bitmap for the class /// implementation for the __strong or __weak case. /// llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI, bool ForStrongLayout); void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI, const llvm::StructLayout *Layout, const RecordDecl *RD, const llvm::SmallVectorImpl<FieldDecl*> &RecFields, unsigned int BytePos, bool ForStrongLayout, int &Index, int &SkIndex, bool &HasUnion); /// GetIvarLayoutName - Returns a unique constant for the given /// ivar layout bitmap. llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident, const ObjCCommonTypesHelper &ObjCTypes); const RecordDecl *GetFirstIvarInRecord(const ObjCInterfaceDecl *OID, RecordDecl::field_iterator &FIV, RecordDecl::field_iterator &PIV); /// EmitPropertyList - Emit the given property list. The return /// value has type PropertyListPtrTy. llvm::Constant *EmitPropertyList(const std::string &Name, const Decl *Container, const ObjCContainerDecl *OCD, const ObjCCommonTypesHelper &ObjCTypes); /// GetProtocolRef - Return a reference to the internal protocol /// description, creating an empty one if it has not been /// defined. The return value has type ProtocolPtrTy. llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD); /// GetIvarBaseOffset - returns ivars byte offset. uint64_t GetIvarBaseOffset(const llvm::StructLayout *Layout, const FieldDecl *Field); /// GetFieldBaseOffset - return's field byte offset. uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI, const llvm::StructLayout *Layout, const FieldDecl *Field); /// CreateMetadataVar - Create a global variable with internal /// linkage for use by the Objective-C runtime. /// /// This is a convenience wrapper which not only creates the /// variable, but also sets the section and alignment and adds the /// global to the UsedGlobals list. /// /// \param Name - The variable name. /// \param Init - The variable initializer; this is also used to /// define the type of the variable. /// \param Section - The section the variable should go into, or 0. /// \param Align - The alignment for the variable, or 0. /// \param AddToUsed - Whether the variable should be added to /// "llvm.used". llvm::GlobalVariable *CreateMetadataVar(const std::string &Name, llvm::Constant *Init, const char *Section, unsigned Align, bool AddToUsed); public: CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm) { } virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL); virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD=0); virtual void GenerateProtocol(const ObjCProtocolDecl *PD); /// GetOrEmitProtocol - Get the protocol object for the given /// declaration, emitting it if necessary. The return value has type /// ProtocolPtrTy. virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0; /// GetOrEmitProtocolRef - Get a forward reference to the protocol /// object for the given declaration, emitting it if needed. These /// forward references will be filled in with empty bodies if no /// definition is seen. The return value has type ProtocolPtrTy. virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0; }; class CGObjCMac : public CGObjCCommonMac { private: ObjCTypesHelper ObjCTypes; /// EmitImageInfo - Emit the image info marker used to encode some module /// level information. void EmitImageInfo(); /// EmitModuleInfo - Another marker encoding module level /// information. void EmitModuleInfo(); /// EmitModuleSymols - Emit module symbols, the list of defined /// classes and categories. The result has type SymtabPtrTy. llvm::Constant *EmitModuleSymbols(); /// FinishModule - Write out global data structures at the end of /// processing a translation unit. void FinishModule(); /// EmitClassExtension - Generate the class extension structure used /// to store the weak ivar layout and properties. The return value /// has type ClassExtensionPtrTy. llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID); /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, /// for the given class. llvm::Value *EmitClassRef(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID); CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, llvm::Value *Arg0, QualType Arg0Ty, bool IsSuper, const CallArgList &CallArgs); /// EmitIvarList - Emit the ivar list for the given /// implementation. If ForClass is true the list of class ivars /// (i.e. metaclass ivars) is emitted, otherwise the list of /// interface ivars will be emitted. The return value has type /// IvarListPtrTy. llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID, bool ForClass); /// EmitMetaClass - Emit a forward reference to the class structure /// for the metaclass of the given interface. The return value has /// type ClassPtrTy. llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID); /// EmitMetaClass - Emit a class structure for the metaclass of the /// given implementation. The return value has type ClassPtrTy. llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID, llvm::Constant *Protocols, const llvm::Type *InterfaceTy, const ConstantVector &Methods); llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); /// EmitMethodList - Emit the method list for the given /// implementation. The return value has type MethodListPtrTy. llvm::Constant *EmitMethodList(const std::string &Name, const char *Section, const ConstantVector &Methods); /// EmitMethodDescList - Emit a method description list for a list of /// method declarations. /// - TypeName: The name for the type containing the methods. /// - IsProtocol: True iff these methods are for a protocol. /// - ClassMethds: True iff these are class methods. /// - Required: When true, only "required" methods are /// listed. Similarly, when false only "optional" methods are /// listed. For classes this should always be true. /// - begin, end: The method list to output. /// /// The return value has type MethodDescriptionListPtrTy. llvm::Constant *EmitMethodDescList(const std::string &Name, const char *Section, const ConstantVector &Methods); /// GetOrEmitProtocol - Get the protocol object for the given /// declaration, emitting it if necessary. The return value has type /// ProtocolPtrTy. virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); /// GetOrEmitProtocolRef - Get a forward reference to the protocol /// object for the given declaration, emitting it if needed. These /// forward references will be filled in with empty bodies if no /// definition is seen. The return value has type ProtocolPtrTy. virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); /// EmitProtocolExtension - Generate the protocol extension /// structure used to store optional instance and class methods, and /// protocol properties. The return value has type /// ProtocolExtensionPtrTy. llvm::Constant * EmitProtocolExtension(const ObjCProtocolDecl *PD, const ConstantVector &OptInstanceMethods, const ConstantVector &OptClassMethods); /// EmitProtocolList - Generate the list of referenced /// protocols. The return value has type ProtocolListPtrTy. llvm::Constant *EmitProtocolList(const std::string &Name, ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end); /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, /// for the given selector. llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel); public: CGObjCMac(CodeGen::CodeGenModule &cgm); virtual llvm::Function *ModuleInitFunction(); virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, llvm::Value *Receiver, bool IsClassMessage, const CallArgList &CallArgs); virtual CodeGen::RValue GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Receiver, bool IsClassMessage, const CallArgList &CallArgs); virtual llvm::Value *GetClass(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID); virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel); virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, const ObjCProtocolDecl *PD); virtual llvm::Constant *GetPropertyGetFunction(); virtual llvm::Constant *GetPropertySetFunction(); virtual llvm::Constant *EnumerationMutationFunction(); virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S); virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S); virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, llvm::Value *AddrWeakObj); virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst); virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dest); virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dest); virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dest); virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, const FieldDecl *Field, unsigned CVRQualifiers); virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar); }; class CGObjCNonFragileABIMac : public CGObjCCommonMac { private: ObjCNonFragileABITypesHelper ObjCTypes; llvm::GlobalVariable* ObjCEmptyCacheVar; llvm::GlobalVariable* ObjCEmptyVtableVar; /// MetaClassReferences - uniqued meta class references. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences; /// EHTypeReferences - uniqued class ehtype references. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences; /// FinishNonFragileABIModule - Write out global data structures at the end of /// processing a translation unit. void FinishNonFragileABIModule(); llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags, unsigned InstanceStart, unsigned InstanceSize, const ObjCImplementationDecl *ID); llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV, llvm::Constant *ClassRoGV, bool HiddenVisibility); llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); /// EmitMethodList - Emit the method list for the given /// implementation. The return value has type MethodListnfABITy. llvm::Constant *EmitMethodList(const std::string &Name, const char *Section, const ConstantVector &Methods); /// EmitIvarList - Emit the ivar list for the given /// implementation. If ForClass is true the list of class ivars /// (i.e. metaclass ivars) is emitted, otherwise the list of /// interface ivars will be emitted. The return value has type /// IvarListnfABIPtrTy. llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID); llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar, unsigned long int offset); /// GetOrEmitProtocol - Get the protocol object for the given /// declaration, emitting it if necessary. The return value has type /// ProtocolPtrTy. virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); /// GetOrEmitProtocolRef - Get a forward reference to the protocol /// object for the given declaration, emitting it if needed. These /// forward references will be filled in with empty bodies if no /// definition is seen. The return value has type ProtocolPtrTy. virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); /// EmitProtocolList - Generate the list of referenced /// protocols. The return value has type ProtocolListPtrTy. llvm::Constant *EmitProtocolList(const std::string &Name, ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end); CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, llvm::Value *Receiver, QualType Arg0Ty, bool IsSuper, const CallArgList &CallArgs); /// GetClassGlobal - Return the global variable for the Objective-C /// class of the given name. llvm::GlobalVariable *GetClassGlobal(const std::string &Name); /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, /// for the given class. llvm::Value *EmitClassRef(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID, bool IsSuper = false); /// EmitMetaClassRef - Return a Value * of the address of _class_t /// meta-data llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID); /// ObjCIvarOffsetVariable - Returns the ivar offset variable for /// the given ivar. /// llvm::GlobalVariable * ObjCIvarOffsetVariable(std::string &Name, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar); /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, /// for the given selector. llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel); /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C /// interface. The return value has type EHTypePtrTy. llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID, bool ForDefinition); const char *getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; } const char *getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; } public: CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm); // FIXME. All stubs for now! virtual llvm::Function *ModuleInitFunction(); virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, llvm::Value *Receiver, bool IsClassMessage, const CallArgList &CallArgs); virtual CodeGen::RValue GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Receiver, bool IsClassMessage, const CallArgList &CallArgs); virtual llvm::Value *GetClass(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID); virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel) { return EmitSelector(Builder, Sel); } virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, const ObjCProtocolDecl *PD); virtual llvm::Constant *GetPropertyGetFunction() { return ObjCTypes.GetPropertyFn; } virtual llvm::Constant *GetPropertySetFunction() { return ObjCTypes.SetPropertyFn; } virtual llvm::Constant *EnumerationMutationFunction() { return ObjCTypes.EnumerationMutationFn; } virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S); virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S); virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, llvm::Value *AddrWeakObj); virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst); virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dest); virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dest); virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dest); virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, const FieldDecl *Field, unsigned CVRQualifiers); virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar); }; } // end anonymous namespace /* *** Helper Functions *** */ /// getConstantGEP() - Help routine to construct simple GEPs. static llvm::Constant *getConstantGEP(llvm::Constant *C, unsigned idx0, unsigned idx1) { llvm::Value *Idxs[] = { llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0), llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1) }; return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2); } /// hasObjCExceptionAttribute - Return true if this class or any super /// class has the __objc_exception__ attribute. static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) { if (OID->hasAttr<ObjCExceptionAttr>()) return true; if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) return hasObjCExceptionAttribute(Super); return false; } /* *** CGObjCMac Public Interface *** */ CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), ObjCTypes(cgm) { ObjCABI = 1; EmitImageInfo(); } /// GetClass - Return a reference to the class for the given interface /// decl. llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID) { return EmitClassRef(Builder, ID); } /// GetSelector - Return the pointer to the unique'd string for this selector. llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) { return EmitSelector(Builder, Sel); } /// Generate a constant CFString object. /* struct __builtin_CFString { const int *isa; // point to __CFConstantStringClassReference int flags; const char *str; long length; }; */ llvm::Constant *CGObjCCommonMac::GenerateConstantString( const ObjCStringLiteral *SL) { return CGM.GetAddrOfConstantCFString(SL->getString()); } /// Generates a message send where the super is the receiver. This is /// a message send to self with special delivery semantics indicating /// which class's method should be called. CodeGen::RValue CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Receiver, bool IsClassMessage, const CodeGen::CallArgList &CallArgs) { // Create and init a super structure; this is a (receiver, class) // pair we will pass to objc_msgSendSuper. llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); llvm::Value *ReceiverAsObject = CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); CGF.Builder.CreateStore(ReceiverAsObject, CGF.Builder.CreateStructGEP(ObjCSuper, 0)); // If this is a class message the metaclass is passed as the target. llvm::Value *Target; if (IsClassMessage) { if (isCategoryImpl) { // Message sent to 'super' in a class method defined in a category // implementation requires an odd treatment. // If we are in a class method, we must retrieve the // _metaclass_ for the current class, pointed at by // the class's "isa" pointer. The following assumes that // isa" is the first ivar in a class (which it must be). Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); Target = CGF.Builder.CreateStructGEP(Target, 0); Target = CGF.Builder.CreateLoad(Target); } else { llvm::Value *MetaClassPtr = EmitMetaClassRef(Class); llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1); llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr); Target = Super; } } else { Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); } // FIXME: We shouldn't need to do this cast, rectify the ASTContext // and ObjCTypes types. const llvm::Type *ClassTy = CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); Target = CGF.Builder.CreateBitCast(Target, ClassTy); CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1)); return EmitMessageSend(CGF, ResultType, Sel, ObjCSuper, ObjCTypes.SuperPtrCTy, true, CallArgs); } /// Generate code for a message send expression. CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, llvm::Value *Receiver, bool IsClassMessage, const CallArgList &CallArgs) { llvm::Value *Arg0 = CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp"); return EmitMessageSend(CGF, ResultType, Sel, Arg0, CGF.getContext().getObjCIdType(), false, CallArgs); } CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, llvm::Value *Arg0, QualType Arg0Ty, bool IsSuper, const CallArgList &CallArgs) { CallArgList ActualArgs; ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder, Sel)), CGF.getContext().getObjCSelType())); ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); CodeGenTypes &Types = CGM.getTypes(); const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs); const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false); llvm::Constant *Fn; if (CGM.ReturnTypeUsesSret(FnInfo)) { Fn = ObjCTypes.getSendStretFn(IsSuper); } else if (ResultType->isFloatingType()) { // FIXME: Sadly, this is wrong. This actually depends on the // architecture. This happens to be right for x86-32 though. Fn = ObjCTypes.getSendFpretFn(IsSuper); } else { Fn = ObjCTypes.getSendFn(IsSuper); } Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy)); return CGF.EmitCall(FnInfo, Fn, ActualArgs); } llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder, const ObjCProtocolDecl *PD) { // FIXME: I don't understand why gcc generates this, or where it is // resolved. Investigate. Its also wasteful to look this up over and // over. LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), ObjCTypes.ExternalProtocolPtrTy); } void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) { // FIXME: We shouldn't need this, the protocol decl should contain // enough information to tell us whether this was a declaration or a // definition. DefinedProtocols.insert(PD->getIdentifier()); // If we have generated a forward reference to this protocol, emit // it now. Otherwise do nothing, the protocol objects are lazily // emitted. if (Protocols.count(PD->getIdentifier())) GetOrEmitProtocol(PD); } llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) { if (DefinedProtocols.count(PD->getIdentifier())) return GetOrEmitProtocol(PD); return GetOrEmitProtocolRef(PD); } /* // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions struct _objc_protocol { struct _objc_protocol_extension *isa; char *protocol_name; struct _objc_protocol_list *protocol_list; struct _objc__method_prototype_list *instance_methods; struct _objc__method_prototype_list *class_methods }; See EmitProtocolExtension(). */ llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) { llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; // Early exit if a defining object has already been generated. if (Entry && Entry->hasInitializer()) return Entry; // FIXME: I don't understand why gcc generates this, or where it is // resolved. Investigate. Its also wasteful to look this up over and // over. LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); const char *ProtocolName = PD->getNameAsCString(); // Construct method lists. std::vector<llvm::Constant*> InstanceMethods, ClassMethods; std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(CGM.getContext()), e = PD->instmeth_end(CGM.getContext()); i != e; ++i) { ObjCMethodDecl *MD = *i; llvm::Constant *C = GetMethodDescriptionConstant(MD); if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptInstanceMethods.push_back(C); } else { InstanceMethods.push_back(C); } } for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(CGM.getContext()), e = PD->classmeth_end(CGM.getContext()); i != e; ++i) { ObjCMethodDecl *MD = *i; llvm::Constant *C = GetMethodDescriptionConstant(MD); if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptClassMethods.push_back(C); } else { ClassMethods.push_back(C); } } std::vector<llvm::Constant*> Values(5); Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods); Values[1] = GetClassName(PD->getIdentifier()); Values[2] = EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(), PD->protocol_begin(), PD->protocol_end()); Values[3] = EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getNameAsString(), "__OBJC,__cat_inst_meth,regular,no_dead_strip", InstanceMethods); Values[4] = EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" + PD->getNameAsString(), "__OBJC,__cat_cls_meth,regular,no_dead_strip", ClassMethods); llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, Values); if (Entry) { // Already created, fix the linkage and update the initializer. Entry->setLinkage(llvm::GlobalValue::InternalLinkage); Entry->setInitializer(Init); } else { Entry = new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, llvm::GlobalValue::InternalLinkage, Init, std::string("\01L_OBJC_PROTOCOL_")+ProtocolName, &CGM.getModule()); Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); Entry->setAlignment(4); UsedGlobals.push_back(Entry); // FIXME: Is this necessary? Why only for protocol? Entry->setAlignment(4); } return Entry; } llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) { llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; if (!Entry) { // We use the initializer as a marker of whether this is a forward // reference or not. At module finalization we add the empty // contents for protocols which were referenced but never defined. Entry = new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, llvm::GlobalValue::ExternalLinkage, 0, "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(), &CGM.getModule()); Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); Entry->setAlignment(4); UsedGlobals.push_back(Entry); // FIXME: Is this necessary? Why only for protocol? Entry->setAlignment(4); } return Entry; } /* struct _objc_protocol_extension { uint32_t size; struct objc_method_description_list *optional_instance_methods; struct objc_method_description_list *optional_class_methods; struct objc_property_list *instance_properties; }; */ llvm::Constant * CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD, const ConstantVector &OptInstanceMethods, const ConstantVector &OptClassMethods) { uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy); std::vector<llvm::Constant*> Values(4); Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); Values[1] = EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" + PD->getNameAsString(), "__OBJC,__cat_inst_meth,regular,no_dead_strip", OptInstanceMethods); Values[2] = EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getNameAsString(), "__OBJC,__cat_cls_meth,regular,no_dead_strip", OptClassMethods); Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + PD->getNameAsString(), 0, PD, ObjCTypes); // Return null if no extension bits are used. if (Values[1]->isNullValue() && Values[2]->isNullValue() && Values[3]->isNullValue()) return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values); // No special section, but goes in llvm.used return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(), Init, 0, 0, true); } /* struct objc_protocol_list { struct objc_protocol_list *next; long count; Protocol *list[]; }; */ llvm::Constant * CGObjCMac::EmitProtocolList(const std::string &Name, ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end) { std::vector<llvm::Constant*> ProtocolRefs; for (; begin != end; ++begin) ProtocolRefs.push_back(GetProtocolRef(*begin)); // Just return null for empty protocol lists if (ProtocolRefs.empty()) return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); // This list is null terminated. ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy)); std::vector<llvm::Constant*> Values(3); // This field is only used by the runtime. Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); Values[2] = llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy, ProtocolRefs.size()), ProtocolRefs); llvm::Constant *Init = llvm::ConstantStruct::get(Values); llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip", 4, false); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); } /* struct _objc_property { const char * const name; const char * const attributes; }; struct _objc_property_list { uint32_t entsize; // sizeof (struct _objc_property) uint32_t prop_count; struct _objc_property[prop_count]; }; */ llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name, const Decl *Container, const ObjCContainerDecl *OCD, const ObjCCommonTypesHelper &ObjCTypes) { std::vector<llvm::Constant*> Properties, Prop(2); for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()), E = OCD->prop_end(CGM.getContext()); I != E; ++I) { const ObjCPropertyDecl *PD = *I; Prop[0] = GetPropertyName(PD->getIdentifier()); Prop[1] = GetPropertyTypeString(PD, Container); Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop)); } // Return null for empty list. if (Properties.empty()) return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); unsigned PropertySize = CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy); std::vector<llvm::Constant*> Values(3); Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize); Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size()); llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy, Properties.size()); Values[2] = llvm::ConstantArray::get(AT, Properties); llvm::Constant *Init = llvm::ConstantStruct::get(Values); llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : "__OBJC,__property,regular,no_dead_strip", (ObjCABI == 2) ? 8 : 4, true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy); } /* struct objc_method_description_list { int count; struct objc_method_description list[]; }; */ llvm::Constant * CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { std::vector<llvm::Constant*> Desc(2); Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), ObjCTypes.SelectorPtrTy); Desc[1] = GetMethodVarType(MD); return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy, Desc); } llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name, const char *Section, const ConstantVector &Methods) { // Return null for empty list. if (Methods.empty()) return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); std::vector<llvm::Constant*> Values(2); Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy, Methods.size()); Values[1] = llvm::ConstantArray::get(AT, Methods); llvm::Constant *Init = llvm::ConstantStruct::get(Values); llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodDescriptionListPtrTy); } /* struct _objc_category { char *category_name; char *class_name; struct _objc_method_list *instance_methods; struct _objc_method_list *class_methods; struct _objc_protocol_list *protocols; uint32_t size; // <rdar://4585769> struct _objc_property_list *instance_properties; }; */ void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy); // FIXME: This is poor design, the OCD should have a pointer to the // category decl. Additionally, note that Category can be null for // the @implementation w/o an @interface case. Sema should just // create one for us as it does for @implementation so everyone else // can live life under a clear blue sky. const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); const ObjCCategoryDecl *Category = Interface->FindCategoryDeclaration(OCD->getIdentifier()); std::string ExtName(Interface->getNameAsString() + "_" + OCD->getNameAsString()); std::vector<llvm::Constant*> InstanceMethods, ClassMethods; for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) { // Instance methods should always be defined. InstanceMethods.push_back(GetMethodConstant(*i)); } for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) { // Class methods should always be defined. ClassMethods.push_back(GetMethodConstant(*i)); } std::vector<llvm::Constant*> Values(7); Values[0] = GetClassName(OCD->getIdentifier()); Values[1] = GetClassName(Interface->getIdentifier()); Values[2] = EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") + ExtName, "__OBJC,__cat_inst_meth,regular,no_dead_strip", InstanceMethods); Values[3] = EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName, "__OBJC,__cat_cls_meth,regular,no_dead_strip", ClassMethods); if (Category) { Values[4] = EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName, Category->protocol_begin(), Category->protocol_end()); } else { Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); } Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); // If there is no category @interface then there can be no properties. if (Category) { Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName, OCD, Category, ObjCTypes); } else { Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); } llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy, Values); llvm::GlobalVariable *GV = CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init, "__OBJC,__category,regular,no_dead_strip", 4, true); DefinedCategories.push_back(GV); } // FIXME: Get from somewhere? enum ClassFlags { eClassFlags_Factory = 0x00001, eClassFlags_Meta = 0x00002, // <rdr://5142207> eClassFlags_HasCXXStructors = 0x02000, eClassFlags_Hidden = 0x20000, eClassFlags_ABI2_Hidden = 0x00010, eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634> }; /* struct _objc_class { Class isa; Class super_class; const char *name; long version; long info; long instance_size; struct _objc_ivar_list *ivars; struct _objc_method_list *methods; struct _objc_cache *cache; struct _objc_protocol_list *protocols; // Objective-C 1.0 extensions (<rdr://4585769>) const char *ivar_layout; struct _objc_class_ext *ext; }; See EmitClassExtension(); */ void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) { DefinedSymbols.insert(ID->getIdentifier()); std::string ClassName = ID->getNameAsString(); // FIXME: Gross ObjCInterfaceDecl *Interface = const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); llvm::Constant *Protocols = EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(), Interface->protocol_begin(), Interface->protocol_end()); const llvm::Type *InterfaceTy = CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface)); unsigned Flags = eClassFlags_Factory; unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy); // FIXME: Set CXX-structors flag. if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden) Flags |= eClassFlags_Hidden; std::vector<llvm::Constant*> InstanceMethods, ClassMethods; for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) { // Instance methods should always be defined. InstanceMethods.push_back(GetMethodConstant(*i)); } for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) { // Class methods should always be defined. ClassMethods.push_back(GetMethodConstant(*i)); } for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) { ObjCPropertyImplDecl *PID = *i; if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { ObjCPropertyDecl *PD = PID->getPropertyDecl(); if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) if (llvm::Constant *C = GetMethodConstant(MD)) InstanceMethods.push_back(C); if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) if (llvm::Constant *C = GetMethodConstant(MD)) InstanceMethods.push_back(C); } } std::vector<llvm::Constant*> Values(12); Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods); if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) { // Record a reference to the super class. LazySymbols.insert(Super->getIdentifier()); Values[ 1] = llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), ObjCTypes.ClassPtrTy); } else { Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); } Values[ 2] = GetClassName(ID->getIdentifier()); // Version is always 0. Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); Values[ 6] = EmitIvarList(ID, false); Values[ 7] = EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(), "__OBJC,__inst_meth,regular,no_dead_strip", InstanceMethods); // cache is always NULL. Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); Values[ 9] = Protocols; // FIXME: Set ivar_layout // Values[10] = BuildIvarLayout(ID, true); Values[10] = GetIvarLayoutName(0, ObjCTypes); Values[11] = EmitClassExtension(ID); llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, Values); llvm::GlobalVariable *GV = CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init, "__OBJC,__class,regular,no_dead_strip", 4, true); DefinedClasses.push_back(GV); } llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID, llvm::Constant *Protocols, const llvm::Type *InterfaceTy, const ConstantVector &Methods) { unsigned Flags = eClassFlags_Meta; unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy); if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden) Flags |= eClassFlags_Hidden; std::vector<llvm::Constant*> Values(12); // The isa for the metaclass is the root of the hierarchy. const ObjCInterfaceDecl *Root = ID->getClassInterface(); while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) Root = Super; Values[ 0] = llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()), ObjCTypes.ClassPtrTy); // The super class for the metaclass is emitted as the name of the // super class. The runtime fixes this up to point to the // *metaclass* for the super class. if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) { Values[ 1] = llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), ObjCTypes.ClassPtrTy); } else { Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); } Values[ 2] = GetClassName(ID->getIdentifier()); // Version is always 0. Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); Values[ 6] = EmitIvarList(ID, true); Values[ 7] = EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(), "__OBJC,__cls_meth,regular,no_dead_strip", Methods); // cache is always NULL. Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); Values[ 9] = Protocols; // ivar_layout for metaclass is always NULL. Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); // The class extension is always unused for metaclasses. Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, Values); std::string Name("\01L_OBJC_METACLASS_"); Name += ID->getNameAsCString(); // Check for a forward reference. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); if (GV) { assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && "Forward metaclass reference has incorrect type."); GV->setLinkage(llvm::GlobalValue::InternalLinkage); GV->setInitializer(Init); } else { GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false, llvm::GlobalValue::InternalLinkage, Init, Name, &CGM.getModule()); } GV->setSection("__OBJC,__meta_class,regular,no_dead_strip"); GV->setAlignment(4); UsedGlobals.push_back(GV); return GV; } llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) { std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString(); // FIXME: Should we look these up somewhere other than the // module. Its a bit silly since we only generate these while // processing an implementation, so exactly one pointer would work // if know when we entered/exitted an implementation block. // Check for an existing forward reference. // Previously, metaclass with internal linkage may have been defined. // pass 'true' as 2nd argument so it is returned. if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) { assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && "Forward metaclass reference has incorrect type."); return GV; } else { // Generate as an external reference to keep a consistent // module. This will be patched up when we emit the metaclass. return new llvm::GlobalVariable(ObjCTypes.ClassTy, false, llvm::GlobalValue::ExternalLinkage, 0, Name, &CGM.getModule()); } } /* struct objc_class_ext { uint32_t size; const char *weak_ivar_layout; struct _objc_property_list *properties; }; */ llvm::Constant * CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) { uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy); std::vector<llvm::Constant*> Values(3); Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); // FIXME: Output weak_ivar_layout string. // Values[1] = BuildIvarLayout(ID, false); Values[1] = GetIvarLayoutName(0, ObjCTypes); Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(), ID, ID->getClassInterface(), ObjCTypes); // Return null if no extension bits are used. if (Values[1]->isNullValue() && Values[2]->isNullValue()) return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values); return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(), Init, "__OBJC,__class_ext,regular,no_dead_strip", 4, true); } /// countInheritedIvars - count number of ivars in class and its super class(s) /// static int countInheritedIvars(const ObjCInterfaceDecl *OI, ASTContext &Context) { int count = 0; if (!OI) return 0; const ObjCInterfaceDecl *SuperClass = OI->getSuperClass(); if (SuperClass) count += countInheritedIvars(SuperClass, Context); for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), E = OI->ivar_end(); I != E; ++I) ++count; // look into properties. for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context), E = OI->prop_end(Context); I != E; ++I) { if ((*I)->getPropertyIvarDecl()) ++count; } return count; } /// getInterfaceDeclForIvar - Get the interface declaration node where /// this ivar is declared in. /// FIXME. Ideally, this info should be in the ivar node. But currently /// it is not and prevailing wisdom is that ASTs should not have more /// info than is absolutely needed, even though this info reflects the /// source language. /// static const ObjCInterfaceDecl *getInterfaceDeclForIvar( const ObjCInterfaceDecl *OI, const ObjCIvarDecl *IVD, ASTContext &Context) { if (!OI) return 0; assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface"); for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), E = OI->ivar_end(); I != E; ++I) if ((*I)->getIdentifier() == IVD->getIdentifier()) return OI; // look into properties. for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context), E = OI->prop_end(Context); I != E; ++I) { ObjCPropertyDecl *PDecl = (*I); if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) if (IV->getIdentifier() == IVD->getIdentifier()) return OI; } return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context); } /* struct objc_ivar { char *ivar_name; char *ivar_type; int ivar_offset; }; struct objc_ivar_list { int ivar_count; struct objc_ivar list[count]; }; */ llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, bool ForClass) { std::vector<llvm::Constant*> Ivars, Ivar(3); // When emitting the root class GCC emits ivar entries for the // actual class structure. It is not clear if we need to follow this // behavior; for now lets try and get away with not doing it. If so, // the cleanest solution would be to make up an ObjCInterfaceDecl // for the class. if (ForClass) return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID); RecordDecl::field_iterator ifield, pfield; const RecordDecl *RD = GetFirstIvarInRecord(OID, ifield, pfield); for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()); ifield != e; ++ifield) { FieldDecl *Field = *ifield; uint64_t Offset = GetIvarBaseOffset(Layout, Field); if (Field->getIdentifier()) Ivar[0] = GetMethodVarName(Field->getIdentifier()); else Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); Ivar[1] = GetMethodVarType(Field); Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset); Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar)); } // Return null for empty list. if (Ivars.empty()) return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); std::vector<llvm::Constant*> Values(2); Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy, Ivars.size()); Values[1] = llvm::ConstantArray::get(AT, Ivars); llvm::Constant *Init = llvm::ConstantStruct::get(Values); llvm::GlobalVariable *GV; if (ForClass) GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(), Init, "__OBJC,__class_vars,regular,no_dead_strip", 4, true); else GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" + ID->getNameAsString(), Init, "__OBJC,__instance_vars,regular,no_dead_strip", 4, true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy); } /* struct objc_method { SEL method_name; char *method_types; void *method; }; struct objc_method_list { struct objc_method_list *obsolete; int count; struct objc_method methods_list[count]; }; */ /// GetMethodConstant - Return a struct objc_method constant for the /// given method if it has been defined. The result is null if the /// method has not been defined. The return value has type MethodPtrTy. llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) { // FIXME: Use DenseMap::lookup llvm::Function *Fn = MethodDefinitions[MD]; if (!Fn) return 0; std::vector<llvm::Constant*> Method(3); Method[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), ObjCTypes.SelectorPtrTy); Method[1] = GetMethodVarType(MD); Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); } llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name, const char *Section, const ConstantVector &Methods) { // Return null for empty list. if (Methods.empty()) return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy); std::vector<llvm::Constant*> Values(3); Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, Methods.size()); Values[2] = llvm::ConstantArray::get(AT, Methods); llvm::Constant *Init = llvm::ConstantStruct::get(Values); llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy); } llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD) { std::string Name; GetNameForMethod(OMD, CD, Name); CodeGenTypes &Types = CGM.getTypes(); const llvm::FunctionType *MethodTy = Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic()); llvm::Function *Method = llvm::Function::Create(MethodTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); MethodDefinitions.insert(std::make_pair(OMD, Method)); return Method; } uint64_t CGObjCCommonMac::GetIvarBaseOffset(const llvm::StructLayout *Layout, const FieldDecl *Field) { if (!Field->isBitField()) return Layout->getElementOffset( CGM.getTypes().getLLVMFieldNo(Field)); // FIXME. Must be a better way of getting a bitfield base offset. uint64_t offset = CGM.getTypes().getLLVMFieldNo(Field); const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMemRecursive(Field->getType()); uint64_t size = CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty); offset = (offset*size)/8; return offset; } /// GetFieldBaseOffset - return's field byt offset. uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI, const llvm::StructLayout *Layout, const FieldDecl *Field) { const ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); const FieldDecl *FD = OI->lookupFieldDeclForIvar(CGM.getContext(), Ivar); return GetIvarBaseOffset(Layout, FD); } llvm::GlobalVariable * CGObjCCommonMac::CreateMetadataVar(const std::string &Name, llvm::Constant *Init, const char *Section, unsigned Align, bool AddToUsed) { const llvm::Type *Ty = Init->getType(); llvm::GlobalVariable *GV = new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::InternalLinkage, Init, Name, &CGM.getModule()); if (Section) GV->setSection(Section); if (Align) GV->setAlignment(Align); if (AddToUsed) UsedGlobals.push_back(GV); return GV; } llvm::Function *CGObjCMac::ModuleInitFunction() { // Abuse this interface function as a place to finalize. FinishModule(); return NULL; } llvm::Constant *CGObjCMac::GetPropertyGetFunction() { return ObjCTypes.GetPropertyFn; } llvm::Constant *CGObjCMac::GetPropertySetFunction() { return ObjCTypes.SetPropertyFn; } llvm::Constant *CGObjCMac::EnumerationMutationFunction() { return ObjCTypes.EnumerationMutationFn; } /* Objective-C setjmp-longjmp (sjlj) Exception Handling -- The basic framework for a @try-catch-finally is as follows: { objc_exception_data d; id _rethrow = null; bool _call_try_exit = true; objc_exception_try_enter(&d); if (!setjmp(d.jmp_buf)) { ... try body ... } else { // exception path id _caught = objc_exception_extract(&d); // enter new try scope for handlers if (!setjmp(d.jmp_buf)) { ... match exception and execute catch blocks ... // fell off end, rethrow. _rethrow = _caught; ... jump-through-finally to finally_rethrow ... } else { // exception in catch block _rethrow = objc_exception_extract(&d); _call_try_exit = false; ... jump-through-finally to finally_rethrow ... } } ... jump-through-finally to finally_end ... finally: if (_call_try_exit) objc_exception_try_exit(&d); ... finally block .... ... dispatch to finally destination ... finally_rethrow: objc_exception_throw(_rethrow); finally_end: } This framework differs slightly from the one gcc uses, in that gcc uses _rethrow to determine if objc_exception_try_exit should be called and if the object should be rethrown. This breaks in the face of throwing nil and introduces unnecessary branches. We specialize this framework for a few particular circumstances: - If there are no catch blocks, then we avoid emitting the second exception handling context. - If there is a catch-all catch block (i.e. @catch(...) or @catch(id e)) we avoid emitting the code to rethrow an uncaught exception. - FIXME: If there is no @finally block we can do a few more simplifications. Rethrows and Jumps-Through-Finally -- Support for implicit rethrows and jumping through the finally block is handled by storing the current exception-handling context in ObjCEHStack. In order to implement proper @finally semantics, we support one basic mechanism for jumping through the finally block to an arbitrary destination. Constructs which generate exits from a @try or @catch block use this mechanism to implement the proper semantics by chaining jumps, as necessary. This mechanism works like the one used for indirect goto: we arbitrarily assign an ID to each destination and store the ID for the destination in a variable prior to entering the finally block. At the end of the finally block we simply create a switch to the proper destination. Code gen for @synchronized(expr) stmt; Effectively generating code for: objc_sync_enter(expr); @try stmt @finally { objc_sync_exit(expr); } */ void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S) { bool isTry = isa<ObjCAtTryStmt>(S); // Create various blocks we refer to for handling @finally. llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit"); llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit"); llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); // For @synchronized, call objc_sync_enter(sync.expr). The // evaluation of the expression must occur before we enter the // @synchronized. We can safely avoid a temp here because jumps into // @synchronized are illegal & this will dominate uses. llvm::Value *SyncArg = 0; if (!isTry) { SyncArg = CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy); CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg); } // Push an EH context entry, used for handling rethrows and jumps // through finally. CGF.PushCleanupBlock(FinallyBlock); CGF.ObjCEHValueStack.push_back(0); // Allocate memory for the exception data and rethrow pointer. llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy, "exceptiondata.ptr"); llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy, "_rethrow"); llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty, "_call_try_exit"); CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr); // Enter a new try block and call setjmp. CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData); llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0, "jmpbufarray"); JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp"); llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn, JmpBufPtr, "result"); llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"), TryHandler, TryBlock); // Emit the @try block. CGF.EmitBlock(TryBlock); CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); CGF.EmitBranchThroughCleanup(FinallyEnd); // Emit the "exception in @try" block. CGF.EmitBlock(TryHandler); // Retrieve the exception object. We may emit multiple blocks but // nothing can cross this so the value is already in SSA form. llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn, ExceptionData, "caught"); CGF.ObjCEHValueStack.back() = Caught; if (!isTry) { CGF.Builder.CreateStore(Caught, RethrowPtr); CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); CGF.EmitBranchThroughCleanup(FinallyRethrow); } else if (const ObjCAtCatchStmt* CatchStmt = cast<ObjCAtTryStmt>(S).getCatchStmts()) { // Enter a new exception try block (in case a @catch block throws // an exception). CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData); llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn, JmpBufPtr, "result"); llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"); llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch"); llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler"); CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock); CGF.EmitBlock(CatchBlock); // Handle catch list. As a special case we check if everything is // matched and avoid generating code for falling off the end if // so. bool AllMatched = false; for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch"); const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl(); const PointerType *PT = 0; // catch(...) always matches. if (!CatchParam) { AllMatched = true; } else { PT = CatchParam->getType()->getAsPointerType(); // catch(id e) always matches. // FIXME: For the time being we also match id<X>; this should // be rejected by Sema instead. if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) || CatchParam->getType()->isObjCQualifiedIdType()) AllMatched = true; } if (AllMatched) { if (CatchParam) { CGF.EmitLocalBlockVarDecl(*CatchParam); assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam)); } CGF.EmitStmt(CatchStmt->getCatchBody()); CGF.EmitBranchThroughCleanup(FinallyEnd); break; } assert(PT && "Unexpected non-pointer type in @catch"); QualType T = PT->getPointeeType(); const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType(); assert(ObjCType && "Catch parameter must have Objective-C type!"); // Check if the @catch block matches the exception object. llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl()); llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn, Class, Caught, "match"); llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched"); CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"), MatchedBlock, NextCatchBlock); // Emit the @catch block. CGF.EmitBlock(MatchedBlock); CGF.EmitLocalBlockVarDecl(*CatchParam); assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); llvm::Value *Tmp = CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()), "tmp"); CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam)); CGF.EmitStmt(CatchStmt->getCatchBody()); CGF.EmitBranchThroughCleanup(FinallyEnd); CGF.EmitBlock(NextCatchBlock); } if (!AllMatched) { // None of the handlers caught the exception, so store it to be // rethrown at the end of the @finally block. CGF.Builder.CreateStore(Caught, RethrowPtr); CGF.EmitBranchThroughCleanup(FinallyRethrow); } // Emit the exception handler for the @catch blocks. CGF.EmitBlock(CatchHandler); CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn, ExceptionData), RethrowPtr); CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); CGF.EmitBranchThroughCleanup(FinallyRethrow); } else { CGF.Builder.CreateStore(Caught, RethrowPtr); CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); CGF.EmitBranchThroughCleanup(FinallyRethrow); } // Pop the exception-handling stack entry. It is important to do // this now, because the code in the @finally block is not in this // context. CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); CGF.ObjCEHValueStack.pop_back(); // Emit the @finally block. CGF.EmitBlock(FinallyBlock); llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp"); CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit); CGF.EmitBlock(FinallyExit); CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData); CGF.EmitBlock(FinallyNoExit); if (isTry) { if (const ObjCAtFinallyStmt* FinallyStmt = cast<ObjCAtTryStmt>(S).getFinallyStmt()) CGF.EmitStmt(FinallyStmt->getFinallyBody()); } else { // Emit objc_sync_exit(expr); as finally's sole statement for // @synchronized. CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg); } // Emit the switch block if (Info.SwitchBlock) CGF.EmitBlock(Info.SwitchBlock); if (Info.EndBlock) CGF.EmitBlock(Info.EndBlock); CGF.EmitBlock(FinallyRethrow); CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, CGF.Builder.CreateLoad(RethrowPtr)); CGF.Builder.CreateUnreachable(); CGF.EmitBlock(FinallyEnd); } void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S) { llvm::Value *ExceptionAsObject; if (const Expr *ThrowExpr = S.getThrowExpr()) { llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); ExceptionAsObject = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp"); } else { assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && "Unexpected rethrow outside @catch block."); ExceptionAsObject = CGF.ObjCEHValueStack.back(); } CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject); CGF.Builder.CreateUnreachable(); // Clear the insertion point to indicate we are in unreachable code. CGF.Builder.ClearInsertionPoint(); } /// EmitObjCWeakRead - Code gen for loading value of a __weak /// object: objc_read_weak (id *src) /// llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, llvm::Value *AddrWeakObj) { const llvm::Type* DestTy = cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType(); AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn, AddrWeakObj, "weakread"); read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); return read_weak; } /// EmitObjCWeakAssign - Code gen for assigning to a __weak object. /// objc_assign_weak (id src, id *dst) /// void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn, src, dst, "weakassign"); return; } /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. /// objc_assign_global (id src, id *dst) /// void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn, src, dst, "globalassign"); return; } /// EmitObjCIvarAssign - Code gen for assigning to a __strong object. /// objc_assign_ivar (id src, id *dst) /// void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn, src, dst, "assignivar"); return; } /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. /// objc_assign_strongCast (id src, id *dst) /// void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn, src, dst, "weakassign"); return; } /// EmitObjCValueForIvar - Code Gen for ivar reference. /// LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, const FieldDecl *Field, unsigned CVRQualifiers) { if (Ivar->isBitField()) return CGF.EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field), CVRQualifiers); // TODO: Add a special case for isa (index 0) unsigned Index = CGM.getTypes().getLLVMFieldNo(Field); llvm::Value *V = CGF.Builder.CreateStructGEP(BaseValue, Index, "tmp"); LValue LV = LValue::MakeAddr(V, Ivar->getType().getCVRQualifiers()|CVRQualifiers, CGM.getContext().getObjCGCAttrKind(Ivar->getType())); LValue::SetObjCIvar(LV, true); return LV; } llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar) { const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(Interface); FieldDecl *Field = Interface->lookupFieldDeclForIvar(CGM.getContext(), Ivar); uint64_t Offset = GetIvarBaseOffset(Layout, Field); return llvm::ConstantInt::get( CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset); } /* *** Private Interface *** */ /// EmitImageInfo - Emit the image info marker used to encode some module /// level information. /// /// See: <rdr://4810609&4810587&4810587> /// struct IMAGE_INFO { /// unsigned version; /// unsigned flags; /// }; enum ImageInfoFlags { eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what this implies eImageInfo_GarbageCollected = (1 << 1), eImageInfo_GCOnly = (1 << 2) }; void CGObjCMac::EmitImageInfo() { unsigned version = 0; // Version is unused? unsigned flags = 0; // FIXME: Fix and continue? if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) flags |= eImageInfo_GarbageCollected; if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) flags |= eImageInfo_GCOnly; // Emitted as int[2]; llvm::Constant *values[2] = { llvm::ConstantInt::get(llvm::Type::Int32Ty, version), llvm::ConstantInt::get(llvm::Type::Int32Ty, flags) }; llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2); const char *Section; if (ObjCABI == 1) Section = "__OBJC, __image_info,regular"; else Section = "__DATA, __objc_imageinfo, regular, no_dead_strip"; llvm::GlobalVariable *GV = CreateMetadataVar("\01L_OBJC_IMAGE_INFO", llvm::ConstantArray::get(AT, values, 2), Section, 0, true); GV->setConstant(true); } // struct objc_module { // unsigned long version; // unsigned long size; // const char *name; // Symtab symtab; // }; // FIXME: Get from somewhere static const int ModuleVersion = 7; void CGObjCMac::EmitModuleInfo() { uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy); std::vector<llvm::Constant*> Values(4); Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion); Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); // This used to be the filename, now it is unused. <rdr://4327263> Values[2] = GetClassName(&CGM.getContext().Idents.get("")); Values[3] = EmitModuleSymbols(); CreateMetadataVar("\01L_OBJC_MODULES", llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values), "__OBJC,__module_info,regular,no_dead_strip", 4, true); } llvm::Constant *CGObjCMac::EmitModuleSymbols() { unsigned NumClasses = DefinedClasses.size(); unsigned NumCategories = DefinedCategories.size(); // Return null if no symbols were defined. if (!NumClasses && !NumCategories) return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy); std::vector<llvm::Constant*> Values(5); Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy); Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses); Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories); // The runtime expects exactly the list of defined classes followed // by the list of defined categories, in a single array. std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories); for (unsigned i=0; i<NumClasses; i++) Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], ObjCTypes.Int8PtrTy); for (unsigned i=0; i<NumCategories; i++) Symbols[NumClasses + i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i], ObjCTypes.Int8PtrTy); Values[4] = llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, NumClasses + NumCategories), Symbols); llvm::Constant *Init = llvm::ConstantStruct::get(Values); llvm::GlobalVariable *GV = CreateMetadataVar("\01L_OBJC_SYMBOLS", Init, "__OBJC,__symbols,regular,no_dead_strip", 4, true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy); } llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID) { LazySymbols.insert(ID->getIdentifier()); llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; if (!Entry) { llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()), ObjCTypes.ClassPtrTy); Entry = CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted, "__OBJC,__cls_refs,literal_pointers,no_dead_strip", 4, true); } return Builder.CreateLoad(Entry, false, "tmp"); } llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) { llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; if (!Entry) { llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), ObjCTypes.SelectorPtrTy); Entry = CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted, "__OBJC,__message_refs,literal_pointers,no_dead_strip", 4, true); } return Builder.CreateLoad(Entry, false, "tmp"); } llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) { llvm::GlobalVariable *&Entry = ClassNames[Ident]; if (!Entry) Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_", llvm::ConstantArray::get(Ident->getName()), "__TEXT,__cstring,cstring_literals", 1, true); return getConstantGEP(Entry, 0, 0); } /// GetInterfaceDeclStructLayout - Get layout for ivars of given /// interface declaration. const llvm::StructLayout *CGObjCCommonMac::GetInterfaceDeclStructLayout( const ObjCInterfaceDecl *OID) const { const llvm::Type *InterfaceTy = CGM.getTypes().ConvertType( CGM.getContext().getObjCInterfaceType( const_cast<ObjCInterfaceDecl*>(OID))); const llvm::StructLayout *Layout = CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy)); return Layout; } /// GetIvarLayoutName - Returns a unique constant for the given /// ivar layout bitmap. llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident, const ObjCCommonTypesHelper &ObjCTypes) { return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); } void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI, const llvm::StructLayout *Layout, const RecordDecl *RD, const llvm::SmallVectorImpl<FieldDecl*> &RecFields, unsigned int BytePos, bool ForStrongLayout, int &Index, int &SkIndex, bool &HasUnion) { bool IsUnion = (RD && RD->isUnion()); uint64_t MaxUnionIvarSize = 0; uint64_t MaxSkippedUnionIvarSize = 0; FieldDecl *MaxField = 0; FieldDecl *MaxSkippedField = 0; unsigned base = 0; if (RecFields.empty()) return; if (IsUnion) base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]); unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0); unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth(); llvm::SmallVector<FieldDecl*, 16> TmpRecFields; for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { FieldDecl *Field = RecFields[i]; // Skip over unnamed or bitfields if (!Field->getIdentifier() || Field->isBitField()) continue; QualType FQT = Field->getType(); if (FQT->isRecordType() || FQT->isUnionType()) { if (FQT->isUnionType()) HasUnion = true; else assert(FQT->isRecordType() && "only union/record is supported for ivar layout bitmap"); const RecordType *RT = FQT->getAsRecordType(); const RecordDecl *RD = RT->getDecl(); // FIXME - Find a more efficiant way of passing records down. TmpRecFields.append(RD->field_begin(CGM.getContext()), RD->field_end(CGM.getContext())); // FIXME - Is Layout correct? BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields, BytePos + GetFieldBaseOffset(OI, Layout, Field), ForStrongLayout, Index, SkIndex, HasUnion); TmpRecFields.clear(); continue; } if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { const ConstantArrayType *CArray = dyn_cast_or_null<ConstantArrayType>(Array); assert(CArray && "only array with know element size is supported"); FQT = CArray->getElementType(); while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { const ConstantArrayType *CArray = dyn_cast_or_null<ConstantArrayType>(Array); FQT = CArray->getElementType(); } assert(!FQT->isUnionType() && "layout for array of unions not supported"); if (FQT->isRecordType()) { uint64_t ElCount = CArray->getSize().getZExtValue(); int OldIndex = Index; int OldSkIndex = SkIndex; // FIXME - Use a common routine with the above! const RecordType *RT = FQT->getAsRecordType(); const RecordDecl *RD = RT->getDecl(); // FIXME - Find a more efficiant way of passing records down. TmpRecFields.append(RD->field_begin(CGM.getContext()), RD->field_end(CGM.getContext())); BuildAggrIvarLayout(OI, Layout, RD, TmpRecFields, BytePos + GetFieldBaseOffset(OI, Layout, Field), ForStrongLayout, Index, SkIndex, HasUnion); TmpRecFields.clear(); // Replicate layout information for each array element. Note that // one element is already done. uint64_t ElIx = 1; for (int FirstIndex = Index, FirstSkIndex = SkIndex; ElIx < ElCount; ElIx++) { uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits; for (int i = OldIndex+1; i <= FirstIndex; ++i) { GC_IVAR gcivar; gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx; gcivar.ivar_size = IvarsInfo[i].ivar_size; IvarsInfo.push_back(gcivar); ++Index; } for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) { GC_IVAR skivar; skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx; skivar.ivar_size = SkipIvars[i].ivar_size; SkipIvars.push_back(skivar); ++SkIndex; } } continue; } } // At this point, we are done with Record/Union and array there of. // For other arrays we are down to its element type. QualType::GCAttrTypes GCAttr = QualType::GCNone; do { if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) { GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak; break; } else if (CGM.getContext().isObjCObjectPointerType(FQT)) { GCAttr = QualType::Strong; break; } else if (const PointerType *PT = FQT->getAsPointerType()) { FQT = PT->getPointeeType(); } else { break; } } while (true); if ((ForStrongLayout && GCAttr == QualType::Strong) || (!ForStrongLayout && GCAttr == QualType::Weak)) { if (IsUnion) { uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType()) / WordSizeInBits; if (UnionIvarSize > MaxUnionIvarSize) { MaxUnionIvarSize = UnionIvarSize; MaxField = Field; } } else { GC_IVAR gcivar; gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field); gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) / WordSizeInBits; IvarsInfo.push_back(gcivar); ++Index; } } else if ((ForStrongLayout && (GCAttr == QualType::GCNone || GCAttr == QualType::Weak)) || (!ForStrongLayout && GCAttr != QualType::Weak)) { if (IsUnion) { uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType()); if (UnionIvarSize > MaxSkippedUnionIvarSize) { MaxSkippedUnionIvarSize = UnionIvarSize; MaxSkippedField = Field; } } else { GC_IVAR skivar; skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field); skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) / WordSizeInBits; SkipIvars.push_back(skivar); ++SkIndex; } } } if (MaxField) { GC_IVAR gcivar; gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField); gcivar.ivar_size = MaxUnionIvarSize; IvarsInfo.push_back(gcivar); ++Index; } if (MaxSkippedField) { GC_IVAR skivar; skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxSkippedField); skivar.ivar_size = MaxSkippedUnionIvarSize; SkipIvars.push_back(skivar); ++SkIndex; } } static int IvarBytePosCompare(const void *a, const void *b) { unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos; unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos; if (sa < sb) return -1; if (sa > sb) return 1; return 0; } /// BuildIvarLayout - Builds ivar layout bitmap for the class /// implementation for the __strong or __weak case. /// The layout map displays which words in ivar list must be skipped /// and which must be scanned by GC (see below). String is built of bytes. /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count /// of words to skip and right nibble is count of words to scan. So, each /// nibble represents up to 15 workds to skip or scan. Skipping the rest is /// represented by a 0x00 byte which also ends the string. /// 1. when ForStrongLayout is true, following ivars are scanned: /// - id, Class /// - object * /// - __strong anything /// /// 2. When ForStrongLayout is false, following ivars are scanned: /// - __weak anything /// llvm::Constant *CGObjCCommonMac::BuildIvarLayout( const ObjCImplementationDecl *OMD, bool ForStrongLayout) { int Index = -1; int SkIndex = -1; bool hasUnion = false; int SkipScan; unsigned int WordsToScan, WordsToSkip; const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) return llvm::Constant::getNullValue(PtrTy); llvm::SmallVector<FieldDecl*, 32> RecFields; const ObjCInterfaceDecl *OI = OMD->getClassInterface(); CGM.getContext().CollectObjCIvars(OI, RecFields); if (RecFields.empty()) return llvm::Constant::getNullValue(PtrTy); SkipIvars.clear(); IvarsInfo.clear(); const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OI); BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, Index, SkIndex, hasUnion); if (Index == -1) return llvm::Constant::getNullValue(PtrTy); // Sort on byte position in case we encounterred a union nested in // the ivar list. if (hasUnion && !IvarsInfo.empty()) qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare); if (hasUnion && !SkipIvars.empty()) qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare); // Build the string of skip/scan nibbles SkipScan = -1; SkipScanIvars.clear(); unsigned int WordSize = CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy); if (IvarsInfo[0].ivar_bytepos == 0) { WordsToSkip = 0; WordsToScan = IvarsInfo[0].ivar_size; } else { WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize; WordsToScan = IvarsInfo[0].ivar_size; } for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) { unsigned int TailPrevGCObjC = IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize; if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) { // consecutive 'scanned' object pointers. WordsToScan += IvarsInfo[i].ivar_size; } else { // Skip over 'gc'able object pointer which lay over each other. if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos) continue; // Must skip over 1 or more words. We save current skip/scan values // and start a new pair. SKIP_SCAN SkScan; SkScan.skip = WordsToSkip; SkScan.scan = WordsToScan; SkipScanIvars.push_back(SkScan); ++SkipScan; // Skip the hole. SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize; SkScan.scan = 0; SkipScanIvars.push_back(SkScan); ++SkipScan; WordsToSkip = 0; WordsToScan = IvarsInfo[i].ivar_size; } } if (WordsToScan > 0) { SKIP_SCAN SkScan; SkScan.skip = WordsToSkip; SkScan.scan = WordsToScan; SkipScanIvars.push_back(SkScan); ++SkipScan; } bool BytesSkipped = false; if (!SkipIvars.empty()) { int LastByteSkipped = SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size; int LastByteScanned = IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize; BytesSkipped = (LastByteSkipped > LastByteScanned); // Compute number of bytes to skip at the tail end of the last ivar scanned. if (BytesSkipped) { unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize; SKIP_SCAN SkScan; SkScan.skip = TotalWords - (LastByteScanned/WordSize); SkScan.scan = 0; SkipScanIvars.push_back(SkScan); ++SkipScan; } } // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced // as 0xMN. for (int i = 0; i <= SkipScan; i++) { if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) { // 0xM0 followed by 0x0N detected. SkipScanIvars[i].scan = SkipScanIvars[i+1].scan; for (int j = i+1; j < SkipScan; j++) SkipScanIvars[j] = SkipScanIvars[j+1]; --SkipScan; } } // Generate the string. std::string BitMap; for (int i = 0; i <= SkipScan; i++) { unsigned char byte; unsigned int skip_small = SkipScanIvars[i].skip % 0xf; unsigned int scan_small = SkipScanIvars[i].scan % 0xf; unsigned int skip_big = SkipScanIvars[i].skip / 0xf; unsigned int scan_big = SkipScanIvars[i].scan / 0xf; if (skip_small > 0 || skip_big > 0) BytesSkipped = true; // first skip big. for (unsigned int ix = 0; ix < skip_big; ix++) BitMap += (unsigned char)(0xf0); // next (skip small, scan) if (skip_small) { byte = skip_small << 4; if (scan_big > 0) { byte |= 0xf; --scan_big; } else if (scan_small) { byte |= scan_small; scan_small = 0; } BitMap += byte; } // next scan big for (unsigned int ix = 0; ix < scan_big; ix++) BitMap += (unsigned char)(0x0f); // last scan small if (scan_small) { byte = scan_small; BitMap += byte; } } // null terminate string. unsigned char zero = 0; BitMap += zero; // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as // final layout. if (ForStrongLayout && !BytesSkipped) return llvm::Constant::getNullValue(PtrTy); llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_", llvm::ConstantArray::get(BitMap.c_str()), "__TEXT,__cstring,cstring_literals", 1, true); // FIXME. Need a commomand-line option for this eventually. if (ForStrongLayout) printf("\nstrong ivar layout: "); else printf("\nweak ivar layout: "); const unsigned char *s = (unsigned char*)BitMap.c_str(); for (unsigned i = 0; i < BitMap.size(); i++) if (!(s[i] & 0xf0)) printf("0x0%x%s", s[i], s[i] != 0 ? ", " : ""); else printf("0x%x%s", s[i], s[i] != 0 ? ", " : ""); printf("\n"); return getConstantGEP(Entry, 0, 0); } llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) { llvm::GlobalVariable *&Entry = MethodVarNames[Sel]; // FIXME: Avoid std::string copying. if (!Entry) Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_", llvm::ConstantArray::get(Sel.getAsString()), "__TEXT,__cstring,cstring_literals", 1, true); return getConstantGEP(Entry, 0, 0); } // FIXME: Merge into a single cstring creation function. llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) { return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID)); } // FIXME: Merge into a single cstring creation function. llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) { return GetMethodVarName(&CGM.getContext().Idents.get(Name)); } llvm::Constant *CGObjCCommonMac::GetMethodVarType(FieldDecl *Field) { std::string TypeStr; CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field); llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; if (!Entry) Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_", llvm::ConstantArray::get(TypeStr), "__TEXT,__cstring,cstring_literals", 1, true); return getConstantGEP(Entry, 0, 0); } llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) { std::string TypeStr; CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D), TypeStr); llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; if (!Entry) Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_", llvm::ConstantArray::get(TypeStr), "__TEXT,__cstring,cstring_literals", 1, true); return getConstantGEP(Entry, 0, 0); } // FIXME: Merge into a single cstring creation function. llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) { llvm::GlobalVariable *&Entry = PropertyNames[Ident]; if (!Entry) Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_", llvm::ConstantArray::get(Ident->getName()), "__TEXT,__cstring,cstring_literals", 1, true); return getConstantGEP(Entry, 0, 0); } // FIXME: Merge into a single cstring creation function. // FIXME: This Decl should be more precise. llvm::Constant * CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD, const Decl *Container) { std::string TypeStr; CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr); return GetPropertyName(&CGM.getContext().Idents.get(TypeStr)); } void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D, const ObjCContainerDecl *CD, std::string &NameOut) { NameOut = '\01'; NameOut += (D->isInstanceMethod() ? '-' : '+'); NameOut += '['; assert (CD && "Missing container decl in GetNameForMethod"); NameOut += CD->getNameAsString(); // FIXME. For a method in a category, (CAT_NAME) is inserted here. // Right now! there is not enough info. to do this. NameOut += ' '; NameOut += D->getSelector().getAsString(); NameOut += ']'; } /// GetFirstIvarInRecord - This routine returns the record for the /// implementation of the fiven class OID. It also returns field /// corresponding to the first ivar in the class in FIV. It also /// returns the one before the first ivar. /// const RecordDecl *CGObjCCommonMac::GetFirstIvarInRecord( const ObjCInterfaceDecl *OID, RecordDecl::field_iterator &FIV, RecordDecl::field_iterator &PIV) { int countSuperClassIvars = countInheritedIvars(OID->getSuperClass(), CGM.getContext()); const RecordDecl *RD = CGM.getContext().addRecordToClass(OID); RecordDecl::field_iterator ifield = RD->field_begin(CGM.getContext()); RecordDecl::field_iterator pfield = RD->field_end(CGM.getContext()); while (countSuperClassIvars-- > 0) { pfield = ifield; ++ifield; } FIV = ifield; PIV = pfield; return RD; } void CGObjCMac::FinishModule() { EmitModuleInfo(); // Emit the dummy bodies for any protocols which were referenced but // never defined. for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator i = Protocols.begin(), e = Protocols.end(); i != e; ++i) { if (i->second->hasInitializer()) continue; std::vector<llvm::Constant*> Values(5); Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); Values[1] = GetClassName(i->first); Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); Values[3] = Values[4] = llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); i->second->setLinkage(llvm::GlobalValue::InternalLinkage); i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, Values)); } std::vector<llvm::Constant*> Used; for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), e = UsedGlobals.end(); i != e; ++i) { Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); } llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); llvm::GlobalValue *GV = new llvm::GlobalVariable(AT, false, llvm::GlobalValue::AppendingLinkage, llvm::ConstantArray::get(AT, Used), "llvm.used", &CGM.getModule()); GV->setSection("llvm.metadata"); // Add assembler directives to add lazy undefined symbol references // for classes which are referenced but not defined. This is // important for correct linker interaction. // FIXME: Uh, this isn't particularly portable. std::stringstream s; if (!CGM.getModule().getModuleInlineAsm().empty()) s << "\n"; for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(), e = LazySymbols.end(); i != e; ++i) { s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n"; } for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(), e = DefinedSymbols.end(); i != e; ++i) { s << "\t.objc_class_name_" << (*i)->getName() << "=0\n" << "\t.globl .objc_class_name_" << (*i)->getName() << "\n"; } CGM.getModule().appendModuleInlineAsm(s.str()); } CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), ObjCTypes(cgm) { ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL; ObjCABI = 2; } /* *** */ ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) : CGM(cgm) { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); ShortTy = Types.ConvertType(Ctx.ShortTy); IntTy = Types.ConvertType(Ctx.IntTy); LongTy = Types.ConvertType(Ctx.LongTy); LongLongTy = Types.ConvertType(Ctx.LongLongTy); Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType()); PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy); SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType()); // FIXME: It would be nice to unify this with the opaque type, so // that the IR comes out a bit cleaner. const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); // I'm not sure I like this. The implicit coordination is a bit // gross. We should solve this in a reasonable fashion because this // is a pretty common task (match some runtime data structure with // an LLVM data structure). // FIXME: This is leaked. // FIXME: Merge with rewriter code? // struct _objc_super { // id self; // Class cls; // } RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, SourceLocation(), &Ctx.Idents.get("_objc_super")); RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, Ctx.getObjCIdType(), 0, false)); RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, Ctx.getObjCClassType(), 0, false)); RD->completeDefinition(Ctx); SuperCTy = Ctx.getTagDeclType(RD); SuperPtrCTy = Ctx.getPointerType(SuperCTy); SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy)); SuperPtrTy = llvm::PointerType::getUnqual(SuperTy); // struct _prop_t { // char *name; // char *attributes; // } PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL); CGM.getModule().addTypeName("struct._prop_t", PropertyTy); // struct _prop_list_t { // uint32_t entsize; // sizeof(struct _prop_t) // uint32_t count_of_properties; // struct _prop_t prop_list[count_of_properties]; // } PropertyListTy = llvm::StructType::get(IntTy, IntTy, llvm::ArrayType::get(PropertyTy, 0), NULL); CGM.getModule().addTypeName("struct._prop_list_t", PropertyListTy); // struct _prop_list_t * PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); // struct _objc_method { // SEL _cmd; // char *method_type; // char *_imp; // } MethodTy = llvm::StructType::get(SelectorPtrTy, Int8PtrTy, Int8PtrTy, NULL); CGM.getModule().addTypeName("struct._objc_method", MethodTy); // struct _objc_cache * CacheTy = llvm::OpaqueType::get(); CGM.getModule().addTypeName("struct._objc_cache", CacheTy); CachePtrTy = llvm::PointerType::getUnqual(CacheTy); // Property manipulation functions. QualType IdType = Ctx.getObjCIdType(); QualType SelType = Ctx.getObjCSelType(); llvm::SmallVector<QualType,16> Params; const llvm::FunctionType *FTy; // id objc_getProperty (id, SEL, ptrdiff_t, bool) Params.push_back(IdType); Params.push_back(SelType); Params.push_back(Ctx.LongTy); Params.push_back(Ctx.BoolTy); FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false); GetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_getProperty"); // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) Params.clear(); Params.push_back(IdType); Params.push_back(SelType); Params.push_back(Ctx.LongTy); Params.push_back(IdType); Params.push_back(Ctx.BoolTy); Params.push_back(Ctx.BoolTy); FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); SetPropertyFn = CGM.CreateRuntimeFunction(FTy, "objc_setProperty"); // Enumeration mutation. // void objc_enumerationMutation (id) Params.clear(); Params.push_back(IdType); FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); EnumerationMutationFn = CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation"); // gc's API // id objc_read_weak (id *) Params.clear(); Params.push_back(Ctx.getPointerType(IdType)); FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false); GcReadWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_read_weak"); // id objc_assign_weak (id, id *) Params.clear(); Params.push_back(IdType); Params.push_back(Ctx.getPointerType(IdType)); FTy = Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false); GcAssignWeakFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_weak"); GcAssignGlobalFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_global"); GcAssignIvarFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar"); GcAssignStrongCastFn = CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast"); // void objc_exception_throw(id) Params.clear(); Params.push_back(IdType); FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); ExceptionThrowFn = CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); // synchronized APIs // void objc_sync_exit (id) Params.clear(); Params.push_back(IdType); FTy = Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); SyncExitFn = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); } ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) : ObjCCommonTypesHelper(cgm) { // struct _objc_method_description { // SEL name; // char *types; // } MethodDescriptionTy = llvm::StructType::get(SelectorPtrTy, Int8PtrTy, NULL); CGM.getModule().addTypeName("struct._objc_method_description", MethodDescriptionTy); // struct _objc_method_description_list { // int count; // struct _objc_method_description[1]; // } MethodDescriptionListTy = llvm::StructType::get(IntTy, llvm::ArrayType::get(MethodDescriptionTy, 0), NULL); CGM.getModule().addTypeName("struct._objc_method_description_list", MethodDescriptionListTy); // struct _objc_method_description_list * MethodDescriptionListPtrTy = llvm::PointerType::getUnqual(MethodDescriptionListTy); // Protocol description structures // struct _objc_protocol_extension { // uint32_t size; // sizeof(struct _objc_protocol_extension) // struct _objc_method_description_list *optional_instance_methods; // struct _objc_method_description_list *optional_class_methods; // struct _objc_property_list *instance_properties; // } ProtocolExtensionTy = llvm::StructType::get(IntTy, MethodDescriptionListPtrTy, MethodDescriptionListPtrTy, PropertyListPtrTy, NULL); CGM.getModule().addTypeName("struct._objc_protocol_extension", ProtocolExtensionTy); // struct _objc_protocol_extension * ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); // Handle recursive construction of Protocol and ProtocolList types llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get(); llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); const llvm::Type *T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder), LongTy, llvm::ArrayType::get(ProtocolTyHolder, 0), NULL); cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T); // struct _objc_protocol { // struct _objc_protocol_extension *isa; // char *protocol_name; // struct _objc_protocol **_objc_protocol_list; // struct _objc_method_description_list *instance_methods; // struct _objc_method_description_list *class_methods; // } T = llvm::StructType::get(ProtocolExtensionPtrTy, Int8PtrTy, llvm::PointerType::getUnqual(ProtocolListTyHolder), MethodDescriptionListPtrTy, MethodDescriptionListPtrTy, NULL); cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T); ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get()); CGM.getModule().addTypeName("struct._objc_protocol_list", ProtocolListTy); // struct _objc_protocol_list * ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get()); CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy); ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy); // Class description structures // struct _objc_ivar { // char *ivar_name; // char *ivar_type; // int ivar_offset; // } IvarTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, IntTy, NULL); CGM.getModule().addTypeName("struct._objc_ivar", IvarTy); // struct _objc_ivar_list * IvarListTy = llvm::OpaqueType::get(); CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy); IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy); // struct _objc_method_list * MethodListTy = llvm::OpaqueType::get(); CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy); MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); // struct _objc_class_extension * ClassExtensionTy = llvm::StructType::get(IntTy, Int8PtrTy, PropertyListPtrTy, NULL); CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy); ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); // struct _objc_class { // Class isa; // Class super_class; // char *name; // long version; // long info; // long instance_size; // struct _objc_ivar_list *ivars; // struct _objc_method_list *methods; // struct _objc_cache *cache; // struct _objc_protocol_list *protocols; // char *ivar_layout; // struct _objc_class_ext *ext; // }; T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), llvm::PointerType::getUnqual(ClassTyHolder), Int8PtrTy, LongTy, LongTy, LongTy, IvarListPtrTy, MethodListPtrTy, CachePtrTy, ProtocolListPtrTy, Int8PtrTy, ClassExtensionPtrTy, NULL); cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T); ClassTy = cast<llvm::StructType>(ClassTyHolder.get()); CGM.getModule().addTypeName("struct._objc_class", ClassTy); ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); // struct _objc_category { // char *category_name; // char *class_name; // struct _objc_method_list *instance_method; // struct _objc_method_list *class_method; // uint32_t size; // sizeof(struct _objc_category) // struct _objc_property_list *instance_properties;// category's @property // } CategoryTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, MethodListPtrTy, MethodListPtrTy, ProtocolListPtrTy, IntTy, PropertyListPtrTy, NULL); CGM.getModule().addTypeName("struct._objc_category", CategoryTy); // Global metadata structures // struct _objc_symtab { // long sel_ref_cnt; // SEL *refs; // short cls_def_cnt; // short cat_def_cnt; // char *defs[cls_def_cnt + cat_def_cnt]; // } SymtabTy = llvm::StructType::get(LongTy, SelectorPtrTy, ShortTy, ShortTy, llvm::ArrayType::get(Int8PtrTy, 0), NULL); CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy); SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); // struct _objc_module { // long version; // long size; // sizeof(struct _objc_module) // char *name; // struct _objc_symtab* symtab; // } ModuleTy = llvm::StructType::get(LongTy, LongTy, Int8PtrTy, SymtabPtrTy, NULL); CGM.getModule().addTypeName("struct._objc_module", ModuleTy); // Message send functions. // id objc_msgSend (id, SEL, ...) std::vector<const llvm::Type*> Params; Params.push_back(ObjectPtrTy); Params.push_back(SelectorPtrTy); MessageSendFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, true), "objc_msgSend"); // id objc_msgSend_stret (id, SEL, ...) Params.clear(); Params.push_back(ObjectPtrTy); Params.push_back(SelectorPtrTy); MessageSendStretFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, Params, true), "objc_msgSend_stret"); // Params.clear(); Params.push_back(ObjectPtrTy); Params.push_back(SelectorPtrTy); // FIXME: This should be long double on x86_64? // [double | long double] objc_msgSend_fpret(id self, SEL op, ...) MessageSendFpretFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy, Params, true), "objc_msgSend_fpret"); // id objc_msgSendSuper(struct objc_super *super, SEL op, ...) Params.clear(); Params.push_back(SuperPtrTy); Params.push_back(SelectorPtrTy); MessageSendSuperFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, true), "objc_msgSendSuper"); // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super, // SEL op, ...) Params.clear(); Params.push_back(Int8PtrTy); Params.push_back(SuperPtrTy); Params.push_back(SelectorPtrTy); MessageSendSuperStretFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, Params, true), "objc_msgSendSuper_stret"); // There is no objc_msgSendSuper_fpret? How can that work? MessageSendSuperFpretFn = MessageSendSuperFn; // FIXME: This is the size of the setjmp buffer and should be // target specific. 18 is what's used on 32-bit X86. uint64_t SetJmpBufferSize = 18; // Exceptions const llvm::Type *StackPtrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4); ExceptionDataTy = llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty, SetJmpBufferSize), StackPtrTy, NULL); CGM.getModule().addTypeName("struct._objc_exception_data", ExceptionDataTy); Params.clear(); Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy)); ExceptionTryEnterFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, Params, false), "objc_exception_try_enter"); ExceptionTryExitFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, Params, false), "objc_exception_try_exit"); ExceptionExtractFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, false), "objc_exception_extract"); Params.clear(); Params.push_back(ClassPtrTy); Params.push_back(ObjectPtrTy); ExceptionMatchFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, Params, false), "objc_exception_match"); Params.clear(); Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty)); SetJmpFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, Params, false), "_setjmp"); } ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) : ObjCCommonTypesHelper(cgm) { // struct _method_list_t { // uint32_t entsize; // sizeof(struct _objc_method) // uint32_t method_count; // struct _objc_method method_list[method_count]; // } MethodListnfABITy = llvm::StructType::get(IntTy, IntTy, llvm::ArrayType::get(MethodTy, 0), NULL); CGM.getModule().addTypeName("struct.__method_list_t", MethodListnfABITy); // struct method_list_t * MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy); // struct _protocol_t { // id isa; // NULL // const char * const protocol_name; // const struct _protocol_list_t * protocol_list; // super protocols // const struct method_list_t * const instance_methods; // const struct method_list_t * const class_methods; // const struct method_list_t *optionalInstanceMethods; // const struct method_list_t *optionalClassMethods; // const struct _prop_list_t * properties; // const uint32_t size; // sizeof(struct _protocol_t) // const uint32_t flags; // = 0 // } // Holder for struct _protocol_list_t * llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy, Int8PtrTy, llvm::PointerType::getUnqual( ProtocolListTyHolder), MethodListnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy, PropertyListPtrTy, IntTy, IntTy, NULL); CGM.getModule().addTypeName("struct._protocol_t", ProtocolnfABITy); // struct _protocol_t* ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy); // struct _protocol_list_t { // long protocol_count; // Note, this is 32/64 bit // struct _protocol_t *[protocol_count]; // } ProtocolListnfABITy = llvm::StructType::get(LongTy, llvm::ArrayType::get( ProtocolnfABIPtrTy, 0), NULL); CGM.getModule().addTypeName("struct._objc_protocol_list", ProtocolListnfABITy); cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo( ProtocolListnfABITy); // struct _objc_protocol_list* ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy); // struct _ivar_t { // unsigned long int *offset; // pointer to ivar offset location // char *name; // char *type; // uint32_t alignment; // uint32_t size; // } IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy), Int8PtrTy, Int8PtrTy, IntTy, IntTy, NULL); CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy); // struct _ivar_list_t { // uint32 entsize; // sizeof(struct _ivar_t) // uint32 count; // struct _iver_t list[count]; // } IvarListnfABITy = llvm::StructType::get(IntTy, IntTy, llvm::ArrayType::get( IvarnfABITy, 0), NULL); CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy); IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy); // struct _class_ro_t { // uint32_t const flags; // uint32_t const instanceStart; // uint32_t const instanceSize; // uint32_t const reserved; // only when building for 64bit targets // const uint8_t * const ivarLayout; // const char *const name; // const struct _method_list_t * const baseMethods; // const struct _objc_protocol_list *const baseProtocols; // const struct _ivar_list_t *const ivars; // const uint8_t * const weakIvarLayout; // const struct _prop_list_t * const properties; // } // FIXME. Add 'reserved' field in 64bit abi mode! ClassRonfABITy = llvm::StructType::get(IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy, MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy, Int8PtrTy, PropertyListPtrTy, NULL); CGM.getModule().addTypeName("struct._class_ro_t", ClassRonfABITy); // ImpnfABITy - LLVM for id (*)(id, SEL, ...) std::vector<const llvm::Type*> Params; Params.push_back(ObjectPtrTy); Params.push_back(SelectorPtrTy); ImpnfABITy = llvm::PointerType::getUnqual( llvm::FunctionType::get(ObjectPtrTy, Params, false)); // struct _class_t { // struct _class_t *isa; // struct _class_t * const superclass; // void *cache; // IMP *vtable; // struct class_ro_t *ro; // } llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), llvm::PointerType::getUnqual(ClassTyHolder), CachePtrTy, llvm::PointerType::getUnqual(ImpnfABITy), llvm::PointerType::getUnqual( ClassRonfABITy), NULL); CGM.getModule().addTypeName("struct._class_t", ClassnfABITy); cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo( ClassnfABITy); // LLVM for struct _class_t * ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy); // struct _category_t { // const char * const name; // struct _class_t *const cls; // const struct _method_list_t * const instance_methods; // const struct _method_list_t * const class_methods; // const struct _protocol_list_t * const protocols; // const struct _prop_list_t * const properties; // } CategorynfABITy = llvm::StructType::get(Int8PtrTy, ClassnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, PropertyListPtrTy, NULL); CGM.getModule().addTypeName("struct._category_t", CategorynfABITy); // New types for nonfragile abi messaging. CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); // MessageRefTy - LLVM for: // struct _message_ref_t { // IMP messenger; // SEL name; // }; // First the clang type for struct _message_ref_t RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, SourceLocation(), &Ctx.Idents.get("_message_ref_t")); RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, Ctx.VoidPtrTy, 0, false)); RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, Ctx.getObjCSelType(), 0, false)); RD->completeDefinition(Ctx); MessageRefCTy = Ctx.getTagDeclType(RD); MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy); MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy)); // MessageRefPtrTy - LLVM for struct _message_ref_t* MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy); // SuperMessageRefTy - LLVM for: // struct _super_message_ref_t { // SUPER_IMP messenger; // SEL name; // }; SuperMessageRefTy = llvm::StructType::get(ImpnfABITy, SelectorPtrTy, NULL); CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy); // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy); // id objc_msgSend_fixup (id, struct message_ref_t*, ...) Params.clear(); Params.push_back(ObjectPtrTy); Params.push_back(MessageRefPtrTy); MessengerTy = llvm::FunctionType::get(ObjectPtrTy, Params, true); MessageSendFixupFn = CGM.CreateRuntimeFunction(MessengerTy, "objc_msgSend_fixup"); // id objc_msgSend_fpret_fixup (id, struct message_ref_t*, ...) MessageSendFpretFixupFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, true), "objc_msgSend_fpret_fixup"); // id objc_msgSend_stret_fixup (id, struct message_ref_t*, ...) MessageSendStretFixupFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, true), "objc_msgSend_stret_fixup"); // id objc_msgSendId_fixup (id, struct message_ref_t*, ...) MessageSendIdFixupFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, true), "objc_msgSendId_fixup"); // id objc_msgSendId_stret_fixup (id, struct message_ref_t*, ...) MessageSendIdStretFixupFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, true), "objc_msgSendId_stret_fixup"); // id objc_msgSendSuper2_fixup (struct objc_super *, // struct _super_message_ref_t*, ...) Params.clear(); Params.push_back(SuperPtrTy); Params.push_back(SuperMessageRefPtrTy); MessageSendSuper2FixupFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, true), "objc_msgSendSuper2_fixup"); // id objc_msgSendSuper2_stret_fixup (struct objc_super *, // struct _super_message_ref_t*, ...) MessageSendSuper2StretFixupFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, Params, true), "objc_msgSendSuper2_stret_fixup"); Params.clear(); Params.push_back(Int8PtrTy); UnwindResumeOrRethrowFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, Params, false), "_Unwind_Resume_or_Rethrow"); ObjCBeginCatchFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy, Params, false), "objc_begin_catch"); Params.clear(); ObjCEndCatchFn = CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, Params, false), "objc_end_catch"); // struct objc_typeinfo { // const void** vtable; // objc_ehtype_vtable + 2 // const char* name; // c++ typeinfo string // Class cls; // }; EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy), Int8PtrTy, ClassnfABIPtrTy, NULL); CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy); EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy); } llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() { FinishNonFragileABIModule(); return NULL; } void CGObjCNonFragileABIMac::FinishNonFragileABIModule() { // nonfragile abi has no module definition. // Build list of all implemented classe addresses in array // L_OBJC_LABEL_CLASS_$. // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$ // list of 'nonlazy' implementations (defined as those with a +load{} // method!!). unsigned NumClasses = DefinedClasses.size(); if (NumClasses) { std::vector<llvm::Constant*> Symbols(NumClasses); for (unsigned i=0; i<NumClasses; i++) Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], ObjCTypes.Int8PtrTy); llvm::Constant* Init = llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, NumClasses), Symbols); llvm::GlobalVariable *GV = new llvm::GlobalVariable(Init->getType(), false, llvm::GlobalValue::InternalLinkage, Init, "\01L_OBJC_LABEL_CLASS_$", &CGM.getModule()); GV->setAlignment(8); GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip"); UsedGlobals.push_back(GV); } // Build list of all implemented category addresses in array // L_OBJC_LABEL_CATEGORY_$. // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$ // list of 'nonlazy' category implementations (defined as those with a +load{} // method!!). unsigned NumCategory = DefinedCategories.size(); if (NumCategory) { std::vector<llvm::Constant*> Symbols(NumCategory); for (unsigned i=0; i<NumCategory; i++) Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i], ObjCTypes.Int8PtrTy); llvm::Constant* Init = llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, NumCategory), Symbols); llvm::GlobalVariable *GV = new llvm::GlobalVariable(Init->getType(), false, llvm::GlobalValue::InternalLinkage, Init, "\01L_OBJC_LABEL_CATEGORY_$", &CGM.getModule()); GV->setAlignment(8); GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip"); UsedGlobals.push_back(GV); } // static int L_OBJC_IMAGE_INFO[2] = { 0, flags }; // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0 std::vector<llvm::Constant*> Values(2); Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0); unsigned int flags = 0; // FIXME: Fix and continue? if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) flags |= eImageInfo_GarbageCollected; if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) flags |= eImageInfo_GCOnly; Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags); llvm::Constant* Init = llvm::ConstantArray::get( llvm::ArrayType::get(ObjCTypes.IntTy, 2), Values); llvm::GlobalVariable *IMGV = new llvm::GlobalVariable(Init->getType(), false, llvm::GlobalValue::InternalLinkage, Init, "\01L_OBJC_IMAGE_INFO", &CGM.getModule()); IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip"); UsedGlobals.push_back(IMGV); std::vector<llvm::Constant*> Used; for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), e = UsedGlobals.end(); i != e; ++i) { Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); } llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); llvm::GlobalValue *GV = new llvm::GlobalVariable(AT, false, llvm::GlobalValue::AppendingLinkage, llvm::ConstantArray::get(AT, Used), "llvm.used", &CGM.getModule()); GV->setSection("llvm.metadata"); } // Metadata flags enum MetaDataDlags { CLS = 0x0, CLS_META = 0x1, CLS_ROOT = 0x2, OBJC2_CLS_HIDDEN = 0x10, CLS_EXCEPTION = 0x20 }; /// BuildClassRoTInitializer - generate meta-data for: /// struct _class_ro_t { /// uint32_t const flags; /// uint32_t const instanceStart; /// uint32_t const instanceSize; /// uint32_t const reserved; // only when building for 64bit targets /// const uint8_t * const ivarLayout; /// const char *const name; /// const struct _method_list_t * const baseMethods; /// const struct _protocol_list_t *const baseProtocols; /// const struct _ivar_list_t *const ivars; /// const uint8_t * const weakIvarLayout; /// const struct _prop_list_t * const properties; /// } /// llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer( unsigned flags, unsigned InstanceStart, unsigned InstanceSize, const ObjCImplementationDecl *ID) { std::string ClassName = ID->getNameAsString(); std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets! Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags); Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart); Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize); // FIXME. For 64bit targets add 0 here. // FIXME. ivarLayout is currently null! Values[ 3] = GetIvarLayoutName(0, ObjCTypes); Values[ 4] = GetClassName(ID->getIdentifier()); // const struct _method_list_t * const baseMethods; std::vector<llvm::Constant*> Methods; std::string MethodListName("\01l_OBJC_$_"); if (flags & CLS_META) { MethodListName += "CLASS_METHODS_" + ID->getNameAsString(); for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) { // Class methods should always be defined. Methods.push_back(GetMethodConstant(*i)); } } else { MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString(); for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) { // Instance methods should always be defined. Methods.push_back(GetMethodConstant(*i)); } for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) { ObjCPropertyImplDecl *PID = *i; if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){ ObjCPropertyDecl *PD = PID->getPropertyDecl(); if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) if (llvm::Constant *C = GetMethodConstant(MD)) Methods.push_back(C); if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) if (llvm::Constant *C = GetMethodConstant(MD)) Methods.push_back(C); } } } Values[ 5] = EmitMethodList(MethodListName, "__DATA, __objc_const", Methods); const ObjCInterfaceDecl *OID = ID->getClassInterface(); assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer"); Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_" + OID->getNameAsString(), OID->protocol_begin(), OID->protocol_end()); if (flags & CLS_META) Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); else Values[ 7] = EmitIvarList(ID); // FIXME. weakIvarLayout is currently null. Values[ 8] = GetIvarLayoutName(0, ObjCTypes); if (flags & CLS_META) Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); else Values[ 9] = EmitPropertyList( "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(), ID, ID->getClassInterface(), ObjCTypes); llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy, Values); llvm::GlobalVariable *CLASS_RO_GV = new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false, llvm::GlobalValue::InternalLinkage, Init, (flags & CLS_META) ? std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName : std::string("\01l_OBJC_CLASS_RO_$_")+ClassName, &CGM.getModule()); CLASS_RO_GV->setAlignment( CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy)); CLASS_RO_GV->setSection("__DATA, __objc_const"); return CLASS_RO_GV; } /// BuildClassMetaData - This routine defines that to-level meta-data /// for the given ClassName for: /// struct _class_t { /// struct _class_t *isa; /// struct _class_t * const superclass; /// void *cache; /// IMP *vtable; /// struct class_ro_t *ro; /// } /// llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData( std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV, llvm::Constant *ClassRoGV, bool HiddenVisibility) { std::vector<llvm::Constant*> Values(5); Values[0] = IsAGV; Values[1] = SuperClassGV ? SuperClassGV : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy); Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar Values[4] = ClassRoGV; // &CLASS_RO_GV llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy, Values); llvm::GlobalVariable *GV = GetClassGlobal(ClassName); GV->setInitializer(Init); GV->setSection("__DATA, __objc_data"); GV->setAlignment( CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy)); if (HiddenVisibility) GV->setVisibility(llvm::GlobalValue::HiddenVisibility); return GV; } void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) { std::string ClassName = ID->getNameAsString(); if (!ObjCEmptyCacheVar) { ObjCEmptyCacheVar = new llvm::GlobalVariable( ObjCTypes.CacheTy, false, llvm::GlobalValue::ExternalLinkage, 0, "_objc_empty_cache", &CGM.getModule()); ObjCEmptyVtableVar = new llvm::GlobalVariable( ObjCTypes.ImpnfABITy, false, llvm::GlobalValue::ExternalLinkage, 0, "_objc_empty_vtable", &CGM.getModule()); } assert(ID->getClassInterface() && "CGObjCNonFragileABIMac::GenerateClass - class is 0"); uint32_t InstanceStart = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy); uint32_t InstanceSize = InstanceStart; uint32_t flags = CLS_META; std::string ObjCMetaClassName(getMetaclassSymbolPrefix()); std::string ObjCClassName(getClassSymbolPrefix()); llvm::GlobalVariable *SuperClassGV, *IsAGV; bool classIsHidden = CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; if (!ID->getClassInterface()->getSuperClass()) { // class is root flags |= CLS_ROOT; SuperClassGV = GetClassGlobal(ObjCClassName + ClassName); IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName); } else { // Has a root. Current class is not a root. const ObjCInterfaceDecl *Root = ID->getClassInterface(); while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) Root = Super; IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString()); // work on super class metadata symbol. std::string SuperClassName = ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString(); SuperClassGV = GetClassGlobal(SuperClassName); } llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags, InstanceStart, InstanceSize,ID); std::string TClassName = ObjCMetaClassName + ClassName; llvm::GlobalVariable *MetaTClass = BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden); // Metadata for the class flags = CLS; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; if (hasObjCExceptionAttribute(ID->getClassInterface())) flags |= CLS_EXCEPTION; if (!ID->getClassInterface()->getSuperClass()) { flags |= CLS_ROOT; SuperClassGV = 0; } else { // Has a root. Current class is not a root. std::string RootClassName = ID->getClassInterface()->getSuperClass()->getNameAsString(); SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName); } // FIXME: Gross InstanceStart = InstanceSize = 0; if (ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(ID->getClassInterface())) { // FIXME. Share this with the one in EmitIvarList. const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID); RecordDecl::field_iterator firstField, lastField; const RecordDecl *RD = GetFirstIvarInRecord(OID, firstField, lastField); for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()), ifield = firstField; ifield != e; ++ifield) lastField = ifield; if (lastField != RD->field_end(CGM.getContext())) { FieldDecl *Field = *lastField; const llvm::Type *FieldTy = CGM.getTypes().ConvertTypeForMem(Field->getType()); unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy); InstanceSize = GetIvarBaseOffset(Layout, Field) + Size; if (firstField == RD->field_end(CGM.getContext())) InstanceStart = InstanceSize; else { Field = *firstField; InstanceStart = GetIvarBaseOffset(Layout, Field); } } } CLASS_RO_GV = BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID); TClassName = ObjCClassName + ClassName; llvm::GlobalVariable *ClassMD = BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV, classIsHidden); DefinedClasses.push_back(ClassMD); // Force the definition of the EHType if necessary. if (flags & CLS_EXCEPTION) GetInterfaceEHType(ID->getClassInterface(), true); } /// GenerateProtocolRef - This routine is called to generate code for /// a protocol reference expression; as in: /// @code /// @protocol(Proto1); /// @endcode /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1 /// which will hold address of the protocol meta-data. /// llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder, const ObjCProtocolDecl *PD) { // This routine is called for @protocol only. So, we must build definition // of protocol's meta-data (not a reference to it!) // llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD), ObjCTypes.ExternalProtocolPtrTy); std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_"); ProtocolName += PD->getNameAsCString(); llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName); if (PTGV) return Builder.CreateLoad(PTGV, false, "tmp"); PTGV = new llvm::GlobalVariable( Init->getType(), false, llvm::GlobalValue::WeakAnyLinkage, Init, ProtocolName, &CGM.getModule()); PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip"); PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); UsedGlobals.push_back(PTGV); return Builder.CreateLoad(PTGV, false, "tmp"); } /// GenerateCategory - Build metadata for a category implementation. /// struct _category_t { /// const char * const name; /// struct _class_t *const cls; /// const struct _method_list_t * const instance_methods; /// const struct _method_list_t * const class_methods; /// const struct _protocol_list_t * const protocols; /// const struct _prop_list_t * const properties; /// } /// void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); const char *Prefix = "\01l_OBJC_$_CATEGORY_"; std::string ExtCatName(Prefix + Interface->getNameAsString()+ "_$_" + OCD->getNameAsString()); std::string ExtClassName(getClassSymbolPrefix() + Interface->getNameAsString()); std::vector<llvm::Constant*> Values(6); Values[0] = GetClassName(OCD->getIdentifier()); // meta-class entry symbol llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName); Values[1] = ClassGV; std::vector<llvm::Constant*> Methods; std::string MethodListName(Prefix); MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() + "_$_" + OCD->getNameAsString(); for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) { // Instance methods should always be defined. Methods.push_back(GetMethodConstant(*i)); } Values[2] = EmitMethodList(MethodListName, "__DATA, __objc_const", Methods); MethodListName = Prefix; MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" + OCD->getNameAsString(); Methods.clear(); for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) { // Class methods should always be defined. Methods.push_back(GetMethodConstant(*i)); } Values[3] = EmitMethodList(MethodListName, "__DATA, __objc_const", Methods); const ObjCCategoryDecl *Category = Interface->FindCategoryDeclaration(OCD->getIdentifier()); if (Category) { std::string ExtName(Interface->getNameAsString() + "_$_" + OCD->getNameAsString()); Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_" + Interface->getNameAsString() + "_$_" + Category->getNameAsString(), Category->protocol_begin(), Category->protocol_end()); Values[5] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName, OCD, Category, ObjCTypes); } else { Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); } llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy, Values); llvm::GlobalVariable *GCATV = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy, false, llvm::GlobalValue::InternalLinkage, Init, ExtCatName, &CGM.getModule()); GCATV->setAlignment( CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy)); GCATV->setSection("__DATA, __objc_const"); UsedGlobals.push_back(GCATV); DefinedCategories.push_back(GCATV); } /// GetMethodConstant - Return a struct objc_method constant for the /// given method if it has been defined. The result is null if the /// method has not been defined. The return value has type MethodPtrTy. llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant( const ObjCMethodDecl *MD) { // FIXME: Use DenseMap::lookup llvm::Function *Fn = MethodDefinitions[MD]; if (!Fn) return 0; std::vector<llvm::Constant*> Method(3); Method[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), ObjCTypes.SelectorPtrTy); Method[1] = GetMethodVarType(MD); Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); } /// EmitMethodList - Build meta-data for method declarations /// struct _method_list_t { /// uint32_t entsize; // sizeof(struct _objc_method) /// uint32_t method_count; /// struct _objc_method method_list[method_count]; /// } /// llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList( const std::string &Name, const char *Section, const ConstantVector &Methods) { // Return null for empty list. if (Methods.empty()) return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy); std::vector<llvm::Constant*> Values(3); // sizeof(struct _objc_method) unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy); Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); // method_count Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, Methods.size()); Values[2] = llvm::ConstantArray::get(AT, Methods); llvm::Constant *Init = llvm::ConstantStruct::get(Values); llvm::GlobalVariable *GV = new llvm::GlobalVariable(Init->getType(), false, llvm::GlobalValue::InternalLinkage, Init, Name, &CGM.getModule()); GV->setAlignment( CGM.getTargetData().getPrefTypeAlignment(Init->getType())); GV->setSection(Section); UsedGlobals.push_back(GV); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy); } /// ObjCIvarOffsetVariable - Returns the ivar offset variable for /// the given ivar. /// llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable( std::string &Name, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar) { Name += "OBJC_IVAR_$_" + getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() + '.' + Ivar->getNameAsString(); llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name); if (!IvarOffsetGV) IvarOffsetGV = new llvm::GlobalVariable(ObjCTypes.LongTy, false, llvm::GlobalValue::ExternalLinkage, 0, Name, &CGM.getModule()); return IvarOffsetGV; } llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar( const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar, unsigned long int Offset) { assert(ID && "EmitIvarOffsetVar - null interface decl."); std::string ExternalName("OBJC_IVAR_$_" + ID->getNameAsString() + '.' + Ivar->getNameAsString()); llvm::Constant *Init = llvm::ConstantInt::get(ObjCTypes.LongTy, Offset); llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(ExternalName); if (IvarOffsetGV) // ivar offset symbol already built due to user code referencing it. IvarOffsetGV->setInitializer(Init); else IvarOffsetGV = new llvm::GlobalVariable(Init->getType(), false, llvm::GlobalValue::ExternalLinkage, Init, ExternalName, &CGM.getModule()); IvarOffsetGV->setAlignment( CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy)); // @private and @package have hidden visibility. bool globalVisibility = (Ivar->getAccessControl() == ObjCIvarDecl::Public || Ivar->getAccessControl() == ObjCIvarDecl::Protected); if (!globalVisibility || CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden) IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility); else IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility); IvarOffsetGV->setSection("__DATA, __objc_const"); return IvarOffsetGV; } /// EmitIvarList - Emit the ivar list for the given /// implementation. If ForClass is true the list of class ivars /// (i.e. metaclass ivars) is emitted, otherwise the list of /// interface ivars will be emitted. The return value has type /// IvarListnfABIPtrTy. /// struct _ivar_t { /// unsigned long int *offset; // pointer to ivar offset location /// char *name; /// char *type; /// uint32_t alignment; /// uint32_t size; /// } /// struct _ivar_list_t { /// uint32 entsize; // sizeof(struct _ivar_t) /// uint32 count; /// struct _iver_t list[count]; /// } /// llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList( const ObjCImplementationDecl *ID) { std::vector<llvm::Constant*> Ivars, Ivar(5); const ObjCInterfaceDecl *OID = ID->getClassInterface(); assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface"); // FIXME. Consolidate this with similar code in GenerateClass. const llvm::StructLayout *Layout = GetInterfaceDeclStructLayout(OID); RecordDecl::field_iterator i,p; const RecordDecl *RD = GetFirstIvarInRecord(OID, i,p); // collect declared and synthesized ivars in a small vector. llvm::SmallVector<ObjCIvarDecl*, 16> OIvars; for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(), E = OID->ivar_end(); I != E; ++I) OIvars.push_back(*I); for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()), E = OID->prop_end(CGM.getContext()); I != E; ++I) if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl()) OIvars.push_back(IV); unsigned iv = 0; for (RecordDecl::field_iterator e = RD->field_end(CGM.getContext()); i != e; ++i) { FieldDecl *Field = *i; uint64_t offset = GetIvarBaseOffset(Layout, Field); Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), OIvars[iv++], offset); if (Field->getIdentifier()) Ivar[1] = GetMethodVarName(Field->getIdentifier()); else Ivar[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); Ivar[2] = GetMethodVarType(Field); const llvm::Type *FieldTy = CGM.getTypes().ConvertTypeForMem(Field->getType()); unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy); unsigned Align = CGM.getContext().getPreferredTypeAlign( Field->getType().getTypePtr()) >> 3; Align = llvm::Log2_32(Align); Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align); // NOTE. Size of a bitfield does not match gcc's, because of the way // bitfields are treated special in each. But I am told that 'size' // for bitfield ivars is ignored by the runtime so it does not matter. // (even if it matters, some day, there is enough info. to get the bitfield // right! Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar)); } // Return null for empty list. if (Ivars.empty()) return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); std::vector<llvm::Constant*> Values(3); unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy); Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy, Ivars.size()); Values[2] = llvm::ConstantArray::get(AT, Ivars); llvm::Constant *Init = llvm::ConstantStruct::get(Values); const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_"; llvm::GlobalVariable *GV = new llvm::GlobalVariable(Init->getType(), false, llvm::GlobalValue::InternalLinkage, Init, Prefix + OID->getNameAsString(), &CGM.getModule()); GV->setAlignment( CGM.getTargetData().getPrefTypeAlignment(Init->getType())); GV->setSection("__DATA, __objc_const"); UsedGlobals.push_back(GV); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy); } llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef( const ObjCProtocolDecl *PD) { llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; if (!Entry) { // We use the initializer as a marker of whether this is a forward // reference or not. At module finalization we add the empty // contents for protocols which were referenced but never defined. Entry = new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false, llvm::GlobalValue::ExternalLinkage, 0, "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(), &CGM.getModule()); Entry->setSection("__DATA,__datacoal_nt,coalesced"); UsedGlobals.push_back(Entry); } return Entry; } /// GetOrEmitProtocol - Generate the protocol meta-data: /// @code /// struct _protocol_t { /// id isa; // NULL /// const char * const protocol_name; /// const struct _protocol_list_t * protocol_list; // super protocols /// const struct method_list_t * const instance_methods; /// const struct method_list_t * const class_methods; /// const struct method_list_t *optionalInstanceMethods; /// const struct method_list_t *optionalClassMethods; /// const struct _prop_list_t * properties; /// const uint32_t size; // sizeof(struct _protocol_t) /// const uint32_t flags; // = 0 /// } /// @endcode /// llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( const ObjCProtocolDecl *PD) { llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; // Early exit if a defining object has already been generated. if (Entry && Entry->hasInitializer()) return Entry; const char *ProtocolName = PD->getNameAsCString(); // Construct method lists. std::vector<llvm::Constant*> InstanceMethods, ClassMethods; std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(CGM.getContext()), e = PD->instmeth_end(CGM.getContext()); i != e; ++i) { ObjCMethodDecl *MD = *i; llvm::Constant *C = GetMethodDescriptionConstant(MD); if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptInstanceMethods.push_back(C); } else { InstanceMethods.push_back(C); } } for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(CGM.getContext()), e = PD->classmeth_end(CGM.getContext()); i != e; ++i) { ObjCMethodDecl *MD = *i; llvm::Constant *C = GetMethodDescriptionConstant(MD); if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptClassMethods.push_back(C); } else { ClassMethods.push_back(C); } } std::vector<llvm::Constant*> Values(10); // isa is NULL Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy); Values[1] = GetClassName(PD->getIdentifier()); Values[2] = EmitProtocolList( "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(), PD->protocol_begin(), PD->protocol_end()); Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_" + PD->getNameAsString(), "__DATA, __objc_const", InstanceMethods); Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_" + PD->getNameAsString(), "__DATA, __objc_const", ClassMethods); Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_" + PD->getNameAsString(), "__DATA, __objc_const", OptInstanceMethods); Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_" + PD->getNameAsString(), "__DATA, __objc_const", OptClassMethods); Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(), 0, PD, ObjCTypes); uint32_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy); Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy); llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy, Values); if (Entry) { // Already created, fix the linkage and update the initializer. Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage); Entry->setInitializer(Init); } else { Entry = new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false, llvm::GlobalValue::WeakAnyLinkage, Init, std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName, &CGM.getModule()); Entry->setAlignment( CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy)); Entry->setSection("__DATA,__datacoal_nt,coalesced"); } Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); // Use this protocol meta-data to build protocol list table in section // __DATA, __objc_protolist llvm::GlobalVariable *PTGV = new llvm::GlobalVariable( ObjCTypes.ProtocolnfABIPtrTy, false, llvm::GlobalValue::WeakAnyLinkage, Entry, std::string("\01l_OBJC_LABEL_PROTOCOL_$_") +ProtocolName, &CGM.getModule()); PTGV->setAlignment( CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy)); PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip"); PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); UsedGlobals.push_back(PTGV); return Entry; } /// EmitProtocolList - Generate protocol list meta-data: /// @code /// struct _protocol_list_t { /// long protocol_count; // Note, this is 32/64 bit /// struct _protocol_t[protocol_count]; /// } /// @endcode /// llvm::Constant * CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name, ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end) { std::vector<llvm::Constant*> ProtocolRefs; // Just return null for empty protocol lists if (begin == end) return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); // FIXME: We shouldn't need to do this lookup here, should we? llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); if (GV) return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy); for (; begin != end; ++begin) ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented??? // This list is null terminated. ProtocolRefs.push_back(llvm::Constant::getNullValue( ObjCTypes.ProtocolnfABIPtrTy)); std::vector<llvm::Constant*> Values(2); Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); Values[1] = llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy, ProtocolRefs.size()), ProtocolRefs); llvm::Constant *Init = llvm::ConstantStruct::get(Values); GV = new llvm::GlobalVariable(Init->getType(), false, llvm::GlobalValue::InternalLinkage, Init, Name, &CGM.getModule()); GV->setSection("__DATA, __objc_const"); GV->setAlignment( CGM.getTargetData().getPrefTypeAlignment(Init->getType())); UsedGlobals.push_back(GV); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy); } /// GetMethodDescriptionConstant - This routine build following meta-data: /// struct _objc_method { /// SEL _cmd; /// char *method_type; /// char *_imp; /// } llvm::Constant * CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { std::vector<llvm::Constant*> Desc(3); Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), ObjCTypes.SelectorPtrTy); Desc[1] = GetMethodVarType(MD); // Protocol methods have no implementation. So, this entry is always NULL. Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc); } /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference. /// This code gen. amounts to generating code for: /// @code /// (type *)((char *)base + _OBJC_IVAR_$_.ivar; /// @encode /// LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar( CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, const FieldDecl *Field, unsigned CVRQualifiers) { assert(ObjectTy->isObjCInterfaceType() && "CGObjCNonFragileABIMac::EmitObjCValueForIvar"); ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl(); std::string ExternalName; llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ExternalName, ID, Ivar); // (char *) BaseValue llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, ObjCTypes.Int8PtrTy); llvm::Value *Offset = CGF.Builder.CreateLoad(IvarOffsetGV); // (char*)BaseValue + Offset_symbol V = CGF.Builder.CreateGEP(V, Offset, "add.ptr"); // (type *)((char*)BaseValue + Offset_symbol) const llvm::Type *IvarTy = CGM.getTypes().ConvertType(Ivar->getType()); llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy); V = CGF.Builder.CreateBitCast(V, ptrIvarTy); if (Ivar->isBitField()) { CodeGenTypes::BitFieldInfo bitFieldInfo = CGM.getTypes().getBitFieldInfo(Field); return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size, Field->getType()->isSignedIntegerType(), Field->getType().getCVRQualifiers()|CVRQualifiers); } LValue LV = LValue::MakeAddr(V, Ivar->getType().getCVRQualifiers()|CVRQualifiers, CGM.getContext().getObjCGCAttrKind(Ivar->getType())); LValue::SetObjCIvar(LV, true); return LV; } llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset( CodeGen::CodeGenFunction &CGF, ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar) { std::string ExternalName; llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ExternalName, Interface, Ivar); return CGF.Builder.CreateLoad(IvarOffsetGV, false, "ivar"); } CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend( CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, llvm::Value *Receiver, QualType Arg0Ty, bool IsSuper, const CallArgList &CallArgs) { // FIXME. Even though IsSuper is passes. This function doese not // handle calls to 'super' receivers. CodeGenTypes &Types = CGM.getTypes(); llvm::Value *Arg0 = Receiver; if (!IsSuper) Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp"); // Find the message function name. // FIXME. This is too much work to get the ABI-specific result type // needed to find the message name. const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, llvm::SmallVector<QualType, 16>()); llvm::Constant *Fn; std::string Name("\01l_"); if (CGM.ReturnTypeUsesSret(FnInfo)) { #if 0 // unlike what is documented. gcc never generates this API!! if (Receiver->getType() == ObjCTypes.ObjectPtrTy) { Fn = ObjCTypes.MessageSendIdStretFixupFn; // FIXME. Is there a better way of getting these names. // They are available in RuntimeFunctions vector pair. Name += "objc_msgSendId_stret_fixup"; } else #endif if (IsSuper) { Fn = ObjCTypes.MessageSendSuper2StretFixupFn; Name += "objc_msgSendSuper2_stret_fixup"; } else { Fn = ObjCTypes.MessageSendStretFixupFn; Name += "objc_msgSend_stret_fixup"; } } else if (ResultType->isFloatingType() && // Selection of frret API only happens in 32bit nonfragile ABI. CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) { Fn = ObjCTypes.MessageSendFpretFixupFn; Name += "objc_msgSend_fpret_fixup"; } else { #if 0 // unlike what is documented. gcc never generates this API!! if (Receiver->getType() == ObjCTypes.ObjectPtrTy) { Fn = ObjCTypes.MessageSendIdFixupFn; Name += "objc_msgSendId_fixup"; } else #endif if (IsSuper) { Fn = ObjCTypes.MessageSendSuper2FixupFn; Name += "objc_msgSendSuper2_fixup"; } else { Fn = ObjCTypes.MessageSendFixupFn; Name += "objc_msgSend_fixup"; } } Name += '_'; std::string SelName(Sel.getAsString()); // Replace all ':' in selector name with '_' ouch! for(unsigned i = 0; i < SelName.size(); i++) if (SelName[i] == ':') SelName[i] = '_'; Name += SelName; llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); if (!GV) { // Build message ref table entry. std::vector<llvm::Constant*> Values(2); Values[0] = Fn; Values[1] = GetMethodVarName(Sel); llvm::Constant *Init = llvm::ConstantStruct::get(Values); GV = new llvm::GlobalVariable(Init->getType(), false, llvm::GlobalValue::WeakAnyLinkage, Init, Name, &CGM.getModule()); GV->setVisibility(llvm::GlobalValue::HiddenVisibility); GV->setAlignment(16); GV->setSection("__DATA, __objc_msgrefs, coalesced"); UsedGlobals.push_back(GV); } llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy); CallArgList ActualArgs; ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); ActualArgs.push_back(std::make_pair(RValue::get(Arg1), ObjCTypes.MessageRefCPtrTy)); ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs); llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0); Callee = CGF.Builder.CreateLoad(Callee); const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true); Callee = CGF.Builder.CreateBitCast(Callee, llvm::PointerType::getUnqual(FTy)); return CGF.EmitCall(FnInfo1, Callee, ActualArgs); } /// Generate code for a message send expression in the nonfragile abi. CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend( CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, llvm::Value *Receiver, bool IsClassMessage, const CallArgList &CallArgs) { return EmitMessageSend(CGF, ResultType, Sel, Receiver, CGF.getContext().getObjCIdType(), false, CallArgs); } llvm::GlobalVariable * CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) { llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); if (!GV) { GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, llvm::GlobalValue::ExternalLinkage, 0, Name, &CGM.getModule()); } return GV; } llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID, bool IsSuper) { llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; if (!Entry) { std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString()); llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName); Entry = new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false, llvm::GlobalValue::InternalLinkage, ClassGV, IsSuper ? "\01L_OBJC_CLASSLIST_SUP_REFS_$_" : "\01L_OBJC_CLASSLIST_REFERENCES_$_", &CGM.getModule()); Entry->setAlignment( CGM.getTargetData().getPrefTypeAlignment( ObjCTypes.ClassnfABIPtrTy)); if (IsSuper) Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip"); else Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip"); UsedGlobals.push_back(Entry); } return Builder.CreateLoad(Entry, false, "tmp"); } /// EmitMetaClassRef - Return a Value * of the address of _class_t /// meta-data /// llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID) { llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()]; if (Entry) return Builder.CreateLoad(Entry, false, "tmp"); std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString()); llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName); Entry = new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false, llvm::GlobalValue::InternalLinkage, MetaClassGV, "\01L_OBJC_CLASSLIST_SUP_REFS_$_", &CGM.getModule()); Entry->setAlignment( CGM.getTargetData().getPrefTypeAlignment( ObjCTypes.ClassnfABIPtrTy)); Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip"); UsedGlobals.push_back(Entry); return Builder.CreateLoad(Entry, false, "tmp"); } /// GetClass - Return a reference to the class for the given interface /// decl. llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder, const ObjCInterfaceDecl *ID) { return EmitClassRef(Builder, ID); } /// Generates a message send where the super is the receiver. This is /// a message send to self with special delivery semantics indicating /// which class's method should be called. CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Receiver, bool IsClassMessage, const CodeGen::CallArgList &CallArgs) { // ... // Create and init a super structure; this is a (receiver, class) // pair we will pass to objc_msgSendSuper. llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); llvm::Value *ReceiverAsObject = CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); CGF.Builder.CreateStore(ReceiverAsObject, CGF.Builder.CreateStructGEP(ObjCSuper, 0)); // If this is a class message the metaclass is passed as the target. llvm::Value *Target; if (IsClassMessage) { if (isCategoryImpl) { // Message sent to "super' in a class method defined in // a category implementation. Target = EmitClassRef(CGF.Builder, Class, false); Target = CGF.Builder.CreateStructGEP(Target, 0); Target = CGF.Builder.CreateLoad(Target); } else Target = EmitMetaClassRef(CGF.Builder, Class); } else Target = EmitClassRef(CGF.Builder, Class, true); // FIXME: We shouldn't need to do this cast, rectify the ASTContext // and ObjCTypes types. const llvm::Type *ClassTy = CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); Target = CGF.Builder.CreateBitCast(Target, ClassTy); CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1)); return EmitMessageSend(CGF, ResultType, Sel, ObjCSuper, ObjCTypes.SuperPtrCTy, true, CallArgs); } llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) { llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; if (!Entry) { llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), ObjCTypes.SelectorPtrTy); Entry = new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false, llvm::GlobalValue::InternalLinkage, Casted, "\01L_OBJC_SELECTOR_REFERENCES_", &CGM.getModule()); Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip"); UsedGlobals.push_back(Entry); } return Builder.CreateLoad(Entry, false, "tmp"); } /// EmitObjCIvarAssign - Code gen for assigning to a __strong object. /// objc_assign_ivar (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn, src, dst, "assignivar"); return; } /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. /// objc_assign_strongCast (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign( CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn, src, dst, "weakassign"); return; } /// EmitObjCWeakRead - Code gen for loading value of a __weak /// object: objc_read_weak (id *src) /// llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead( CodeGen::CodeGenFunction &CGF, llvm::Value *AddrWeakObj) { const llvm::Type* DestTy = cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType(); AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn, AddrWeakObj, "weakread"); read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); return read_weak; } /// EmitObjCWeakAssign - Code gen for assigning to a __weak object. /// objc_assign_weak (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn, src, dst, "weakassign"); return; } /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. /// objc_assign_global (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, llvm::Value *dst) { const llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn, src, dst, "globalassign"); return; } void CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S) { bool isTry = isa<ObjCAtTryStmt>(S); llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest(); llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); // For @synchronized, call objc_sync_enter(sync.expr). The // evaluation of the expression must occur before we enter the // @synchronized. We can safely avoid a temp here because jumps into // @synchronized are illegal & this will dominate uses. llvm::Value *SyncArg = 0; if (!isTry) { SyncArg = CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy); CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg); } // Push an EH context entry, used for handling rethrows and jumps // through finally. CGF.PushCleanupBlock(FinallyBlock); CGF.setInvokeDest(TryHandler); CGF.EmitBlock(TryBlock); CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); CGF.EmitBranchThroughCleanup(FinallyEnd); // Emit the exception handler. CGF.EmitBlock(TryHandler); llvm::Value *llvm_eh_exception = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception); llvm::Value *llvm_eh_selector_i64 = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64); llvm::Value *llvm_eh_typeid_for_i64 = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64); llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow"); llvm::SmallVector<llvm::Value*, 8> SelectorArgs; SelectorArgs.push_back(Exc); SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr()); // Construct the lists of (type, catch body) to handle. llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers; bool HasCatchAll = false; if (isTry) { if (const ObjCAtCatchStmt* CatchStmt = cast<ObjCAtTryStmt>(S).getCatchStmts()) { for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody())); // catch(...) always matches. if (!CatchDecl) { // Use i8* null here to signal this is a catch all, not a cleanup. llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); SelectorArgs.push_back(Null); HasCatchAll = true; break; } if (CGF.getContext().isObjCIdType(CatchDecl->getType()) || CatchDecl->getType()->isObjCQualifiedIdType()) { llvm::Value *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id"); if (!IDEHType) IDEHType = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, llvm::GlobalValue::ExternalLinkage, 0, "OBJC_EHTYPE_id", &CGM.getModule()); SelectorArgs.push_back(IDEHType); HasCatchAll = true; break; } // All other types should be Objective-C interface pointer types. const PointerType *PT = CatchDecl->getType()->getAsPointerType(); assert(PT && "Invalid @catch type."); const ObjCInterfaceType *IT = PT->getPointeeType()->getAsObjCInterfaceType(); assert(IT && "Invalid @catch type."); llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false); SelectorArgs.push_back(EHType); } } } // We use a cleanup unless there was already a catch all. if (!HasCatchAll) { SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0)); } llvm::Value *Selector = CGF.Builder.CreateCall(llvm_eh_selector_i64, SelectorArgs.begin(), SelectorArgs.end(), "selector"); for (unsigned i = 0, e = Handlers.size(); i != e; ++i) { const ParmVarDecl *CatchParam = Handlers[i].first; const Stmt *CatchBody = Handlers[i].second; llvm::BasicBlock *Next = 0; // The last handler always matches. if (i + 1 != e) { assert(CatchParam && "Only last handler can be a catch all."); llvm::BasicBlock *Match = CGF.createBasicBlock("match"); Next = CGF.createBasicBlock("catch.next"); llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for_i64, CGF.Builder.CreateBitCast(SelectorArgs[i+2], ObjCTypes.Int8PtrTy)); CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id), Match, Next); CGF.EmitBlock(Match); } if (CatchBody) { llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end"); llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler"); // Cleanups must call objc_end_catch. // // FIXME: It seems incorrect for objc_begin_catch to be inside // this context, but this matches gcc. CGF.PushCleanupBlock(MatchEnd); CGF.setInvokeDest(MatchHandler); llvm::Value *ExcObject = CGF.Builder.CreateCall(ObjCTypes.ObjCBeginCatchFn, Exc); // Bind the catch parameter if it exists. if (CatchParam) { ExcObject = CGF.Builder.CreateBitCast(ExcObject, CGF.ConvertType(CatchParam->getType())); // CatchParam is a ParmVarDecl because of the grammar // construction used to handle this, but for codegen purposes // we treat this as a local decl. CGF.EmitLocalBlockVarDecl(*CatchParam); CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam)); } CGF.ObjCEHValueStack.push_back(ExcObject); CGF.EmitStmt(CatchBody); CGF.ObjCEHValueStack.pop_back(); CGF.EmitBranchThroughCleanup(FinallyEnd); CGF.EmitBlock(MatchHandler); llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); // We are required to emit this call to satisfy LLVM, even // though we don't use the result. llvm::SmallVector<llvm::Value*, 8> Args; Args.push_back(Exc); Args.push_back(ObjCTypes.getEHPersonalityPtr()); Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end()); CGF.Builder.CreateStore(Exc, RethrowPtr); CGF.EmitBranchThroughCleanup(FinallyRethrow); CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); CGF.EmitBlock(MatchEnd); // Unfortunately, we also have to generate another EH frame here // in case this throws. llvm::BasicBlock *MatchEndHandler = CGF.createBasicBlock("match.end.handler"); llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont"); CGF.Builder.CreateInvoke(ObjCTypes.ObjCEndCatchFn, Cont, MatchEndHandler, Args.begin(), Args.begin()); CGF.EmitBlock(Cont); if (Info.SwitchBlock) CGF.EmitBlock(Info.SwitchBlock); if (Info.EndBlock) CGF.EmitBlock(Info.EndBlock); CGF.EmitBlock(MatchEndHandler); Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); // We are required to emit this call to satisfy LLVM, even // though we don't use the result. Args.clear(); Args.push_back(Exc); Args.push_back(ObjCTypes.getEHPersonalityPtr()); Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end()); CGF.Builder.CreateStore(Exc, RethrowPtr); CGF.EmitBranchThroughCleanup(FinallyRethrow); if (Next) CGF.EmitBlock(Next); } else { assert(!Next && "catchup should be last handler."); CGF.Builder.CreateStore(Exc, RethrowPtr); CGF.EmitBranchThroughCleanup(FinallyRethrow); } } // Pop the cleanup entry, the @finally is outside this cleanup // scope. CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); CGF.setInvokeDest(PrevLandingPad); CGF.EmitBlock(FinallyBlock); if (isTry) { if (const ObjCAtFinallyStmt* FinallyStmt = cast<ObjCAtTryStmt>(S).getFinallyStmt()) CGF.EmitStmt(FinallyStmt->getFinallyBody()); } else { // Emit 'objc_sync_exit(expr)' as finally's sole statement for // @synchronized. CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, SyncArg); } if (Info.SwitchBlock) CGF.EmitBlock(Info.SwitchBlock); if (Info.EndBlock) CGF.EmitBlock(Info.EndBlock); // Branch around the rethrow code. CGF.EmitBranch(FinallyEnd); CGF.EmitBlock(FinallyRethrow); CGF.Builder.CreateCall(ObjCTypes.UnwindResumeOrRethrowFn, CGF.Builder.CreateLoad(RethrowPtr)); CGF.Builder.CreateUnreachable(); CGF.EmitBlock(FinallyEnd); } /// EmitThrowStmt - Generate code for a throw statement. void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S) { llvm::Value *Exception; if (const Expr *ThrowExpr = S.getThrowExpr()) { Exception = CGF.EmitScalarExpr(ThrowExpr); } else { assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && "Unexpected rethrow outside @catch block."); Exception = CGF.ObjCEHValueStack.back(); } llvm::Value *ExceptionAsObject = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp"); llvm::BasicBlock *InvokeDest = CGF.getInvokeDest(); if (InvokeDest) { llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont"); CGF.Builder.CreateInvoke(ObjCTypes.ExceptionThrowFn, Cont, InvokeDest, &ExceptionAsObject, &ExceptionAsObject + 1); CGF.EmitBlock(Cont); } else CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject); CGF.Builder.CreateUnreachable(); // Clear the insertion point to indicate we are in unreachable code. CGF.Builder.ClearInsertionPoint(); } llvm::Value * CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID, bool ForDefinition) { llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()]; // If we don't need a definition, return the entry if found or check // if we use an external reference. if (!ForDefinition) { if (Entry) return Entry; // If this type (or a super class) has the __objc_exception__ // attribute, emit an external reference. if (hasObjCExceptionAttribute(ID)) return Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, llvm::GlobalValue::ExternalLinkage, 0, (std::string("OBJC_EHTYPE_$_") + ID->getIdentifier()->getName()), &CGM.getModule()); } // Otherwise we need to either make a new entry or fill in the // initializer. assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition"); std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString()); std::string VTableName = "objc_ehtype_vtable"; llvm::GlobalVariable *VTableGV = CGM.getModule().getGlobalVariable(VTableName); if (!VTableGV) VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false, llvm::GlobalValue::ExternalLinkage, 0, VTableName, &CGM.getModule()); llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2); std::vector<llvm::Constant*> Values(3); Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1); Values[1] = GetClassName(ID->getIdentifier()); Values[2] = GetClassGlobal(ClassName); llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values); if (Entry) { Entry->setInitializer(Init); } else { Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, llvm::GlobalValue::WeakAnyLinkage, Init, (std::string("OBJC_EHTYPE_$_") + ID->getIdentifier()->getName()), &CGM.getModule()); } if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden) Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); Entry->setAlignment(8); if (ForDefinition) { Entry->setSection("__DATA,__objc_const"); Entry->setLinkage(llvm::GlobalValue::ExternalLinkage); } else { Entry->setSection("__DATA,__datacoal_nt,coalesced"); } return Entry; } /* *** */ CodeGen::CGObjCRuntime * CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) { return new CGObjCMac(CGM); } CodeGen::CGObjCRuntime * CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) { return new CGObjCNonFragileABIMac(CGM); } <file_sep>/test/Analysis/rdar-6541136-region.c // RUN: clang-cc -verify -analyze -checker-cfref -analyzer-store=region %s struct tea_cheese { unsigned magic; }; typedef struct tea_cheese kernel_tea_cheese_t; extern kernel_tea_cheese_t _wonky_gesticulate_cheese; // This test case exercises the ElementRegion::getRValueType() logic. void foo( void ) { kernel_tea_cheese_t *wonky = &_wonky_gesticulate_cheese; struct load_wine *cmd = (void*) &wonky[1]; cmd = cmd; char *p = (void*) &wonky[1]; *p = 1; kernel_tea_cheese_t *q = &wonky[1]; kernel_tea_cheese_t r = *q; // expected-warning{{out-of-bound memory position}} } <file_sep>/lib/AST/DeclTemplate.cpp //===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the C++ related Decl classes for templates. // //===----------------------------------------------------------------------===// #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/IdentifierTable.h" #include "llvm/ADT/STLExtras.h" using namespace clang; //===----------------------------------------------------------------------===// // TemplateParameterList Implementation //===----------------------------------------------------------------------===// TemplateParameterList::TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc, Decl **Params, unsigned NumParams, SourceLocation RAngleLoc) : TemplateLoc(TemplateLoc), LAngleLoc(LAngleLoc), RAngleLoc(RAngleLoc), NumParams(NumParams) { for (unsigned Idx = 0; Idx < NumParams; ++Idx) begin()[Idx] = Params[Idx]; } TemplateParameterList * TemplateParameterList::Create(ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, Decl **Params, unsigned NumParams, SourceLocation RAngleLoc) { unsigned Size = sizeof(TemplateParameterList) + sizeof(Decl *) * NumParams; unsigned Align = llvm::AlignOf<TemplateParameterList>::Alignment; void *Mem = C.Allocate(Size, Align); return new (Mem) TemplateParameterList(TemplateLoc, LAngleLoc, Params, NumParams, RAngleLoc); } unsigned TemplateParameterList::getMinRequiredArguments() const { unsigned NumRequiredArgs = size(); iterator Param = const_cast<TemplateParameterList *>(this)->end(), ParamBegin = const_cast<TemplateParameterList *>(this)->begin(); while (Param != ParamBegin) { --Param; if (!(isa<TemplateTypeParmDecl>(*Param) && cast<TemplateTypeParmDecl>(*Param)->hasDefaultArgument()) && !(isa<NonTypeTemplateParmDecl>(*Param) && cast<NonTypeTemplateParmDecl>(*Param)->hasDefaultArgument()) && !(isa<TemplateTemplateParmDecl>(*Param) && cast<TemplateTemplateParmDecl>(*Param)->hasDefaultArgument())) break; --NumRequiredArgs; } return NumRequiredArgs; } //===----------------------------------------------------------------------===// // TemplateDecl Implementation //===----------------------------------------------------------------------===// TemplateDecl::~TemplateDecl() { } //===----------------------------------------------------------------------===// // FunctionTemplateDecl Implementation //===----------------------------------------------------------------------===// FunctionTemplateDecl *FunctionTemplateDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl) { return new (C) FunctionTemplateDecl(DC, L, Name, Params, Decl); } //===----------------------------------------------------------------------===// // ClassTemplateDecl Implementation //===----------------------------------------------------------------------===// ClassTemplateDecl *ClassTemplateDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl, ClassTemplateDecl *PrevDecl) { Common *CommonPtr; if (PrevDecl) CommonPtr = PrevDecl->CommonPtr; else CommonPtr = new (C) Common; return new (C) ClassTemplateDecl(DC, L, Name, Params, Decl, PrevDecl, CommonPtr); } ClassTemplateDecl::~ClassTemplateDecl() { assert(CommonPtr == 0 && "ClassTemplateDecl must be explicitly destroyed"); } void ClassTemplateDecl::Destroy(ASTContext& C) { if (!PreviousDeclaration) { CommonPtr->~Common(); C.Deallocate((void*)CommonPtr); } CommonPtr = 0; this->~ClassTemplateDecl(); C.Deallocate((void*)this); } //===----------------------------------------------------------------------===// // TemplateTypeParm Allocation/Deallocation Method Implementations //===----------------------------------------------------------------------===// TemplateTypeParmDecl * TemplateTypeParmDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename) { QualType Type = C.getTemplateTypeParmType(D, P, Id); return new (C) TemplateTypeParmDecl(DC, L, Id, Typename, Type); } //===----------------------------------------------------------------------===// // NonTypeTemplateParmDecl Method Implementations //===----------------------------------------------------------------------===// NonTypeTemplateParmDecl * NonTypeTemplateParmDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, SourceLocation TypeSpecStartLoc) { return new (C) NonTypeTemplateParmDecl(DC, L, D, P, Id, T, TypeSpecStartLoc); } SourceLocation NonTypeTemplateParmDecl::getDefaultArgumentLoc() const { return DefaultArgument? DefaultArgument->getSourceRange().getBegin() : SourceLocation(); } //===----------------------------------------------------------------------===// // TemplateTemplateParmDecl Method Implementations //===----------------------------------------------------------------------===// TemplateTemplateParmDecl * TemplateTemplateParmDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, TemplateParameterList *Params) { return new (C) TemplateTemplateParmDecl(DC, L, D, P, Id, Params); } SourceLocation TemplateTemplateParmDecl::getDefaultArgumentLoc() const { return DefaultArgument? DefaultArgument->getSourceRange().getBegin() : SourceLocation(); } //===----------------------------------------------------------------------===// // TemplateArgument Implementation //===----------------------------------------------------------------------===// TemplateArgument::TemplateArgument(Expr *E) : Kind(Expression) { TypeOrValue = reinterpret_cast<uintptr_t>(E); StartLoc = E->getSourceRange().getBegin(); } //===----------------------------------------------------------------------===// // ClassTemplateSpecializationDecl Implementation //===----------------------------------------------------------------------===// ClassTemplateSpecializationDecl:: ClassTemplateSpecializationDecl(DeclContext *DC, SourceLocation L, ClassTemplateDecl *SpecializedTemplate, TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) : CXXRecordDecl(ClassTemplateSpecialization, SpecializedTemplate->getTemplatedDecl()->getTagKind(), DC, L, // FIXME: Should we use DeclarationName for the name of // class template specializations? SpecializedTemplate->getIdentifier()), SpecializedTemplate(SpecializedTemplate), NumTemplateArgs(NumTemplateArgs), SpecializationKind(TSK_Undeclared) { TemplateArgument *Arg = reinterpret_cast<TemplateArgument *>(this + 1); for (unsigned ArgIdx = 0; ArgIdx < NumTemplateArgs; ++ArgIdx, ++Arg) new (Arg) TemplateArgument(TemplateArgs[ArgIdx]); } ClassTemplateSpecializationDecl * ClassTemplateSpecializationDecl::Create(ASTContext &Context, DeclContext *DC, SourceLocation L, ClassTemplateDecl *SpecializedTemplate, TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, ClassTemplateSpecializationDecl *PrevDecl) { unsigned Size = sizeof(ClassTemplateSpecializationDecl) + sizeof(TemplateArgument) * NumTemplateArgs; unsigned Align = llvm::AlignOf<ClassTemplateSpecializationDecl>::Alignment; void *Mem = Context.Allocate(Size, Align); ClassTemplateSpecializationDecl *Result = new (Mem) ClassTemplateSpecializationDecl(DC, L, SpecializedTemplate, TemplateArgs, NumTemplateArgs); Context.getTypeDeclType(Result, PrevDecl); return Result; } <file_sep>/lib/Sema/SemaAccess.cpp //===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides Sema routines for C++ access control semantics. // //===----------------------------------------------------------------------===// #include "SemaInherit.h" #include "Sema.h" #include "clang/AST/ASTContext.h" using namespace clang; /// SetMemberAccessSpecifier - Set the access specifier of a member. /// Returns true on error (when the previous member decl access specifier /// is different from the new member decl access specifier). bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS) { if (!PrevMemberDecl) { // Use the lexical access specifier. MemberDecl->setAccess(LexicalAS); return false; } // C++ [class.access.spec]p3: When a member is redeclared its access // specifier must be same as its initial declaration. if (LexicalAS != AS_none && LexicalAS != PrevMemberDecl->getAccess()) { Diag(MemberDecl->getLocation(), diag::err_class_redeclared_with_different_access) << MemberDecl << LexicalAS; Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration) << PrevMemberDecl << PrevMemberDecl->getAccess(); return true; } MemberDecl->setAccess(PrevMemberDecl->getAccess()); return false; } /// CheckBaseClassAccess - Check that a derived class can access its base class /// and report an error if it can't. [class.access.base] bool Sema::CheckBaseClassAccess(QualType Derived, QualType Base, BasePaths& Paths, SourceLocation AccessLoc) { Base = Context.getCanonicalType(Base).getUnqualifiedType(); assert(!Paths.isAmbiguous(Base) && "Can't check base class access if set of paths is ambiguous"); assert(Paths.isRecordingPaths() && "Can't check base class access without recorded paths"); const CXXBaseSpecifier *InacessibleBase = 0; const CXXRecordDecl* CurrentClassDecl = 0; if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl())) CurrentClassDecl = MD->getParent(); for (BasePaths::paths_iterator Path = Paths.begin(), PathsEnd = Paths.end(); Path != PathsEnd; ++Path) { bool FoundInaccessibleBase = false; for (BasePath::const_iterator Element = Path->begin(), ElementEnd = Path->end(); Element != ElementEnd; ++Element) { const CXXBaseSpecifier *Base = Element->Base; switch (Base->getAccessSpecifier()) { default: assert(0 && "invalid access specifier"); case AS_public: // Nothing to do. break; case AS_private: // FIXME: Check if the current function/class is a friend. if (CurrentClassDecl != Element->Class) FoundInaccessibleBase = true; break; case AS_protected: // FIXME: Implement break; } if (FoundInaccessibleBase) { InacessibleBase = Base; break; } } if (!FoundInaccessibleBase) { // We found a path to the base, our work here is done. InacessibleBase = 0; break; } } if (InacessibleBase) { Diag(AccessLoc, diag::err_conv_to_inaccessible_base) << Derived << Base; AccessSpecifier AS = InacessibleBase->getAccessSpecifierAsWritten(); // If there's no written access specifier, then the inheritance specifier // is implicitly private. if (AS == AS_none) Diag(InacessibleBase->getSourceRange().getBegin(), diag::note_inheritance_implicitly_private_here); else Diag(InacessibleBase->getSourceRange().getBegin(), diag::note_inheritance_specifier_here) << AS; return true; } return false; } <file_sep>/test/CodeGen/align-local.c // RUN: clang-cc -emit-llvm < %s | grep "align 16" | count 2 typedef struct __attribute((aligned(16))) {int x[4];} ff; int a() { ff a; struct {int x[4];} b __attribute((aligned(16))); } <file_sep>/lib/Analysis/MemRegion.cpp //== MemRegion.cpp - Abstract memory regions for static analysis --*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines MemRegion and its subclasses. MemRegion defines a // partially-typed abstraction of memory useful for path-sensitive dataflow // analyses. // //===----------------------------------------------------------------------===// #include "llvm/Support/raw_ostream.h" #include "clang/Analysis/PathSensitive/MemRegion.h" using namespace clang; MemRegion::~MemRegion() {} bool SubRegion::isSubRegionOf(const MemRegion* R) const { const MemRegion* r = getSuperRegion(); while (r != 0) { if (r == R) return true; if (const SubRegion* sr = dyn_cast<SubRegion>(r)) r = sr->getSuperRegion(); else break; } return false; } void MemSpaceRegion::Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned)getKind()); } void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const StringLiteral* Str, const MemRegion* superRegion) { ID.AddInteger((unsigned) StringRegionKind); ID.AddPointer(Str); ID.AddPointer(superRegion); } void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Expr* Ex, unsigned cnt) { ID.AddInteger((unsigned) AllocaRegionKind); ID.AddPointer(Ex); ID.AddInteger(cnt); } void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const { ProfileRegion(ID, Ex, Cnt); } void TypedViewRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, QualType T, const MemRegion* superRegion) { ID.AddInteger((unsigned) TypedViewRegionKind); ID.Add(T); ID.AddPointer(superRegion); } void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const { CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion); } void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const CompoundLiteralExpr* CL, const MemRegion* superRegion) { ID.AddInteger((unsigned) CompoundLiteralRegionKind); ID.AddPointer(CL); ID.AddPointer(superRegion); } void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl* D, const MemRegion* superRegion, Kind k) { ID.AddInteger((unsigned) k); ID.AddPointer(D); ID.AddPointer(superRegion); } void DeclRegion::Profile(llvm::FoldingSetNodeID& ID) const { DeclRegion::ProfileRegion(ID, D, superRegion, getKind()); } void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym) { ID.AddInteger((unsigned) MemRegion::SymbolicRegionKind); ID.Add(sym); } void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const { SymbolicRegion::ProfileRegion(ID, sym); } void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SVal Idx, const MemRegion* superRegion) { ID.AddInteger(MemRegion::ElementRegionKind); ID.AddPointer(superRegion); Idx.Profile(ID); } void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const { ElementRegion::ProfileRegion(ID, Index, superRegion); } void CodeTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const void* data, QualType t) { ID.AddInteger(MemRegion::CodeTextRegionKind); ID.AddPointer(data); ID.Add(t); } void CodeTextRegion::Profile(llvm::FoldingSetNodeID& ID) const { CodeTextRegion::ProfileRegion(ID, Data, LocationType); } //===----------------------------------------------------------------------===// // getLValueType() and getRValueType() //===----------------------------------------------------------------------===// QualType ElementRegion::getRValueType(ASTContext& C) const { // Strip off typedefs from the ArrayRegion's RvalueType. QualType T = getArrayRegion()->getRValueType(C)->getDesugaredType(); if (ArrayType* AT = dyn_cast<ArrayType>(T.getTypePtr())) return AT->getElementType(); // If the RValueType of the array region isn't an ArrayType, then essentially // the element's return T; } QualType StringRegion::getRValueType(ASTContext& C) const { return Str->getType(); } //===----------------------------------------------------------------------===// // Region pretty-printing. //===----------------------------------------------------------------------===// std::string MemRegion::getString() const { std::string s; llvm::raw_string_ostream os(s); print(os); return os.str(); } void MemRegion::print(llvm::raw_ostream& os) const { os << "<Unknown Region>"; } void AllocaRegion::print(llvm::raw_ostream& os) const { os << "alloca{" << (void*) Ex << ',' << Cnt << '}'; } void TypedViewRegion::print(llvm::raw_ostream& os) const { os << "typed_view{" << LValueType.getAsString() << ','; getSuperRegion()->print(os); os << '}'; } void VarRegion::print(llvm::raw_ostream& os) const { os << cast<VarDecl>(D)->getNameAsString(); } void SymbolicRegion::print(llvm::raw_ostream& os) const { os << "SymRegion-" << sym; } void FieldRegion::print(llvm::raw_ostream& os) const { superRegion->print(os); os << "->" << getDecl()->getNameAsString(); } void ElementRegion::print(llvm::raw_ostream& os) const { superRegion->print(os); os << '['; Index.print(os); os << ']'; } void CompoundLiteralRegion::print(llvm::raw_ostream& os) const { // FIXME: More elaborate pretty-printing. os << "{ " << (void*) CL << " }"; } void StringRegion::print(llvm::raw_ostream& os) const { Str->printPretty(os); } //===----------------------------------------------------------------------===// // MemRegionManager methods. //===----------------------------------------------------------------------===// MemSpaceRegion* MemRegionManager::LazyAllocate(MemSpaceRegion*& region) { if (!region) { region = (MemSpaceRegion*) A.Allocate<MemSpaceRegion>(); new (region) MemSpaceRegion(); } return region; } MemSpaceRegion* MemRegionManager::getStackRegion() { return LazyAllocate(stack); } MemSpaceRegion* MemRegionManager::getGlobalsRegion() { return LazyAllocate(globals); } MemSpaceRegion* MemRegionManager::getHeapRegion() { return LazyAllocate(heap); } MemSpaceRegion* MemRegionManager::getUnknownRegion() { return LazyAllocate(unknown); } MemSpaceRegion* MemRegionManager::getCodeRegion() { return LazyAllocate(code); } bool MemRegionManager::onStack(const MemRegion* R) { while (const SubRegion* SR = dyn_cast<SubRegion>(R)) R = SR->getSuperRegion(); return (R != 0) && (R == stack); } bool MemRegionManager::onHeap(const MemRegion* R) { while (const SubRegion* SR = dyn_cast<SubRegion>(R)) R = SR->getSuperRegion(); return (R != 0) && (R == heap); } StringRegion* MemRegionManager::getStringRegion(const StringLiteral* Str) { llvm::FoldingSetNodeID ID; MemSpaceRegion* GlobalsR = getGlobalsRegion(); StringRegion::ProfileRegion(ID, Str, GlobalsR); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); StringRegion* R = cast_or_null<StringRegion>(data); if (!R) { R = (StringRegion*) A.Allocate<StringRegion>(); new (R) StringRegion(Str, GlobalsR); Regions.InsertNode(R, InsertPos); } return R; } VarRegion* MemRegionManager::getVarRegion(const VarDecl* d) { const MemRegion* superRegion = d->hasLocalStorage() ? getStackRegion() : getGlobalsRegion(); llvm::FoldingSetNodeID ID; DeclRegion::ProfileRegion(ID, d, superRegion, MemRegion::VarRegionKind); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); VarRegion* R = cast_or_null<VarRegion>(data); if (!R) { R = (VarRegion*) A.Allocate<VarRegion>(); new (R) VarRegion(d, superRegion); Regions.InsertNode(R, InsertPos); } return R; } CompoundLiteralRegion* MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr* CL) { // Is this compound literal allocated on the stack or is part of the // global constant pool? const MemRegion* superRegion = CL->isFileScope() ? getGlobalsRegion() : getStackRegion(); // Profile the compound literal. llvm::FoldingSetNodeID ID; CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); CompoundLiteralRegion* R = cast_or_null<CompoundLiteralRegion>(data); if (!R) { R = (CompoundLiteralRegion*) A.Allocate<CompoundLiteralRegion>(); new (R) CompoundLiteralRegion(CL, superRegion); Regions.InsertNode(R, InsertPos); } return R; } ElementRegion* MemRegionManager::getElementRegion(SVal Idx, const TypedRegion* superRegion){ llvm::FoldingSetNodeID ID; ElementRegion::ProfileRegion(ID, Idx, superRegion); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); ElementRegion* R = cast_or_null<ElementRegion>(data); if (!R) { R = (ElementRegion*) A.Allocate<ElementRegion>(); new (R) ElementRegion(Idx, superRegion); Regions.InsertNode(R, InsertPos); } return R; } CodeTextRegion* MemRegionManager::getCodeTextRegion(const FunctionDecl* fd, QualType t) { llvm::FoldingSetNodeID ID; CodeTextRegion::ProfileRegion(ID, fd, t); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); CodeTextRegion* R = cast_or_null<CodeTextRegion>(data); if (!R) { R = (CodeTextRegion*) A.Allocate<CodeTextRegion>(); new (R) CodeTextRegion(fd, t, getCodeRegion()); Regions.InsertNode(R, InsertPos); } return R; } CodeTextRegion* MemRegionManager::getCodeTextRegion(SymbolRef sym, QualType t) { llvm::FoldingSetNodeID ID; CodeTextRegion::ProfileRegion(ID, sym, t); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); CodeTextRegion* R = cast_or_null<CodeTextRegion>(data); if (!R) { R = (CodeTextRegion*) A.Allocate<CodeTextRegion>(); new (R) CodeTextRegion(sym, t, getCodeRegion()); Regions.InsertNode(R, InsertPos); } return R; } /// getSymbolicRegion - Retrieve or create a "symbolic" memory region. SymbolicRegion* MemRegionManager::getSymbolicRegion(SymbolRef sym) { llvm::FoldingSetNodeID ID; SymbolicRegion::ProfileRegion(ID, sym); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); SymbolicRegion* R = cast_or_null<SymbolicRegion>(data); if (!R) { R = (SymbolicRegion*) A.Allocate<SymbolicRegion>(); // SymbolicRegion's storage class is usually unknown. new (R) SymbolicRegion(sym, getUnknownRegion()); Regions.InsertNode(R, InsertPos); } return R; } FieldRegion* MemRegionManager::getFieldRegion(const FieldDecl* d, const MemRegion* superRegion) { llvm::FoldingSetNodeID ID; DeclRegion::ProfileRegion(ID, d, superRegion, MemRegion::FieldRegionKind); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); FieldRegion* R = cast_or_null<FieldRegion>(data); if (!R) { R = (FieldRegion*) A.Allocate<FieldRegion>(); new (R) FieldRegion(d, superRegion); Regions.InsertNode(R, InsertPos); } return R; } ObjCIvarRegion* MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl* d, const MemRegion* superRegion) { llvm::FoldingSetNodeID ID; DeclRegion::ProfileRegion(ID, d, superRegion, MemRegion::ObjCIvarRegionKind); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); ObjCIvarRegion* R = cast_or_null<ObjCIvarRegion>(data); if (!R) { R = (ObjCIvarRegion*) A.Allocate<ObjCIvarRegion>(); new (R) ObjCIvarRegion(d, superRegion); Regions.InsertNode(R, InsertPos); } return R; } ObjCObjectRegion* MemRegionManager::getObjCObjectRegion(const ObjCInterfaceDecl* d, const MemRegion* superRegion) { llvm::FoldingSetNodeID ID; DeclRegion::ProfileRegion(ID, d, superRegion, MemRegion::ObjCObjectRegionKind); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); ObjCObjectRegion* R = cast_or_null<ObjCObjectRegion>(data); if (!R) { R = (ObjCObjectRegion*) A.Allocate<ObjCObjectRegion>(); new (R) ObjCObjectRegion(d, superRegion); Regions.InsertNode(R, InsertPos); } return R; } TypedViewRegion* MemRegionManager::getTypedViewRegion(QualType t, const MemRegion* superRegion) { llvm::FoldingSetNodeID ID; TypedViewRegion::ProfileRegion(ID, t, superRegion); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); TypedViewRegion* R = cast_or_null<TypedViewRegion>(data); if (!R) { R = (TypedViewRegion*) A.Allocate<TypedViewRegion>(); new (R) TypedViewRegion(t, superRegion); Regions.InsertNode(R, InsertPos); } return R; } AllocaRegion* MemRegionManager::getAllocaRegion(const Expr* E, unsigned cnt) { llvm::FoldingSetNodeID ID; AllocaRegion::ProfileRegion(ID, E, cnt); void* InsertPos; MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos); AllocaRegion* R = cast_or_null<AllocaRegion>(data); if (!R) { R = (AllocaRegion*) A.Allocate<AllocaRegion>(); new (R) AllocaRegion(E, cnt, getStackRegion()); Regions.InsertNode(R, InsertPos); } return R; } bool MemRegionManager::hasStackStorage(const MemRegion* R) { // Only subregions can have stack storage. const SubRegion* SR = dyn_cast<SubRegion>(R); if (!SR) return false; MemSpaceRegion* S = getStackRegion(); while (SR) { R = SR->getSuperRegion(); if (R == S) return true; SR = dyn_cast<SubRegion>(R); } return false; } //===----------------------------------------------------------------------===// // View handling. //===----------------------------------------------------------------------===// const MemRegion *TypedViewRegion::removeViews() const { const SubRegion *SR = this; const MemRegion *R = SR; while (SR && isa<TypedViewRegion>(SR)) { R = SR->getSuperRegion(); SR = dyn_cast<SubRegion>(R); } return R; } <file_sep>/include/clang/Analysis/ProgramPoint.h //==- ProgramPoint.h - Program Points for Path-Sensitive Analysis --*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface ProgramPoint, which identifies a // distinct location in a function. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_PROGRAM_POINT #define LLVM_CLANG_ANALYSIS_PROGRAM_POINT #include "clang/AST/CFG.h" #include "llvm/Support/DataTypes.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/FoldingSet.h" #include <cassert> #include <utility> namespace clang { class ProgramPoint { public: enum Kind { BlockEdgeKind = 0x0, BlockEntranceKind = 0x1, BlockExitKind = 0x2, // Keep the following four together and in this order. PostStmtKind = 0x3, PostLocationChecksSucceedKind = 0x4, PostOutOfBoundsCheckFailedKind = 0x5, PostNullCheckFailedKind = 0x6, PostUndefLocationCheckFailedKind = 0x7, PostLoadKind = 0x8, PostStoreKind = 0x9, PostPurgeDeadSymbolsKind = 0x10, PostStmtCustomKind = 0x11, MinPostStmtKind = PostStmtKind, MaxPostStmtKind = PostStmtCustomKind }; private: enum { TwoPointers = 0x1, Custom = 0x2, Mask = 0x3 }; std::pair<uintptr_t,uintptr_t> Data; const void *Tag; protected: ProgramPoint(const void* P, Kind k, const void *tag = 0) : Data(reinterpret_cast<uintptr_t>(P), (uintptr_t) k), Tag(tag) {} ProgramPoint(const void* P1, const void* P2, const void *tag = 0) : Data(reinterpret_cast<uintptr_t>(P1) | TwoPointers, reinterpret_cast<uintptr_t>(P2)), Tag(tag) {} ProgramPoint(const void* P1, const void* P2, bool, const void *tag = 0) : Data(reinterpret_cast<uintptr_t>(P1) | Custom, reinterpret_cast<uintptr_t>(P2)), Tag(tag) {} protected: void* getData1NoMask() const { Kind k = getKind(); k = k; assert(k == BlockEntranceKind || k == BlockExitKind); return reinterpret_cast<void*>(Data.first); } void* getData1() const { Kind k = getKind(); k = k; assert(k == BlockEdgeKind ||(k >= MinPostStmtKind && k <= MaxPostStmtKind)); return reinterpret_cast<void*>(Data.first & ~Mask); } void* getData2() const { Kind k = getKind(); k = k; assert(k == BlockEdgeKind || k == PostStmtCustomKind); return reinterpret_cast<void*>(Data.second); } const void *getTag() const { return Tag; } public: Kind getKind() const { switch (Data.first & Mask) { case TwoPointers: return BlockEdgeKind; case Custom: return PostStmtCustomKind; default: return (Kind) Data.second; } } // For use with DenseMap. This hash is probably slow. unsigned getHashValue() const { llvm::FoldingSetNodeID ID; ID.AddPointer(reinterpret_cast<void*>(Data.first)); ID.AddPointer(reinterpret_cast<void*>(Data.second)); ID.AddPointer(Tag); return ID.ComputeHash(); } static bool classof(const ProgramPoint*) { return true; } bool operator==(const ProgramPoint & RHS) const { return Data == RHS.Data && Tag == RHS.Tag; } bool operator!=(const ProgramPoint& RHS) const { return Data != RHS.Data || Tag != RHS.Tag; } bool operator<(const ProgramPoint& RHS) const { return Data < RHS.Data && Tag < RHS.Tag; } void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddPointer(reinterpret_cast<void*>(Data.first)); if (getKind() != PostStmtCustomKind) ID.AddPointer(reinterpret_cast<void*>(Data.second)); else { const std::pair<const void*, const void*> *P = reinterpret_cast<std::pair<const void*, const void*>*>(Data.second); ID.AddPointer(P->first); ID.AddPointer(P->second); } ID.AddPointer(Tag); } }; class BlockEntrance : public ProgramPoint { public: BlockEntrance(const CFGBlock* B) : ProgramPoint(B, BlockEntranceKind) {} CFGBlock* getBlock() const { return reinterpret_cast<CFGBlock*>(getData1NoMask()); } Stmt* getFirstStmt() const { CFGBlock* B = getBlock(); return B->empty() ? NULL : B->front(); } static bool classof(const ProgramPoint* Location) { return Location->getKind() == BlockEntranceKind; } }; class BlockExit : public ProgramPoint { public: BlockExit(const CFGBlock* B) : ProgramPoint(B, BlockExitKind) {} CFGBlock* getBlock() const { return reinterpret_cast<CFGBlock*>(getData1NoMask()); } Stmt* getLastStmt() const { CFGBlock* B = getBlock(); return B->empty() ? NULL : B->back(); } Stmt* getTerminator() const { return getBlock()->getTerminator(); } static bool classof(const ProgramPoint* Location) { return Location->getKind() == BlockExitKind; } }; class PostStmt : public ProgramPoint { protected: PostStmt(const Stmt* S, Kind k,const void *tag = 0) : ProgramPoint(S, k, tag) {} PostStmt(const Stmt* S, const void* data, bool, const void *tag =0) : ProgramPoint(S, data, true, tag) {} public: PostStmt(const Stmt* S, const void *tag = 0) : ProgramPoint(S, PostStmtKind, tag) {} Stmt* getStmt() const { return (Stmt*) getData1(); } static bool classof(const ProgramPoint* Location) { unsigned k = Location->getKind(); return k >= MinPostStmtKind && k <= MaxPostStmtKind; } }; class PostLocationChecksSucceed : public PostStmt { public: PostLocationChecksSucceed(const Stmt* S, const void *tag = 0) : PostStmt(S, PostLocationChecksSucceedKind, tag) {} static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostLocationChecksSucceedKind; } }; class PostStmtCustom : public PostStmt { public: PostStmtCustom(const Stmt* S, const std::pair<const void*, const void*>* TaggedData) : PostStmt(S, TaggedData, true) { assert(getKind() == PostStmtCustomKind); } const std::pair<const void*, const void*>& getTaggedPair() const { return *reinterpret_cast<std::pair<const void*, const void*>*>(getData2()); } const void* getTag() const { return getTaggedPair().first; } const void* getTaggedData() const { return getTaggedPair().second; } static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostStmtCustomKind; } }; class PostOutOfBoundsCheckFailed : public PostStmt { public: PostOutOfBoundsCheckFailed(const Stmt* S, const void *tag = 0) : PostStmt(S, PostOutOfBoundsCheckFailedKind, tag) {} static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostOutOfBoundsCheckFailedKind; } }; class PostUndefLocationCheckFailed : public PostStmt { public: PostUndefLocationCheckFailed(const Stmt* S, const void *tag = 0) : PostStmt(S, PostUndefLocationCheckFailedKind, tag) {} static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostUndefLocationCheckFailedKind; } }; class PostNullCheckFailed : public PostStmt { public: PostNullCheckFailed(const Stmt* S, const void *tag = 0) : PostStmt(S, PostNullCheckFailedKind, tag) {} static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostNullCheckFailedKind; } }; class PostLoad : public PostStmt { public: PostLoad(const Stmt* S, const void *tag = 0) : PostStmt(S, PostLoadKind, tag) {} static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostLoadKind; } }; class PostStore : public PostStmt { public: PostStore(const Stmt* S, const void *tag = 0) : PostStmt(S, PostStoreKind, tag) {} static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostStoreKind; } }; class PostPurgeDeadSymbols : public PostStmt { public: PostPurgeDeadSymbols(const Stmt* S, const void *tag = 0) : PostStmt(S, PostPurgeDeadSymbolsKind, tag) {} static bool classof(const ProgramPoint* Location) { return Location->getKind() == PostPurgeDeadSymbolsKind; } }; class BlockEdge : public ProgramPoint { public: BlockEdge(const CFGBlock* B1, const CFGBlock* B2) : ProgramPoint(B1, B2) {} CFGBlock* getSrc() const { return static_cast<CFGBlock*>(getData1()); } CFGBlock* getDst() const { return static_cast<CFGBlock*>(getData2()); } static bool classof(const ProgramPoint* Location) { return Location->getKind() == BlockEdgeKind; } }; } // end namespace clang namespace llvm { // Traits specialization for DenseMap template <> struct DenseMapInfo<clang::ProgramPoint> { static inline clang::ProgramPoint getEmptyKey() { uintptr_t x = reinterpret_cast<uintptr_t>(DenseMapInfo<void*>::getEmptyKey()) & ~0x7; return clang::BlockEntrance(reinterpret_cast<clang::CFGBlock*>(x)); } static inline clang::ProgramPoint getTombstoneKey() { uintptr_t x = reinterpret_cast<uintptr_t>(DenseMapInfo<void*>::getTombstoneKey()) & ~0x7; return clang::BlockEntrance(reinterpret_cast<clang::CFGBlock*>(x)); } static unsigned getHashValue(const clang::ProgramPoint& Loc) { return Loc.getHashValue(); } static bool isEqual(const clang::ProgramPoint& L, const clang::ProgramPoint& R) { return L == R; } static bool isPod() { return true; } }; } // end namespace llvm #endif <file_sep>/test/CodeGen/string-init.c // RUN: clang-cc -emit-llvm %s -o %t && // RUN: grep 'internal constant \[10 x i8\]' %t && // RUN: not grep -F "[5 x i8]" %t && // RUN: not grep "store " %t void test(void) { char a[10] = "asdf"; char b[10] = { "asdf" }; } <file_sep>/test/Coverage/codegen.c // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm -o %t %s && // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm-bc -o %t %s && // RUN: clang-cc -triple i386-unknown-unknown -g -emit-llvm-bc -o %t %s && // RUN: clang-cc -triple x86_64-unknown-unknown -emit-llvm-bc -o %t %s && // RUN: clang-cc -triple x86_64-unknown-unknown -g -emit-llvm-bc -o %t %s #include "c-language-features.inc" <file_sep>/test/SemaCXX/expressions.cpp // RUN: clang-cc -fsyntax-only -verify %s void choice(int); int choice(bool); void test() { // Result of ! must be type bool. int i = choice(!1); } <file_sep>/test/CodeGen/2008-08-19-cast-of-typedef.c // RUN: clang-cc --emit-llvm -o %t %s typedef short T[4]; struct s { T f0; }; void foo(struct s *x) { bar((long) x->f0); } <file_sep>/include/clang/AST/PPCBuiltins.def //===--- PPCBuiltins.def - PowerPC Builtin function database ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PowerPC-specific builtin function database. Users of // this file must define the BUILTIN macro to make use of this information. // //===----------------------------------------------------------------------===// // FIXME: this needs to be the full list supported by GCC. Right now, I'm just // adding stuff on demand. // The format of this database matches clang/AST/Builtins.def. // This is just a placeholder, the types and attributes are wrong. BUILTIN(__builtin_altivec_abs_v4sf , "ii" , "nc") // FIXME: Obviously incomplete. #undef BUILTIN <file_sep>/test/CodeGen/rdr-6098585-empty-case-range.c // RUN: clang-cc -triple i386-unknown-unknown --emit-llvm-bc -o - %s | opt -std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32" %t | count 2 && // RUN: grep "ret i32 3" %t | count 2 // This generated incorrect code because of poor switch chaining. int f1(int x) { switch(x) { default: return 3; case 10 ... 0xFFFFFFFF: return 0; } } // This just asserted because of the way case ranges were calculated. int f2(int x) { switch (x) { default: return 3; case 10 ... -1: return 0; } } <file_sep>/test/SemaCXX/enum.cpp // RUN: clang-cc -fsyntax-only -verify %s enum E { Val1, Val2 }; int& enumerator_type(int); float& enumerator_type(E); void f() { E e = Val1; float& fr = enumerator_type(Val2); } // <rdar://problem/6502934> typedef enum Foo { A = 0, B = 1 } Foo; void bar() { Foo myvar = A; myvar = B; } /// PR3688 struct s1 { enum e1 (*bar)(void); // expected-error{{ISO C++ forbids forward references to 'enum' types}} expected-note{{forward declaration of 'enum s1::e1'}} }; enum e1 { YES, NO }; static enum e1 badfunc(struct s1 *q) { return q->bar(); // expected-error{{return type of called function ('enum s1::e1') is incomplete}} } enum e2; // expected-error{{ISO C++ forbids forward references to 'enum' types}} <file_sep>/test/SemaCXX/static-cast.cpp // RUN: clang-cc -fsyntax-only -verify %s struct A {}; struct B : public A {}; // Single public base. struct C1 : public virtual B {}; // Single virtual base. struct C2 : public virtual B {}; struct D : public C1, public C2 {}; // Diamond struct E : private A {}; // Single private base. struct F : public C1 {}; // Single path to B with virtual. struct G1 : public B {}; struct G2 : public B {}; struct H : public G1, public G2 {}; // Ambiguous path to B. enum Enum { En1, En2 }; enum Onom { On1, On2 }; // Explicit implicits void t_529_2() { int i = 1; (void)static_cast<float>(i); double d = 1.0; (void)static_cast<float>(d); (void)static_cast<int>(d); (void)static_cast<char>(i); (void)static_cast<unsigned long>(i); (void)static_cast<int>(En1); (void)static_cast<double>(En1); (void)static_cast<int&>(i); (void)static_cast<const int&>(i); int ar[1]; (void)static_cast<const int*>(ar); (void)static_cast<void (*)()>(t_529_2); (void)static_cast<void*>(0); (void)static_cast<void*>((int*)0); (void)static_cast<volatile const void*>((const int*)0); (void)static_cast<A*>((B*)0); (void)static_cast<A&>(*((B*)0)); (void)static_cast<const B*>((C1*)0); (void)static_cast<B&>(*((C1*)0)); (void)static_cast<A*>((D*)0); (void)static_cast<const A&>(*((D*)0)); (void)static_cast<int B::*>((int A::*)0); (void)static_cast<void (B::*)()>((void (A::*)())0); // TODO: User-defined conversions // Bad code below (void)static_cast<void*>((const int*)0); // expected-error {{static_cast from 'int const *' to 'void *' is not allowed}} //(void)static_cast<A*>((E*)0); // {{static_cast from 'struct E *' to 'struct A *' is not allowed}} //(void)static_cast<A*>((H*)0); // {{static_cast from 'struct H *' to 'struct A *' is not allowed}} (void)static_cast<int>((int*)0); // expected-error {{static_cast from 'int *' to 'int' is not allowed}} (void)static_cast<A**>((B**)0); // expected-error {{static_cast from 'struct B **' to 'struct A **' is not allowed}} (void)static_cast<char&>(i); // expected-error {{non-const lvalue reference to type 'char' cannot be initialized with a value of type 'int'}} } // Anything to void void t_529_4() { static_cast<void>(1); static_cast<void>(t_529_4); } // Static downcasts void t_529_5_8() { (void)static_cast<B*>((A*)0); (void)static_cast<B&>(*((A*)0)); (void)static_cast<const G1*>((A*)0); (void)static_cast<const G1&>(*((A*)0)); // Bad code below (void)static_cast<C1*>((A*)0); // expected-error {{cannot cast 'struct A *' to 'struct C1 *' via virtual base 'struct B'}} (void)static_cast<C1&>(*((A*)0)); // expected-error {{cannot cast 'struct A' to 'struct C1 &' via virtual base 'struct B'}} (void)static_cast<D*>((A*)0); // expected-error {{cannot cast 'struct A *' to 'struct D *' via virtual base 'struct B'}} (void)static_cast<D&>(*((A*)0)); // expected-error {{cannot cast 'struct A' to 'struct D &' via virtual base 'struct B'}} (void)static_cast<B*>((const A*)0); // expected-error {{static_cast from 'struct A const *' to 'struct B *' casts away constness}} (void)static_cast<B&>(*((const A*)0)); // expected-error {{static_cast from 'struct A const' to 'struct B &' casts away constness}} // Accessibility is not yet tested //(void)static_cast<E*>((A*)0); // {{static_cast from 'struct A *' to 'struct E *' is not allowed}} //(void)static_cast<E&>(*((A*)0)); // {{static_cast from 'struct A' to 'struct E &' is not allowed}} (void)static_cast<H*>((A*)0); // expected-error {{ambiguous static_cast from base 'struct A' to derived 'struct H':\n struct A -> struct B -> struct G1 -> struct H\n struct A -> struct B -> struct G2 -> struct H}} (void)static_cast<H&>(*((A*)0)); // expected-error {{ambiguous static_cast from base 'struct A' to derived 'struct H':\n struct A -> struct B -> struct G1 -> struct H\n struct A -> struct B -> struct G2 -> struct H}} (void)static_cast<E*>((B*)0); // expected-error {{static_cast from 'struct B *' to 'struct E *' is not allowed}} (void)static_cast<E&>(*((B*)0)); // expected-error {{non-const lvalue reference to type 'struct E' cannot be initialized with a value of type 'struct B'}} // TODO: Test inaccessible base in context where it's accessible, i.e. // member function and friend. // TODO: Test DR427. This requires user-defined conversions, though. } // Enum conversions void t_529_7() { (void)static_cast<Enum>(1); (void)static_cast<Enum>(1.0); (void)static_cast<Onom>(En1); // Bad code below (void)static_cast<Enum>((int*)0); // expected-error {{static_cast from 'int *' to 'enum Enum' is not allowed}} } // Void pointer to object pointer void t_529_10() { (void)static_cast<int*>((void*)0); (void)static_cast<const A*>((void*)0); // Bad code below (void)static_cast<int*>((const void*)0); // expected-error {{static_cast from 'void const *' to 'int *' casts away constness}} (void)static_cast<void (*)()>((void*)0); // expected-error {{static_cast from 'void *' to 'void (*)(void)' is not allowed}} } // Member pointer upcast. void t_529_9() { (void)static_cast<int A::*>((int B::*)0); // Bad code below (void)static_cast<int A::*>((int H::*)0); // expected-error {{ambiguous conversion from pointer to member of derived class 'struct H'}} (void)static_cast<int A::*>((int F::*)0); // expected-error {{conversion from pointer to member of class 'struct F'}} } <file_sep>/lib/Driver/Tools.cpp //===--- Tools.cpp - Tools Implementations ------------------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Tools.h" #include "clang/Driver/Action.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Driver.h" // FIXME: Remove? #include "clang/Driver/DriverDiagnostic.h" // FIXME: Remove? #include "clang/Driver/Compilation.h" #include "clang/Driver/Job.h" #include "clang/Driver/HostInfo.h" #include "clang/Driver/Option.h" #include "clang/Driver/ToolChain.h" #include "clang/Driver/Util.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include "InputInfo.h" #include "ToolChains.h" using namespace clang::driver; using namespace clang::driver::tools; void Clang::AddPreprocessingOptions(const ArgList &Args, ArgStringList &CmdArgs, const InputInfo &Output, const InputInfoList &Inputs) const { // Handle dependency file generation. Arg *A; if ((A = Args.getLastArg(options::OPT_M)) || (A = Args.getLastArg(options::OPT_MM)) || (A = Args.getLastArg(options::OPT_MD)) || (A = Args.getLastArg(options::OPT_MMD))) { // Determine the output location. const char *DepFile; if (Output.getType() == types::TY_Dependencies) { if (Output.isPipe()) DepFile = "-"; else DepFile = Output.getFilename(); } else if (Arg *MF = Args.getLastArg(options::OPT_MF)) { DepFile = MF->getValue(Args); } else if (A->getOption().getId() == options::OPT_M || A->getOption().getId() == options::OPT_MM) { DepFile = "-"; } else { DepFile = darwin::CC1::getDependencyFileName(Args, Inputs); } CmdArgs.push_back("-dependency-file"); CmdArgs.push_back(DepFile); // Add an -MT option if the user didn't specify their own. // FIXME: This should use -MQ, when we support it. if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) { const char *DepTarget; // If user provided -o, that is the dependency target, except // when we are only generating a dependency file. Arg *OutputOpt = Args.getLastArg(options::OPT_o); if (OutputOpt && Output.getType() != types::TY_Dependencies) { DepTarget = OutputOpt->getValue(Args); } else { // Otherwise derive from the base input. // // FIXME: This should use the computed output file location. llvm::sys::Path P(Inputs[0].getBaseInput()); P.eraseSuffix(); P.appendSuffix("o"); DepTarget = Args.MakeArgString(P.getLast().c_str()); } CmdArgs.push_back("-MT"); CmdArgs.push_back(DepTarget); } if (A->getOption().getId() == options::OPT_M || A->getOption().getId() == options::OPT_MD) CmdArgs.push_back("-sys-header-deps"); } Args.AddLastArg(CmdArgs, options::OPT_MP); Args.AddAllArgs(CmdArgs, options::OPT_MT); // FIXME: Use iterator. // Add -i* options, and automatically translate to -include-pth for // transparent PCH support. It's wonky, but we include looking for // .gch so we can support seamless replacement into a build system // already set up to be generating .gch files. for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { const Arg *A = *it; if (!A->getOption().matches(options::OPT_clang_i_Group)) continue; if (A->getOption().matches(options::OPT_include)) { bool FoundPTH = false; llvm::sys::Path P(A->getValue(Args)); P.appendSuffix("pth"); if (P.exists()) { FoundPTH = true; } else { P.eraseSuffix(); P.appendSuffix("gch"); if (P.exists()) FoundPTH = true; } if (FoundPTH) { A->claim(); CmdArgs.push_back("-include-pth"); CmdArgs.push_back(Args.MakeArgString(P.c_str())); continue; } } // Not translated, render as usual. A->claim(); A->render(Args, CmdArgs); } Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U); Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F); // Add -Wp, and -Xassembler if using the preprocessor. // FIXME: There is a very unfortunate problem here, some troubled // souls abuse -Wp, to pass preprocessor options in gcc syntax. To // really support that we would have to parse and then translate // those options. :( Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA, options::OPT_Xpreprocessor); } void Clang::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { const Driver &D = getToolChain().getHost().getDriver(); ArgStringList CmdArgs; assert(Inputs.size() == 1 && "Unable to handle multiple inputs."); CmdArgs.push_back("-triple"); const char *TripleStr = Args.MakeArgString(getToolChain().getTripleString().c_str()); CmdArgs.push_back(TripleStr); if (isa<AnalyzeJobAction>(JA)) { assert(JA.getType() == types::TY_Plist && "Invalid output type."); CmdArgs.push_back("-analyze"); } else if (isa<PreprocessJobAction>(JA)) { if (Output.getType() == types::TY_Dependencies) CmdArgs.push_back("-Eonly"); else CmdArgs.push_back("-E"); } else if (isa<PrecompileJobAction>(JA)) { CmdArgs.push_back("-emit-pth"); } else { assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool."); if (JA.getType() == types::TY_Nothing) { CmdArgs.push_back("-fsyntax-only"); } else if (JA.getType() == types::TY_LLVMAsm) { CmdArgs.push_back("-emit-llvm"); } else if (JA.getType() == types::TY_LLVMBC) { CmdArgs.push_back("-emit-llvm-bc"); } else if (JA.getType() == types::TY_PP_Asm) { CmdArgs.push_back("-S"); } } // The make clang go fast button. CmdArgs.push_back("-disable-free"); // Set the main file name, so that debug info works even with // -save-temps. CmdArgs.push_back("-main-file-name"); CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs)); // Some flags which affect the language (via preprocessor // defines). See darwin::CC1::AddCPPArgs. if (Args.hasArg(options::OPT_static)) CmdArgs.push_back("-static-define"); if (isa<AnalyzeJobAction>(JA)) { // Add default argument set. // // FIXME: Move into clang? CmdArgs.push_back("-warn-dead-stores"); CmdArgs.push_back("-checker-cfref"); CmdArgs.push_back("-analyzer-eagerly-assume"); CmdArgs.push_back("-warn-objc-methodsigs"); // Do not enable the missing -dealloc check. // '-warn-objc-missing-dealloc', CmdArgs.push_back("-warn-objc-unused-ivars"); CmdArgs.push_back("-analyzer-output=plist"); // Add -Xanalyzer arguments when running as analyzer. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer); } else { // Perform argument translation for LLVM backend. This // takes some care in reconciling with llvm-gcc. The // issue is that llvm-gcc translates these options based on // the values in cc1, whereas we are processing based on // the driver arguments. // // FIXME: This is currently broken for -f flags when -fno // variants are present. // This comes from the default translation the driver + cc1 // would do to enable flag_pic. // // FIXME: Centralize this code. bool PICEnabled = (Args.hasArg(options::OPT_fPIC) || Args.hasArg(options::OPT_fpic) || Args.hasArg(options::OPT_fPIE) || Args.hasArg(options::OPT_fpie)); bool PICDisabled = (Args.hasArg(options::OPT_mkernel) || Args.hasArg(options::OPT_static)); const char *Model = getToolChain().GetForcedPicModel(); if (!Model) { if (Args.hasArg(options::OPT_mdynamic_no_pic)) Model = "dynamic-no-pic"; else if (PICDisabled) Model = "static"; else if (PICEnabled) Model = "pic"; else Model = getToolChain().GetDefaultRelocationModel(); } CmdArgs.push_back("--relocation-model"); CmdArgs.push_back(Model); // Infer the __PIC__ value. // // FIXME: This isn't quite right on Darwin, which always sets // __PIC__=2. if (strcmp(Model, "pic") == 0 || strcmp(Model, "dynamic-no-pic") == 0) { if (Args.hasArg(options::OPT_fPIC)) CmdArgs.push_back("-pic-level=2"); else CmdArgs.push_back("-pic-level=1"); } if (Args.hasArg(options::OPT_ftime_report)) CmdArgs.push_back("--time-passes"); // FIXME: Set --enable-unsafe-fp-math. if (!Args.hasArg(options::OPT_fomit_frame_pointer)) CmdArgs.push_back("--disable-fp-elim"); if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss, options::OPT_fno_zero_initialized_in_bss, true)) CmdArgs.push_back("--nozero-initialized-in-bss"); if (Args.hasArg(options::OPT_dA) || Args.hasArg(options::OPT_fverbose_asm)) CmdArgs.push_back("--asm-verbose"); if (Args.hasArg(options::OPT_fdebug_pass_structure)) CmdArgs.push_back("--debug-pass=Structure"); if (Args.hasArg(options::OPT_fdebug_pass_arguments)) CmdArgs.push_back("--debug-pass=Arguments"); // FIXME: set --inline-threshhold=50 if (optimize_size || optimize // < 3) if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables, getToolChain().IsUnwindTablesDefault())) CmdArgs.push_back("--unwind-tables=1"); else CmdArgs.push_back("--unwind-tables=0"); if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true)) CmdArgs.push_back("--disable-red-zone"); if (Args.hasFlag(options::OPT_msoft_float, options::OPT_mno_soft_float, false)) CmdArgs.push_back("--soft-float"); // FIXME: Need target hooks. if (memcmp(getToolChain().getPlatform().c_str(), "darwin", 6) == 0) { if (getToolChain().getArchName() == "x86_64") CmdArgs.push_back("--mcpu=core2"); else if (getToolChain().getArchName() == "i386") CmdArgs.push_back("--mcpu=yonah"); } // FIXME: Ignores ordering. Also, we need to find a realistic // solution for this. static const struct { options::ID Pos, Neg; const char *Name; } FeatureOptions[] = { { options::OPT_mmmx, options::OPT_mno_mmx, "mmx" }, { options::OPT_msse, options::OPT_mno_sse, "sse" }, { options::OPT_msse2, options::OPT_mno_sse2, "sse2" }, { options::OPT_msse3, options::OPT_mno_sse3, "sse3" }, { options::OPT_mssse3, options::OPT_mno_ssse3, "ssse3" }, { options::OPT_msse41, options::OPT_mno_sse41, "sse41" }, { options::OPT_msse42, options::OPT_mno_sse42, "sse42" }, { options::OPT_msse4a, options::OPT_mno_sse4a, "sse4a" }, { options::OPT_m3dnow, options::OPT_mno_3dnow, "3dnow" }, { options::OPT_m3dnowa, options::OPT_mno_3dnowa, "3dnowa" } }; const unsigned NumFeatureOptions = sizeof(FeatureOptions)/sizeof(FeatureOptions[0]); // FIXME: Avoid std::string std::string Attrs; for (unsigned i=0; i < NumFeatureOptions; ++i) { if (Args.hasArg(FeatureOptions[i].Pos)) { if (!Attrs.empty()) Attrs += ','; Attrs += '+'; Attrs += FeatureOptions[i].Name; } else if (Args.hasArg(FeatureOptions[i].Neg)) { if (!Attrs.empty()) Attrs += ','; Attrs += '-'; Attrs += FeatureOptions[i].Name; } } if (!Attrs.empty()) { CmdArgs.push_back("--mattr"); CmdArgs.push_back(Args.MakeArgString(Attrs.c_str())); } if (Args.hasFlag(options::OPT_fmath_errno, options::OPT_fno_math_errno, getToolChain().IsMathErrnoDefault())) CmdArgs.push_back("--fmath-errno=1"); else CmdArgs.push_back("--fmath-errno=0"); if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) { CmdArgs.push_back("--limit-float-precision"); CmdArgs.push_back(A->getValue(Args)); } // FIXME: Add --stack-protector-buffer-size=<xxx> on // -fstack-protect. Arg *Unsupported; if ((Unsupported = Args.getLastArg(options::OPT_MG)) || (Unsupported = Args.getLastArg(options::OPT_MQ))) D.Diag(clang::diag::err_drv_unsupported_opt) << Unsupported->getOption().getName(); } Args.AddAllArgs(CmdArgs, options::OPT_v); Args.AddLastArg(CmdArgs, options::OPT_P); Args.AddLastArg(CmdArgs, options::OPT_mmacosx_version_min_EQ); Args.AddLastArg(CmdArgs, options::OPT_miphoneos_version_min_EQ); // Special case debug options to only pass -g to clang. This is // wrong. if (Args.hasArg(options::OPT_g_Group)) CmdArgs.push_back("-g"); Args.AddLastArg(CmdArgs, options::OPT_nostdinc); Args.AddLastArg(CmdArgs, options::OPT_isysroot); // Add preprocessing options like -I, -D, etc. if we are using the // preprocessor. // // FIXME: Support -fpreprocessed types::ID InputType = Inputs[0].getType(); if (types::getPreprocessedType(InputType) != types::TY_INVALID) AddPreprocessingOptions(Args, CmdArgs, Output, Inputs); // Manually translate -O to -O1 and -O4 to -O3; let clang reject // others. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { if (A->getOption().getId() == options::OPT_O4) CmdArgs.push_back("-O3"); else if (A->getValue(Args)[0] == '\0') CmdArgs.push_back("-O1"); else A->render(Args, CmdArgs); } Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group); Args.AddLastArg(CmdArgs, options::OPT_w); // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi} // (-ansi is equivalent to -std=c89). // // If a std is supplied, only add -trigraphs if it follows the // option. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) { if (Std->getOption().matches(options::OPT_ansi)) CmdArgs.push_back("-std=c89"); else Std->render(Args, CmdArgs); if (Arg *A = Args.getLastArg(options::OPT_trigraphs)) if (A->getIndex() > Std->getIndex()) A->render(Args, CmdArgs); } else Args.AddLastArg(CmdArgs, options::OPT_trigraphs); if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_)) { CmdArgs.push_back("-ftemplate-depth"); CmdArgs.push_back(A->getValue(Args)); } // Forward -f options which we can pass directly. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls); Args.AddLastArg(CmdArgs, options::OPT_fexceptions); Args.AddLastArg(CmdArgs, options::OPT_ffreestanding); Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions); Args.AddLastArg(CmdArgs, options::OPT_fgnu_runtime); Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions); Args.AddLastArg(CmdArgs, options::OPT_fms_extensions); Args.AddLastArg(CmdArgs, options::OPT_fnext_runtime); Args.AddLastArg(CmdArgs, options::OPT_fno_caret_diagnostics); Args.AddLastArg(CmdArgs, options::OPT_fno_show_column); Args.AddLastArg(CmdArgs, options::OPT_fobjc_gc_only); Args.AddLastArg(CmdArgs, options::OPT_fobjc_gc); // FIXME: Should we remove this? Args.AddLastArg(CmdArgs, options::OPT_fobjc_nonfragile_abi); Args.AddLastArg(CmdArgs, options::OPT_fprint_source_range_info); Args.AddLastArg(CmdArgs, options::OPT_ftime_report); Args.AddLastArg(CmdArgs, options::OPT_ftrapv); Args.AddLastArg(CmdArgs, options::OPT_fvisibility_EQ); Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings); // Forward -f options with positive and negative forms; we translate // these by hand. // -fbuiltin is default, only pass non-default. if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin)) CmdArgs.push_back("-fbuiltin=0"); // -fblocks default varies depending on platform and language; // -always pass if specified. if (Arg *A = Args.getLastArg(options::OPT_fblocks, options::OPT_fno_blocks)) { if (A->getOption().matches(options::OPT_fblocks)) CmdArgs.push_back("-fblocks"); else CmdArgs.push_back("-fblocks=0"); } // -fno-pascal-strings is default, only pass non-default. If the // -tool chain happened to translate to -mpascal-strings, we want to // -back translate here. // // FIXME: This is gross; that translation should be pulled from the // tool chain. if (Args.hasFlag(options::OPT_fpascal_strings, options::OPT_fno_pascal_strings, false) || Args.hasFlag(options::OPT_mpascal_strings, options::OPT_mno_pascal_strings, false)) CmdArgs.push_back("-fpascal-strings"); // -fcommon is default, only pass non-default. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common)) CmdArgs.push_back("-fno-common"); // -fsigned-bitfields is default, and clang doesn't yet support // --funsigned-bitfields. if (!Args.hasFlag(options::OPT_fsigned_bitfields, options::OPT_funsigned_bitfields)) D.Diag(clang::diag::warn_drv_clang_unsupported) << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args); // Enable -fdiagnostics-show-option by default. if (Args.hasFlag(options::OPT_fdiagnostics_show_option, options::OPT_fno_diagnostics_show_option)) CmdArgs.push_back("-fdiagnostics-show-option"); Args.AddLastArg(CmdArgs, options::OPT_dM); Args.AddLastArg(CmdArgs, options::OPT_dD); Args.AddAllArgValues(CmdArgs, options::OPT_Xclang); if (Output.getType() == types::TY_Dependencies) { // Handled with other dependency code. } else if (Output.isPipe()) { CmdArgs.push_back("-o"); CmdArgs.push_back("-"); } else if (Output.isFilename()) { CmdArgs.push_back("-o"); CmdArgs.push_back(Output.getFilename()); } else { assert(Output.isNothing() && "Invalid output."); } for (InputInfoList::const_iterator it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { const InputInfo &II = *it; CmdArgs.push_back("-x"); CmdArgs.push_back(types::getTypeName(II.getType())); if (II.isPipe()) CmdArgs.push_back("-"); else if (II.isFilename()) CmdArgs.push_back(II.getFilename()); else II.getInputArg().renderAsInput(Args, CmdArgs); } const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, "clang-cc").c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); // Explicitly warn that these options are unsupported, even though // we are allowing compilation to continue. // FIXME: Use iterator. for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(options::OPT_pg)) { A->claim(); D.Diag(clang::diag::warn_drv_clang_unsupported) << A->getAsString(Args); } } // Claim some arguments which clang supports automatically. // -fpch-preprocess is used with gcc to add a special marker in the // -output to include the PCH file. Clang's PTH solution is // -completely transparent, so we do not need to deal with it at // -all. Args.ClaimAllArgs(options::OPT_fpch_preprocess); // Claim some arguments which clang doesn't support, but we don't // care to warn the user about. // FIXME: Use iterator. for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(options::OPT_clang_ignored_f_Group) || A->getOption().matches(options::OPT_clang_ignored_m_Group)) A->claim(); } } void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { ArgStringList CmdArgs; for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { Arg *A = *it; if (A->getOption().hasForwardToGCC()) { // It is unfortunate that we have to claim here, as this means // we will basically never report anything interesting for // platforms using a generic gcc. A->claim(); A->render(Args, CmdArgs); } } RenderExtraToolArgs(CmdArgs); // If using a driver driver, force the arch. if (getToolChain().getHost().useDriverDriver()) { CmdArgs.push_back("-arch"); // FIXME: Remove these special cases. const char *Str = getToolChain().getArchName().c_str(); if (strcmp(Str, "powerpc") == 0) Str = "ppc"; else if (strcmp(Str, "powerpc64") == 0) Str = "ppc64"; CmdArgs.push_back(Str); } if (Output.isPipe()) { CmdArgs.push_back("-o"); CmdArgs.push_back("-"); } else if (Output.isFilename()) { CmdArgs.push_back("-o"); CmdArgs.push_back(Output.getFilename()); } else { assert(Output.isNothing() && "Unexpected output"); CmdArgs.push_back("-fsyntax-only"); } // Only pass -x if gcc will understand it; otherwise hope gcc // understands the suffix correctly. The main use case this would go // wrong in is for linker inputs if they happened to have an odd // suffix; really the only way to get this to happen is a command // like '-x foobar a.c' which will treat a.c like a linker input. // // FIXME: For the linker case specifically, can we safely convert // inputs into '-Wl,' options? for (InputInfoList::const_iterator it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { const InputInfo &II = *it; if (types::canTypeBeUserSpecified(II.getType())) { CmdArgs.push_back("-x"); CmdArgs.push_back(types::getTypeName(II.getType())); } if (II.isPipe()) CmdArgs.push_back("-"); else if (II.isFilename()) CmdArgs.push_back(II.getFilename()); else // Don't render as input, we need gcc to do the translations. II.getInputArg().render(Args, CmdArgs); } const char *GCCName = getToolChain().getHost().getDriver().CCCGenericGCCName.c_str(); const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, GCCName).c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); } void gcc::Preprocess::RenderExtraToolArgs(ArgStringList &CmdArgs) const { CmdArgs.push_back("-E"); } void gcc::Precompile::RenderExtraToolArgs(ArgStringList &CmdArgs) const { // The type is good enough. } void gcc::Compile::RenderExtraToolArgs(ArgStringList &CmdArgs) const { CmdArgs.push_back("-S"); } void gcc::Assemble::RenderExtraToolArgs(ArgStringList &CmdArgs) const { CmdArgs.push_back("-c"); } void gcc::Link::RenderExtraToolArgs(ArgStringList &CmdArgs) const { // The types are (hopefully) good enough. } const char *darwin::CC1::getCC1Name(types::ID Type) const { switch (Type) { default: assert(0 && "Unexpected type for Darwin CC1 tool."); case types::TY_Asm: case types::TY_C: case types::TY_CHeader: case types::TY_PP_C: case types::TY_PP_CHeader: return "cc1"; case types::TY_ObjC: case types::TY_ObjCHeader: case types::TY_PP_ObjC: case types::TY_PP_ObjCHeader: return "cc1obj"; case types::TY_CXX: case types::TY_CXXHeader: case types::TY_PP_CXX: case types::TY_PP_CXXHeader: return "cc1plus"; case types::TY_ObjCXX: case types::TY_ObjCXXHeader: case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXXHeader: return "cc1objplus"; } } const char *darwin::CC1::getBaseInputName(const ArgList &Args, const InputInfoList &Inputs) { llvm::sys::Path P(Inputs[0].getBaseInput()); return Args.MakeArgString(P.getLast().c_str()); } const char *darwin::CC1::getBaseInputStem(const ArgList &Args, const InputInfoList &Inputs) { const char *Str = getBaseInputName(Args, Inputs); if (const char *End = strchr(Str, '.')) return Args.MakeArgString(std::string(Str, End).c_str()); return Str; } const char * darwin::CC1::getDependencyFileName(const ArgList &Args, const InputInfoList &Inputs) { // FIXME: Think about this more. std::string Res; if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { std::string Str(OutputOpt->getValue(Args)); Res = Str.substr(0, Str.rfind('.')); } else Res = darwin::CC1::getBaseInputStem(Args, Inputs); return Args.MakeArgString((Res + ".d").c_str()); } void darwin::CC1::AddCC1Args(const ArgList &Args, ArgStringList &CmdArgs) const { // Derived from cc1 spec. // FIXME: -fapple-kext seems to disable this too. Investigate. if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) && !Args.hasArg(options::OPT_mdynamic_no_pic)) CmdArgs.push_back("-fPIC"); // gcc has some code here to deal with when no -mmacosx-version-min // and no -miphoneos-version-min is present, but this never happens // due to tool chain specific argument translation. // FIXME: Remove mthumb // FIXME: Remove mno-thumb // FIXME: Remove faltivec // FIXME: Remove mno-fused-madd // FIXME: Remove mlong-branch // FIXME: Remove mlongcall // FIXME: Remove mcpu=G4 // FIXME: Remove mcpu=G5 if (Args.hasArg(options::OPT_g_Flag) && !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols)) CmdArgs.push_back("-feliminate-unused-debug-symbols"); } void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, const InputInfoList &Inputs, const ArgStringList &OutputArgs) const { const Driver &D = getToolChain().getHost().getDriver(); // Derived from cc1_options spec. if (Args.hasArg(options::OPT_fast) || Args.hasArg(options::OPT_fastf) || Args.hasArg(options::OPT_fastcp)) CmdArgs.push_back("-O3"); if (Arg *A = Args.getLastArg(options::OPT_pg)) if (Args.hasArg(options::OPT_fomit_frame_pointer)) D.Diag(clang::diag::err_drv_argument_not_allowed_with) << A->getAsString(Args) << "-fomit-frame-pointer"; AddCC1Args(Args, CmdArgs); if (!Args.hasArg(options::OPT_Q)) CmdArgs.push_back("-quiet"); CmdArgs.push_back("-dumpbase"); CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs)); Args.AddAllArgs(CmdArgs, options::OPT_d_Group); Args.AddAllArgs(CmdArgs, options::OPT_m_Group); Args.AddAllArgs(CmdArgs, options::OPT_a_Group); // FIXME: The goal is to use the user provided -o if that is our // final output, otherwise to drive from the original input // name. Find a clean way to go about this. if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) && Args.hasArg(options::OPT_o)) { Arg *OutputOpt = Args.getLastArg(options::OPT_o); CmdArgs.push_back("-auxbase-strip"); CmdArgs.push_back(OutputOpt->getValue(Args)); } else { CmdArgs.push_back("-auxbase"); CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs)); } Args.AddAllArgs(CmdArgs, options::OPT_g_Group); Args.AddAllArgs(CmdArgs, options::OPT_O); // FIXME: -Wall is getting some special treatment. Investigate. Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group); Args.AddLastArg(CmdArgs, options::OPT_w); Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi, options::OPT_trigraphs); if (Args.hasArg(options::OPT_v)) CmdArgs.push_back("-version"); if (Args.hasArg(options::OPT_pg)) CmdArgs.push_back("-p"); Args.AddLastArg(CmdArgs, options::OPT_p); // The driver treats -fsyntax-only specially. Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only); Args.AddAllArgs(CmdArgs, options::OPT_undef); if (Args.hasArg(options::OPT_Qn)) CmdArgs.push_back("-fno-ident"); // FIXME: This isn't correct. //Args.AddLastArg(CmdArgs, options::OPT__help) //Args.AddLastArg(CmdArgs, options::OPT__targetHelp) CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); // FIXME: Still don't get what is happening here. Investigate. Args.AddAllArgs(CmdArgs, options::OPT__param); if (Args.hasArg(options::OPT_fmudflap) || Args.hasArg(options::OPT_fmudflapth)) { CmdArgs.push_back("-fno-builtin"); CmdArgs.push_back("-fno-merge-constants"); } if (Args.hasArg(options::OPT_coverage)) { CmdArgs.push_back("-fprofile-arcs"); CmdArgs.push_back("-ftest-coverage"); } if (types::isCXX(Inputs[0].getType())) CmdArgs.push_back("-D__private_extern__=extern"); } void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, const InputInfoList &Inputs, const ArgStringList &OutputArgs) const { // Derived from cpp_options AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs); CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); AddCC1Args(Args, CmdArgs); // NOTE: The code below has some commonality with cpp_options, but // in classic gcc style ends up sending things in different // orders. This may be a good merge candidate once we drop pedantic // compatibility. Args.AddAllArgs(CmdArgs, options::OPT_m_Group); Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi, options::OPT_trigraphs); Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group); Args.AddLastArg(CmdArgs, options::OPT_w); // The driver treats -fsyntax-only specially. Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only); if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) && !Args.hasArg(options::OPT_fno_working_directory)) CmdArgs.push_back("-fworking-directory"); Args.AddAllArgs(CmdArgs, options::OPT_O); Args.AddAllArgs(CmdArgs, options::OPT_undef); if (Args.hasArg(options::OPT_save_temps)) CmdArgs.push_back("-fpch-preprocess"); } void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, const InputInfoList &Inputs) const { const Driver &D = getToolChain().getHost().getDriver(); // Derived from cpp_unique_options. Arg *A; if ((A = Args.getLastArg(options::OPT_C)) || (A = Args.getLastArg(options::OPT_CC))) { if (!Args.hasArg(options::OPT_E)) D.Diag(clang::diag::err_drv_argument_only_allowed_with) << A->getAsString(Args) << "-E"; } if (!Args.hasArg(options::OPT_Q)) CmdArgs.push_back("-quiet"); Args.AddAllArgs(CmdArgs, options::OPT_nostdinc); Args.AddLastArg(CmdArgs, options::OPT_v); Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F); Args.AddLastArg(CmdArgs, options::OPT_P); // FIXME: Handle %I properly. if (getToolChain().getArchName() == "x86_64") { CmdArgs.push_back("-imultilib"); CmdArgs.push_back("x86_64"); } if (Args.hasArg(options::OPT_MD)) { CmdArgs.push_back("-MD"); CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs)); } if (Args.hasArg(options::OPT_MMD)) { CmdArgs.push_back("-MMD"); CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs)); } Args.AddLastArg(CmdArgs, options::OPT_M); Args.AddLastArg(CmdArgs, options::OPT_MM); Args.AddAllArgs(CmdArgs, options::OPT_MF); Args.AddLastArg(CmdArgs, options::OPT_MG); Args.AddLastArg(CmdArgs, options::OPT_MP); Args.AddAllArgs(CmdArgs, options::OPT_MQ); Args.AddAllArgs(CmdArgs, options::OPT_MT); if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) && (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) { if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { CmdArgs.push_back("-MQ"); CmdArgs.push_back(OutputOpt->getValue(Args)); } } Args.AddLastArg(CmdArgs, options::OPT_remap); if (Args.hasArg(options::OPT_g3)) CmdArgs.push_back("-dD"); Args.AddLastArg(CmdArgs, options::OPT_H); AddCPPArgs(Args, CmdArgs); Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A); Args.AddAllArgs(CmdArgs, options::OPT_i_Group); for (InputInfoList::const_iterator it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { const InputInfo &II = *it; if (II.isPipe()) CmdArgs.push_back("-"); else CmdArgs.push_back(II.getFilename()); } Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA, options::OPT_Xpreprocessor); if (Args.hasArg(options::OPT_fmudflap)) { CmdArgs.push_back("-D_MUDFLAP"); CmdArgs.push_back("-include"); CmdArgs.push_back("mf-runtime.h"); } if (Args.hasArg(options::OPT_fmudflapth)) { CmdArgs.push_back("-D_MUDFLAP"); CmdArgs.push_back("-D_MUDFLAPTH"); CmdArgs.push_back("-include"); CmdArgs.push_back("mf-runtime.h"); } } void darwin::CC1::AddCPPArgs(const ArgList &Args, ArgStringList &CmdArgs) const { // Derived from cpp spec. if (Args.hasArg(options::OPT_static)) { // The gcc spec is broken here, it refers to dynamic but // that has been translated. Start by being bug compatible. // if (!Args.hasArg(arglist.parser.dynamicOption)) CmdArgs.push_back("-D__STATIC__"); } else CmdArgs.push_back("-D__DYNAMIC__"); if (Args.hasArg(options::OPT_pthread)) CmdArgs.push_back("-D_REENTRANT"); } void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { ArgStringList CmdArgs; assert(Inputs.size() == 1 && "Unexpected number of inputs!"); CmdArgs.push_back("-E"); if (Args.hasArg(options::OPT_traditional) || Args.hasArg(options::OPT_ftraditional) || Args.hasArg(options::OPT_traditional_cpp)) CmdArgs.push_back("-traditional-cpp"); ArgStringList OutputArgs; if (Output.isFilename()) { OutputArgs.push_back("-o"); OutputArgs.push_back(Output.getFilename()); } else { assert(Output.isPipe() && "Unexpected CC1 output."); } if (Args.hasArg(options::OPT_E)) { AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs); } else { AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList()); CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); } Args.AddAllArgs(CmdArgs, options::OPT_d_Group); const char *CC1Name = getCC1Name(Inputs[0].getType()); const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, CC1Name).c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); } void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { const Driver &D = getToolChain().getHost().getDriver(); ArgStringList CmdArgs; assert(Inputs.size() == 1 && "Unexpected number of inputs!"); types::ID InputType = Inputs[0].getType(); const Arg *A; if ((A = Args.getLastArg(options::OPT_traditional)) || (A = Args.getLastArg(options::OPT_ftraditional))) D.Diag(clang::diag::err_drv_argument_only_allowed_with) << A->getAsString(Args) << "-E"; if (Output.getType() == types::TY_LLVMAsm) CmdArgs.push_back("-emit-llvm"); else if (Output.getType() == types::TY_LLVMBC) CmdArgs.push_back("-emit-llvm-bc"); ArgStringList OutputArgs; if (Output.getType() != types::TY_PCH) { OutputArgs.push_back("-o"); if (Output.isPipe()) OutputArgs.push_back("-"); else if (Output.isNothing()) OutputArgs.push_back("/dev/null"); else OutputArgs.push_back(Output.getFilename()); } // There is no need for this level of compatibility, but it makes // diffing easier. bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) || Args.hasArg(options::OPT_S)); if (types::getPreprocessedType(InputType) != types::TY_INVALID) { AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs); if (OutputArgsEarly) { AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs); } else { AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList()); CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); } } else { CmdArgs.push_back("-fpreprocessed"); // FIXME: There is a spec command to remove // -fpredictive-compilation args here. Investigate. for (InputInfoList::const_iterator it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { const InputInfo &II = *it; if (II.isPipe()) CmdArgs.push_back("-"); else CmdArgs.push_back(II.getFilename()); } if (OutputArgsEarly) { AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs); } else { AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList()); CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); } } if (Output.getType() == types::TY_PCH) { assert(Output.isFilename() && "Invalid PCH output."); CmdArgs.push_back("-o"); // NOTE: gcc uses a temp .s file for this, but there doesn't seem // to be a good reason. CmdArgs.push_back("/dev/null"); CmdArgs.push_back("--output-pch="); CmdArgs.push_back(Output.getFilename()); } const char *CC1Name = getCC1Name(Inputs[0].getType()); const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, CC1Name).c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); } void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { ArgStringList CmdArgs; assert(Inputs.size() == 1 && "Unexpected number of inputs."); const InputInfo &Input = Inputs[0]; // Bit of a hack, this is only used for original inputs. // // FIXME: This is broken for preprocessed .s inputs. if (Input.isFilename() && strcmp(Input.getFilename(), Input.getBaseInput()) == 0) { if (Args.hasArg(options::OPT_gstabs)) CmdArgs.push_back("--gstabs"); else if (Args.hasArg(options::OPT_g_Group)) CmdArgs.push_back("--gdwarf2"); } // Derived from asm spec. CmdArgs.push_back("-arch"); CmdArgs.push_back(getToolChain().getArchName().c_str()); CmdArgs.push_back("-force_cpusubtype_ALL"); if ((Args.hasArg(options::OPT_mkernel) || Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_fapple_kext)) && !Args.hasArg(options::OPT_dynamic)) CmdArgs.push_back("-static"); Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler); assert(Output.isFilename() && "Unexpected lipo output."); CmdArgs.push_back("-o"); CmdArgs.push_back(Output.getFilename()); if (Input.isPipe()) { CmdArgs.push_back("-"); } else { assert(Input.isFilename() && "Invalid input."); CmdArgs.push_back(Input.getFilename()); } // asm_final spec is empty. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, "as").c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); } static const char *MakeFormattedString(const ArgList &Args, const llvm::format_object_base &Fmt) { std::string Str; llvm::raw_string_ostream(Str) << Fmt; return Args.MakeArgString(Str.c_str()); } /// Helper routine for seeing if we should use dsymutil; this is a /// gcc compatible hack, we should remove it and use the input /// type information. static bool isSourceSuffix(const char *Str) { // match: 'C', 'CPP', 'c', 'cc', 'cp', 'c++', 'cpp', 'cxx', 'm', // 'mm'. switch (strlen(Str)) { default: return false; case 1: return (memcmp(Str, "C", 1) == 0 || memcmp(Str, "c", 1) == 0 || memcmp(Str, "m", 1) == 0); case 2: return (memcmp(Str, "cc", 2) == 0 || memcmp(Str, "cp", 2) == 0 || memcmp(Str, "mm", 2) == 0); case 3: return (memcmp(Str, "CPP", 3) == 0 || memcmp(Str, "c++", 3) == 0 || memcmp(Str, "cpp", 3) == 0 || memcmp(Str, "cxx", 3) == 0); } } static bool isMacosxVersionLT(unsigned (&A)[3], unsigned (&B)[3]) { for (unsigned i=0; i < 3; ++i) { if (A[i] > B[i]) return false; if (A[i] < B[i]) return true; } return false; } static bool isMacosxVersionLT(unsigned (&A)[3], unsigned V0, unsigned V1=0, unsigned V2=0) { unsigned B[3] = { V0, V1, V2 }; return isMacosxVersionLT(A, B); } const toolchains::Darwin_X86 &darwin::Link::getDarwinToolChain() const { return reinterpret_cast<const toolchains::Darwin_X86&>(getToolChain()); } void darwin::Link::AddDarwinArch(const ArgList &Args, ArgStringList &CmdArgs) const { // Derived from darwin_arch spec. CmdArgs.push_back("-arch"); CmdArgs.push_back(getToolChain().getArchName().c_str()); } void darwin::Link::AddDarwinSubArch(const ArgList &Args, ArgStringList &CmdArgs) const { // Derived from darwin_subarch spec, not sure what the distinction // exists for but at least for this chain it is the same. AddDarwinArch(Args, CmdArgs); } void darwin::Link::AddLinkArgs(const ArgList &Args, ArgStringList &CmdArgs) const { const Driver &D = getToolChain().getHost().getDriver(); // Derived from the "link" spec. Args.AddAllArgs(CmdArgs, options::OPT_static); if (!Args.hasArg(options::OPT_static)) CmdArgs.push_back("-dynamic"); if (Args.hasArg(options::OPT_fgnu_runtime)) { // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu // here. How do we wish to handle such things? } if (!Args.hasArg(options::OPT_dynamiclib)) { if (Args.hasArg(options::OPT_force__cpusubtype__ALL)) { AddDarwinArch(Args, CmdArgs); CmdArgs.push_back("-force_cpusubtype_ALL"); } else AddDarwinSubArch(Args, CmdArgs); Args.AddLastArg(CmdArgs, options::OPT_bundle); Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader); Args.AddAllArgs(CmdArgs, options::OPT_client__name); Arg *A; if ((A = Args.getLastArg(options::OPT_compatibility__version)) || (A = Args.getLastArg(options::OPT_current__version)) || (A = Args.getLastArg(options::OPT_install__name))) D.Diag(clang::diag::err_drv_argument_only_allowed_with) << A->getAsString(Args) << "-dynamiclib"; Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace); Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs); Args.AddLastArg(CmdArgs, options::OPT_private__bundle); } else { CmdArgs.push_back("-dylib"); Arg *A; if ((A = Args.getLastArg(options::OPT_bundle)) || (A = Args.getLastArg(options::OPT_bundle__loader)) || (A = Args.getLastArg(options::OPT_client__name)) || (A = Args.getLastArg(options::OPT_force__flat__namespace)) || (A = Args.getLastArg(options::OPT_keep__private__externs)) || (A = Args.getLastArg(options::OPT_private__bundle))) D.Diag(clang::diag::err_drv_argument_not_allowed_with) << A->getAsString(Args) << "-dynamiclib"; Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version, "-dylib_compatibility_version"); Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version, "-dylib_current_version"); if (Args.hasArg(options::OPT_force__cpusubtype__ALL)) { AddDarwinArch(Args, CmdArgs); // NOTE: We don't add -force_cpusubtype_ALL on this path. Ok. } else AddDarwinSubArch(Args, CmdArgs); Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name, "-dylib_install_name"); } Args.AddLastArg(CmdArgs, options::OPT_all__load); Args.AddAllArgs(CmdArgs, options::OPT_allowable__client); Args.AddLastArg(CmdArgs, options::OPT_bind__at__load); Args.AddLastArg(CmdArgs, options::OPT_dead__strip); Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms); Args.AddAllArgs(CmdArgs, options::OPT_dylib__file); Args.AddLastArg(CmdArgs, options::OPT_dynamic); Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list); Args.AddLastArg(CmdArgs, options::OPT_flat__namespace); Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names); Args.AddAllArgs(CmdArgs, options::OPT_image__base); Args.AddAllArgs(CmdArgs, options::OPT_init); if (!Args.hasArg(options::OPT_mmacosx_version_min_EQ)) { if (!Args.hasArg(options::OPT_miphoneos_version_min_EQ)) { // FIXME: I don't understand what is going on here. This is // supposed to come from darwin_ld_minversion, but gcc doesn't // seem to be following that; it must be getting overridden // somewhere. CmdArgs.push_back("-macosx_version_min"); CmdArgs.push_back(getDarwinToolChain().getMacosxVersionStr()); } } else { // Adding all arguments doesn't make sense here but this is what // gcc does. Args.AddAllArgsTranslated(CmdArgs, options::OPT_mmacosx_version_min_EQ, "-macosx_version_min"); } Args.AddAllArgsTranslated(CmdArgs, options::OPT_miphoneos_version_min_EQ, "-iphoneos_version_min"); Args.AddLastArg(CmdArgs, options::OPT_nomultidefs); Args.AddLastArg(CmdArgs, options::OPT_multi__module); Args.AddLastArg(CmdArgs, options::OPT_single__module); Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined); Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused); if (Args.hasArg(options::OPT_fpie)) CmdArgs.push_back("-pie"); Args.AddLastArg(CmdArgs, options::OPT_prebind); Args.AddLastArg(CmdArgs, options::OPT_noprebind); Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding); Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules); Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs); Args.AddAllArgs(CmdArgs, options::OPT_sectcreate); Args.AddAllArgs(CmdArgs, options::OPT_sectorder); Args.AddAllArgs(CmdArgs, options::OPT_seg1addr); Args.AddAllArgs(CmdArgs, options::OPT_segprot); Args.AddAllArgs(CmdArgs, options::OPT_segaddr); Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr); Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr); Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table); Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename); Args.AddAllArgs(CmdArgs, options::OPT_sub__library); Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella); Args.AddAllArgsTranslated(CmdArgs, options::OPT_isysroot, "-syslibroot"); Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace); Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints); Args.AddAllArgs(CmdArgs, options::OPT_umbrella); Args.AddAllArgs(CmdArgs, options::OPT_undefined); Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list); Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches); if (!Args.hasArg(options::OPT_weak__reference__mismatches)) { CmdArgs.push_back("-weak_reference_mismatches"); CmdArgs.push_back("non-weak"); } Args.AddLastArg(CmdArgs, options::OPT_X_Flag); Args.AddAllArgs(CmdArgs, options::OPT_y); Args.AddLastArg(CmdArgs, options::OPT_w); Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size); Args.AddAllArgs(CmdArgs, options::OPT_segs__read__); Args.AddLastArg(CmdArgs, options::OPT_seglinkedit); Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit); Args.AddAllArgs(CmdArgs, options::OPT_sectalign); Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols); Args.AddAllArgs(CmdArgs, options::OPT_segcreate); Args.AddLastArg(CmdArgs, options::OPT_whyload); Args.AddLastArg(CmdArgs, options::OPT_whatsloaded); Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name); Args.AddLastArg(CmdArgs, options::OPT_dylinker); Args.AddLastArg(CmdArgs, options::OPT_Mach); } void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { assert(Output.getType() == types::TY_Image && "Invalid linker output type."); // The logic here is derived from gcc's behavior; most of which // comes from specs (starting with link_command). Consult gcc for // more information. // FIXME: The spec references -fdump= which seems to have // disappeared? ArgStringList CmdArgs; // I'm not sure why this particular decomposition exists in gcc, but // we follow suite for ease of comparison. AddLinkArgs(Args, CmdArgs); // FIXME: gcc has %{x} in here. How could this ever happen? Cruft? Args.AddAllArgs(CmdArgs, options::OPT_d_Flag); Args.AddAllArgs(CmdArgs, options::OPT_s); Args.AddAllArgs(CmdArgs, options::OPT_t); Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag); Args.AddAllArgs(CmdArgs, options::OPT_u_Group); Args.AddAllArgs(CmdArgs, options::OPT_A); Args.AddLastArg(CmdArgs, options::OPT_e); Args.AddAllArgs(CmdArgs, options::OPT_m_Separate); Args.AddAllArgs(CmdArgs, options::OPT_r); // FIXME: This is just being pedantically bug compatible, gcc // doesn't *mean* to forward this, it just does (yay for pattern // matching). It doesn't work, of course. Args.AddAllArgs(CmdArgs, options::OPT_object); CmdArgs.push_back("-o"); CmdArgs.push_back(Output.getFilename()); unsigned MacosxVersion[3]; if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ)) { bool HadExtra; if (!Driver::GetReleaseVersion(A->getValue(Args), MacosxVersion[0], MacosxVersion[1], MacosxVersion[2], HadExtra) || HadExtra) { const Driver &D = getToolChain().getHost().getDriver(); D.Diag(clang::diag::err_drv_invalid_version_number) << A->getAsString(Args); } } else { getDarwinToolChain().getMacosxVersion(MacosxVersion); } if (!Args.hasArg(options::OPT_A) && !Args.hasArg(options::OPT_nostdlib) && !Args.hasArg(options::OPT_nostartfiles)) { // Derived from startfile spec. if (Args.hasArg(options::OPT_dynamiclib)) { // Derived from darwin_dylib1 spec. if (isMacosxVersionLT(MacosxVersion, 10, 5)) CmdArgs.push_back("-ldylib1.o"); else if (isMacosxVersionLT(MacosxVersion, 10, 6)) CmdArgs.push_back("-ldylib1.10.5.o"); } else { if (Args.hasArg(options::OPT_bundle)) { if (!Args.hasArg(options::OPT_static)) { // Derived from darwin_bundle1 spec. if (isMacosxVersionLT(MacosxVersion, 10, 6)) CmdArgs.push_back("-lbundle1.o"); } } else { if (Args.hasArg(options::OPT_pg)) { if (Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_object) || Args.hasArg(options::OPT_preload)) { CmdArgs.push_back("-lgcrt0.o"); } else { CmdArgs.push_back("-lgcrt1.o"); // darwin_crt2 spec is empty. } } else { if (Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_object) || Args.hasArg(options::OPT_preload)) { CmdArgs.push_back("-lcrt0.o"); } else { // Derived from darwin_crt1 spec. if (isMacosxVersionLT(MacosxVersion, 10, 5)) CmdArgs.push_back("-lcrt1.o"); else if (isMacosxVersionLT(MacosxVersion, 10, 6)) CmdArgs.push_back("-lcrt1.10.5.o"); else CmdArgs.push_back("-lcrt1.10.6.o"); // darwin_crt2 spec is empty. } } } } if (Args.hasArg(options::OPT_shared_libgcc) && !Args.hasArg(options::OPT_miphoneos_version_min_EQ) && isMacosxVersionLT(MacosxVersion, 10, 5)) { const char *Str = getToolChain().GetFilePath(C, "crt3.o").c_str(); CmdArgs.push_back(Args.MakeArgString(Str)); } } Args.AddAllArgs(CmdArgs, options::OPT_L); if (Args.hasArg(options::OPT_fopenmp)) // This is more complicated in gcc... CmdArgs.push_back("-lgomp"); // FIXME: Derive these correctly. const char *TCDir = getDarwinToolChain().getToolChainDir().c_str(); if (getToolChain().getArchName() == "x86_64") { CmdArgs.push_back(MakeFormattedString(Args, llvm::format("-L/usr/lib/gcc/%s/x86_64", TCDir))); // Intentionally duplicated for (temporary) gcc bug compatibility. CmdArgs.push_back(MakeFormattedString(Args, llvm::format("-L/usr/lib/gcc/%s/x86_64", TCDir))); } CmdArgs.push_back(MakeFormattedString(Args, llvm::format("-L/usr/lib/%s", TCDir))); CmdArgs.push_back(MakeFormattedString(Args, llvm::format("-L/usr/lib/gcc/%s", TCDir))); // Intentionally duplicated for (temporary) gcc bug compatibility. CmdArgs.push_back(MakeFormattedString(Args, llvm::format("-L/usr/lib/gcc/%s", TCDir))); CmdArgs.push_back(MakeFormattedString(Args, llvm::format("-L/usr/lib/gcc/%s/../../../%s", TCDir, TCDir))); CmdArgs.push_back(MakeFormattedString(Args, llvm::format("-L/usr/lib/gcc/%s/../../..", TCDir))); for (InputInfoList::const_iterator it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { const InputInfo &II = *it; if (II.isFilename()) CmdArgs.push_back(II.getFilename()); else II.getInputArg().renderAsInput(Args, CmdArgs); } if (LinkingOutput) { CmdArgs.push_back("-arch_multiple"); CmdArgs.push_back("-final_output"); CmdArgs.push_back(LinkingOutput); } if (Args.hasArg(options::OPT_fprofile_arcs) || Args.hasArg(options::OPT_fprofile_generate) || Args.hasArg(options::OPT_fcreate_profile) || Args.hasArg(options::OPT_coverage)) CmdArgs.push_back("-lgcov"); if (Args.hasArg(options::OPT_fnested_functions)) CmdArgs.push_back("-allow_stack_execute"); if (!Args.hasArg(options::OPT_nostdlib) && !Args.hasArg(options::OPT_nodefaultlibs)) { // FIXME: g++ is more complicated here, it tries to put -lstdc++ // before -lm, for example. if (getToolChain().getHost().getDriver().CCCIsCXX) CmdArgs.push_back("-lstdc++"); // link_ssp spec is empty. // Derived from libgcc and lib specs but refactored. if (Args.hasArg(options::OPT_static)) { CmdArgs.push_back("-lgcc_static"); } else { if (Args.hasArg(options::OPT_static_libgcc)) { CmdArgs.push_back("-lgcc_eh"); } else if (Args.hasArg(options::OPT_miphoneos_version_min_EQ)) { // Derived from darwin_iphoneos_libgcc spec. CmdArgs.push_back("-lgcc_s.10.5"); } else if (Args.hasArg(options::OPT_shared_libgcc) || Args.hasArg(options::OPT_fexceptions) || Args.hasArg(options::OPT_fgnu_runtime)) { // FIXME: This is probably broken on 10.3? if (isMacosxVersionLT(MacosxVersion, 10, 5)) CmdArgs.push_back("-lgcc_s.10.4"); else if (isMacosxVersionLT(MacosxVersion, 10, 6)) CmdArgs.push_back("-lgcc_s.10.5"); } else { if (isMacosxVersionLT(MacosxVersion, 10, 3, 9)) ; // Do nothing. else if (isMacosxVersionLT(MacosxVersion, 10, 5)) CmdArgs.push_back("-lgcc_s.10.4"); else if (isMacosxVersionLT(MacosxVersion, 10, 6)) CmdArgs.push_back("-lgcc_s.10.5"); } if (isMacosxVersionLT(MacosxVersion, 10, 6)) { CmdArgs.push_back("-lgcc"); CmdArgs.push_back("-lSystem"); } else { CmdArgs.push_back("-lSystem"); CmdArgs.push_back("-lgcc"); } } } if (!Args.hasArg(options::OPT_A) && !Args.hasArg(options::OPT_nostdlib) && !Args.hasArg(options::OPT_nostartfiles)) { // endfile_spec is empty. } Args.AddAllArgs(CmdArgs, options::OPT_T_Group); Args.AddAllArgs(CmdArgs, options::OPT_F); const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, "collect2").c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); // Find the first non-empty base input (we want to ignore linker // inputs). const char *BaseInput = ""; for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { if (Inputs[i].getBaseInput()[0] != '\0') { BaseInput = Inputs[i].getBaseInput(); break; } } if (Args.getLastArg(options::OPT_g_Group) && !Args.getLastArg(options::OPT_gstabs) && !Args.getLastArg(options::OPT_g0)) { // FIXME: This is gross, but matches gcc. The test only considers // the suffix (not the -x type), and then only of the first // source input. Awesome. const char *Suffix = strrchr(BaseInput, '.'); if (Suffix && isSourceSuffix(Suffix + 1)) { const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, "dsymutil").c_str()); ArgStringList CmdArgs; CmdArgs.push_back(Output.getFilename()); C.getJobs().addCommand(new Command(Exec, CmdArgs)); } } } void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { ArgStringList CmdArgs; CmdArgs.push_back("-create"); assert(Output.isFilename() && "Unexpected lipo output."); CmdArgs.push_back("-output"); CmdArgs.push_back(Output.getFilename()); for (InputInfoList::const_iterator it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { const InputInfo &II = *it; assert(II.isFilename() && "Unexpected lipo input."); CmdArgs.push_back(II.getFilename()); } const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, "lipo").c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); } void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { ArgStringList CmdArgs; // When building 32-bit code on FreeBSD/amd64, we have to explicitly // instruct as in the base system to assemble 32-bit code. if (getToolChain().getArchName() == "i386") CmdArgs.push_back("--32"); Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler); CmdArgs.push_back("-o"); if (Output.isPipe()) CmdArgs.push_back("-"); else CmdArgs.push_back(Output.getFilename()); for (InputInfoList::const_iterator it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { const InputInfo &II = *it; if (II.isPipe()) CmdArgs.push_back("-"); else CmdArgs.push_back(II.getFilename()); } const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, "as").c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); } void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA, Job &Dest, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { ArgStringList CmdArgs; if (Args.hasArg(options::OPT_static)) { CmdArgs.push_back("-Bstatic"); } else { CmdArgs.push_back("--eh-frame-hdr"); if (Args.hasArg(options::OPT_shared)) { CmdArgs.push_back("-Bshareable"); } else { CmdArgs.push_back("-dynamic-linker"); CmdArgs.push_back("/libexec/ld-elf.so.1"); } } // When building 32-bit code on FreeBSD/amd64, we have to explicitly // instruct ld in the base system to link 32-bit code. if (getToolChain().getArchName() == "i386") { CmdArgs.push_back("-m"); CmdArgs.push_back("elf_i386_fbsd"); } if (Output.isPipe()) { CmdArgs.push_back("-o"); CmdArgs.push_back("-"); } else if (Output.isFilename()) { CmdArgs.push_back("-o"); CmdArgs.push_back(Output.getFilename()); } else { assert(Output.isNothing() && "Invalid output."); } if (!Args.hasArg(options::OPT_nostdlib) && !Args.hasArg(options::OPT_nostartfiles)) { if (!Args.hasArg(options::OPT_shared)) { CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crt1.o").c_str())); CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crti.o").c_str())); CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbegin.o").c_str())); } else { CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crti.o").c_str())); CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtbeginS.o").c_str())); } } Args.AddAllArgs(CmdArgs, options::OPT_L); Args.AddAllArgs(CmdArgs, options::OPT_T_Group); Args.AddAllArgs(CmdArgs, options::OPT_e); for (InputInfoList::const_iterator it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { const InputInfo &II = *it; if (II.isPipe()) CmdArgs.push_back("-"); else if (II.isFilename()) CmdArgs.push_back(II.getFilename()); else II.getInputArg().renderAsInput(Args, CmdArgs); } if (!Args.hasArg(options::OPT_nostdlib) && !Args.hasArg(options::OPT_nodefaultlibs)) { // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding // the default system libraries. Just mimic this for now. CmdArgs.push_back("-lgcc"); if (Args.hasArg(options::OPT_static)) { CmdArgs.push_back("-lgcc_eh"); } else { CmdArgs.push_back("--as-needed"); CmdArgs.push_back("-lgcc_s"); CmdArgs.push_back("--no-as-needed"); } if (Args.hasArg(options::OPT_pthread)) CmdArgs.push_back("-lpthread"); CmdArgs.push_back("-lc"); CmdArgs.push_back("-lgcc"); if (Args.hasArg(options::OPT_static)) { CmdArgs.push_back("-lgcc_eh"); } else { CmdArgs.push_back("--as-needed"); CmdArgs.push_back("-lgcc_s"); CmdArgs.push_back("--no-as-needed"); } } if (!Args.hasArg(options::OPT_nostdlib) && !Args.hasArg(options::OPT_nostartfiles)) { if (!Args.hasArg(options::OPT_shared)) CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtend.o").c_str())); else CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtendS.o").c_str())); CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(C, "crtn.o").c_str())); } const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(C, "ld").c_str()); Dest.addCommand(new Command(Exec, CmdArgs)); } <file_sep>/test/SemaCXX/wchar_t.cpp // RUN: clang-cc -fsyntax-only -pedantic -verify %s wchar_t x; void f(wchar_t p) { wchar_t x; unsigned wchar_t y; // expected-warning {{'wchar_t' cannot be signed or unsigned}} signed wchar_t z; // expected-warning {{'wchar_t' cannot be signed or unsigned}} ++x; } <file_sep>/test/CodeGen/emit-all-decls.c // RUN: clang-cc -emit-llvm -o %t %s && // RUN: not grep "@foo" %t && // RUN: clang-cc -femit-all-decls -emit-llvm -o %t %s && // RUN: grep "@foo" %t static void foo() { } <file_sep>/utils/builtin-defines.c /* This is a clang style test case for checking that preprocessor defines match gcc. */ /* RUN: for arch in -m32 -m64; do \ RUN: for lang in -std=gnu89 -ansi -std=c99 -std=gnu99; do \ RUN: for input in c objective-c; do \ RUN: for opts in "-O0" "-O1 -dynamic" "-O2 -static" "-Os"; do \ RUN: echo "-- $arch, $lang, $input, $opts --"; \ RUN: for cc in 0 1; do \ RUN: if [ "$cc" == 0 ]; then \ RUN: cc_prog=clang; \ RUN: output=%t0; \ RUN: else \ RUN: cc_prog=gcc; \ RUN: output=%t1; \ RUN: fi; \ RUN: $cc_prog $arch $lang $opts -dM -E -x $input %s | sort > $output; \ RUN: done; \ RUN: if (! diff %t0 %t1); then exit 1; fi; \ RUN: done; \ RUN: done; \ RUN: done; \ RUN: done; */ /* We don't care about this difference */ #ifdef __PIC__ #if __PIC__ == 1 #undef __PIC__ #undef __pic__ #define __PIC__ 2 #define __pic__ 2 #endif #endif /* Undefine things we don't expect to match. */ #undef __DEC_EVAL_METHOD__ #undef __INT16_TYPE__ #undef __INT32_TYPE__ #undef __INT64_TYPE__ #undef __INT8_TYPE__ #undef __SSP__ #undef __APPLE_CC__ #undef __VERSION__ #undef __clang__ #undef __llvm__ #undef __nocona #undef __nocona__ #undef __k8 #undef __k8__ #undef __tune_nocona__ #undef __tune_core2__ #undef __POINTER_WIDTH__ #undef __INTPTR_TYPE__ #undef __DEC128_DEN__ #undef __DEC128_EPSILON__ #undef __DEC128_MANT_DIG__ #undef __DEC128_MAX_EXP__ #undef __DEC128_MAX__ #undef __DEC128_MIN_EXP__ #undef __DEC128_MIN__ #undef __DEC32_DEN__ #undef __DEC32_EPSILON__ #undef __DEC32_MANT_DIG__ #undef __DEC32_MAX_EXP__ #undef __DEC32_MAX__ #undef __DEC32_MIN_EXP__ #undef __DEC32_MIN__ #undef __DEC64_DEN__ #undef __DEC64_EPSILON__ #undef __DEC64_MANT_DIG__ #undef __DEC64_MAX_EXP__ #undef __DEC64_MAX__ #undef __DEC64_MIN_EXP__ #undef __DEC64_MIN__ <file_sep>/lib/AST/StmtDumper.cpp //===--- StmtDumper.cpp - Dumping implementation for Stmt ASTs ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Stmt::dump/Stmt::print methods, which dump out the // AST in a form that exposes type details and other fields. // //===----------------------------------------------------------------------===// #include "clang/AST/StmtVisitor.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclCXX.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/Compiler.h" #include <cstdio> using namespace clang; //===----------------------------------------------------------------------===// // StmtDumper Visitor //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN StmtDumper : public StmtVisitor<StmtDumper> { SourceManager *SM; FILE *F; unsigned IndentLevel; /// MaxDepth - When doing a normal dump (not dumpAll) we only want to dump /// the first few levels of an AST. This keeps track of how many ast levels /// are left. unsigned MaxDepth; /// LastLocFilename/LastLocLine - Keep track of the last location we print /// out so that we can print out deltas from then on out. const char *LastLocFilename; unsigned LastLocLine; public: StmtDumper(SourceManager *sm, FILE *f, unsigned maxDepth) : SM(sm), F(f), IndentLevel(0-1), MaxDepth(maxDepth) { LastLocFilename = ""; LastLocLine = ~0U; } void DumpSubTree(Stmt *S) { // Prune the recursion if not using dump all. if (MaxDepth == 0) return; ++IndentLevel; if (S) { if (DeclStmt* DS = dyn_cast<DeclStmt>(S)) VisitDeclStmt(DS); else { Visit(S); // Print out children. Stmt::child_iterator CI = S->child_begin(), CE = S->child_end(); if (CI != CE) { while (CI != CE) { fprintf(F, "\n"); DumpSubTree(*CI++); } } fprintf(F, ")"); } } else { Indent(); fprintf(F, "<<<NULL>>>"); } --IndentLevel; } void DumpDeclarator(Decl *D); void Indent() const { for (int i = 0, e = IndentLevel; i < e; ++i) fprintf(F, " "); } void DumpType(QualType T) { fprintf(F, "'%s'", T.getAsString().c_str()); if (!T.isNull()) { // If the type is directly a typedef, strip off typedefness to give at // least one level of concreteness. if (TypedefType *TDT = dyn_cast<TypedefType>(T)) { QualType Simplified = TDT->LookThroughTypedefs().getQualifiedType(T.getCVRQualifiers()); fprintf(F, ":'%s'", Simplified.getAsString().c_str()); } } } void DumpStmt(const Stmt *Node) { Indent(); fprintf(F, "(%s %p", Node->getStmtClassName(), (void*)Node); DumpSourceRange(Node); } void DumpExpr(const Expr *Node) { DumpStmt(Node); fprintf(F, " "); DumpType(Node->getType()); } void DumpSourceRange(const Stmt *Node); void DumpLocation(SourceLocation Loc); // Stmts. void VisitStmt(Stmt *Node); void VisitDeclStmt(DeclStmt *Node); void VisitLabelStmt(LabelStmt *Node); void VisitGotoStmt(GotoStmt *Node); // Exprs void VisitExpr(Expr *Node); void VisitDeclRefExpr(DeclRefExpr *Node); void VisitPredefinedExpr(PredefinedExpr *Node); void VisitCharacterLiteral(CharacterLiteral *Node); void VisitIntegerLiteral(IntegerLiteral *Node); void VisitFloatingLiteral(FloatingLiteral *Node); void VisitStringLiteral(StringLiteral *Str); void VisitUnaryOperator(UnaryOperator *Node); void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *Node); void VisitMemberExpr(MemberExpr *Node); void VisitExtVectorElementExpr(ExtVectorElementExpr *Node); void VisitBinaryOperator(BinaryOperator *Node); void VisitCompoundAssignOperator(CompoundAssignOperator *Node); void VisitAddrLabelExpr(AddrLabelExpr *Node); void VisitTypesCompatibleExpr(TypesCompatibleExpr *Node); // C++ void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node); void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node); void VisitCXXThisExpr(CXXThisExpr *Node); void VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node); // ObjC void VisitObjCEncodeExpr(ObjCEncodeExpr *Node); void VisitObjCMessageExpr(ObjCMessageExpr* Node); void VisitObjCSelectorExpr(ObjCSelectorExpr *Node); void VisitObjCProtocolExpr(ObjCProtocolExpr *Node); void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node); void VisitObjCKVCRefExpr(ObjCKVCRefExpr *Node); void VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node); void VisitObjCSuperExpr(ObjCSuperExpr *Node); }; } //===----------------------------------------------------------------------===// // Utilities //===----------------------------------------------------------------------===// void StmtDumper::DumpLocation(SourceLocation Loc) { SourceLocation SpellingLoc = SM->getSpellingLoc(Loc); if (SpellingLoc.isInvalid()) { fprintf(stderr, "<invalid sloc>"); return; } // The general format we print out is filename:line:col, but we drop pieces // that haven't changed since the last loc printed. PresumedLoc PLoc = SM->getPresumedLoc(SpellingLoc); if (strcmp(PLoc.getFilename(), LastLocFilename) != 0) { fprintf(stderr, "%s:%u:%u", PLoc.getFilename(), PLoc.getLine(), PLoc.getColumn()); LastLocFilename = PLoc.getFilename(); LastLocLine = PLoc.getLine(); } else if (PLoc.getLine() != LastLocLine) { fprintf(stderr, "line:%u:%u", PLoc.getLine(), PLoc.getColumn()); LastLocLine = PLoc.getLine(); } else { fprintf(stderr, "col:%u", PLoc.getColumn()); } } void StmtDumper::DumpSourceRange(const Stmt *Node) { // Can't translate locations if a SourceManager isn't available. if (SM == 0) return; // TODO: If the parent expression is available, we can print a delta vs its // location. SourceRange R = Node->getSourceRange(); fprintf(stderr, " <"); DumpLocation(R.getBegin()); if (R.getBegin() != R.getEnd()) { fprintf(stderr, ", "); DumpLocation(R.getEnd()); } fprintf(stderr, ">"); // <t2.c:123:421[blah], t2.c:412:321> } //===----------------------------------------------------------------------===// // Stmt printing methods. //===----------------------------------------------------------------------===// void StmtDumper::VisitStmt(Stmt *Node) { DumpStmt(Node); } void StmtDumper::DumpDeclarator(Decl *D) { // FIXME: Need to complete/beautify this... this code simply shows the // nodes are where they need to be. if (TypedefDecl *localType = dyn_cast<TypedefDecl>(D)) { fprintf(F, "\"typedef %s %s\"", localType->getUnderlyingType().getAsString().c_str(), localType->getNameAsString().c_str()); } else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { fprintf(F, "\""); // Emit storage class for vardecls. if (VarDecl *V = dyn_cast<VarDecl>(VD)) { if (V->getStorageClass() != VarDecl::None) fprintf(F, "%s ", VarDecl::getStorageClassSpecifierString(V->getStorageClass())); } std::string Name = VD->getNameAsString(); VD->getType().getAsStringInternal(Name); fprintf(F, "%s", Name.c_str()); // If this is a vardecl with an initializer, emit it. if (VarDecl *V = dyn_cast<VarDecl>(VD)) { if (V->getInit()) { fprintf(F, " =\n"); DumpSubTree(V->getInit()); } } fprintf(F, "\""); } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { // print a free standing tag decl (e.g. "struct x;"). const char *tagname; if (const IdentifierInfo *II = TD->getIdentifier()) tagname = II->getName(); else tagname = "<anonymous>"; fprintf(F, "\"%s %s;\"", TD->getKindName(), tagname); // FIXME: print tag bodies. } else if (UsingDirectiveDecl *UD = dyn_cast<UsingDirectiveDecl>(D)) { // print using-directive decl (e.g. "using namespace x;") const char *ns; if (const IdentifierInfo *II = UD->getNominatedNamespace()->getIdentifier()) ns = II->getName(); else ns = "<anonymous>"; fprintf(F, "\"%s %s;\"",UD->getDeclKindName(), ns); } else { assert(0 && "Unexpected decl"); } } void StmtDumper::VisitDeclStmt(DeclStmt *Node) { DumpStmt(Node); fprintf(F,"\n"); for (DeclStmt::decl_iterator DI = Node->decl_begin(), DE = Node->decl_end(); DI != DE; ++DI) { Decl* D = *DI; ++IndentLevel; Indent(); fprintf(F, "%p ", (void*) D); DumpDeclarator(D); if (DI+1 != DE) fprintf(F,"\n"); --IndentLevel; } } void StmtDumper::VisitLabelStmt(LabelStmt *Node) { DumpStmt(Node); fprintf(F, " '%s'", Node->getName()); } void StmtDumper::VisitGotoStmt(GotoStmt *Node) { DumpStmt(Node); fprintf(F, " '%s':%p", Node->getLabel()->getName(), (void*)Node->getLabel()); } //===----------------------------------------------------------------------===// // Expr printing methods. //===----------------------------------------------------------------------===// void StmtDumper::VisitExpr(Expr *Node) { DumpExpr(Node); } void StmtDumper::VisitDeclRefExpr(DeclRefExpr *Node) { DumpExpr(Node); fprintf(F, " "); switch (Node->getDecl()->getKind()) { case Decl::Function: fprintf(F,"FunctionDecl"); break; case Decl::Var: fprintf(F,"Var"); break; case Decl::ParmVar: fprintf(F,"ParmVar"); break; case Decl::EnumConstant: fprintf(F,"EnumConstant"); break; case Decl::Typedef: fprintf(F,"Typedef"); break; case Decl::Record: fprintf(F,"Record"); break; case Decl::Enum: fprintf(F,"Enum"); break; case Decl::CXXRecord: fprintf(F,"CXXRecord"); break; case Decl::ObjCInterface: fprintf(F,"ObjCInterface"); break; case Decl::ObjCClass: fprintf(F,"ObjCClass"); break; default: fprintf(F,"Decl"); break; } fprintf(F, "='%s' %p", Node->getDecl()->getNameAsString().c_str(), (void*)Node->getDecl()); } void StmtDumper::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) { DumpExpr(Node); fprintf(F, " %sDecl='%s' %p", Node->getDecl()->getDeclKindName(), Node->getDecl()->getNameAsString().c_str(), (void*)Node->getDecl()); if (Node->isFreeIvar()) fprintf(F, " isFreeIvar"); } void StmtDumper::VisitPredefinedExpr(PredefinedExpr *Node) { DumpExpr(Node); switch (Node->getIdentType()) { default: assert(0 && "unknown case"); case PredefinedExpr::Func: fprintf(F, " __func__"); break; case PredefinedExpr::Function: fprintf(F, " __FUNCTION__"); break; case PredefinedExpr::PrettyFunction: fprintf(F, " __PRETTY_FUNCTION__");break; } } void StmtDumper::VisitCharacterLiteral(CharacterLiteral *Node) { DumpExpr(Node); fprintf(F, " %d", Node->getValue()); } void StmtDumper::VisitIntegerLiteral(IntegerLiteral *Node) { DumpExpr(Node); bool isSigned = Node->getType()->isSignedIntegerType(); fprintf(F, " %s", Node->getValue().toString(10, isSigned).c_str()); } void StmtDumper::VisitFloatingLiteral(FloatingLiteral *Node) { DumpExpr(Node); fprintf(F, " %f", Node->getValueAsApproximateDouble()); } void StmtDumper::VisitStringLiteral(StringLiteral *Str) { DumpExpr(Str); // FIXME: this doesn't print wstrings right. fprintf(F, " %s\"", Str->isWide() ? "L" : ""); for (unsigned i = 0, e = Str->getByteLength(); i != e; ++i) { switch (char C = Str->getStrData()[i]) { default: if (isprint(C)) fputc(C, F); else fprintf(F, "\\%03o", C); break; // Handle some common ones to make dumps prettier. case '\\': fprintf(F, "\\\\"); break; case '"': fprintf(F, "\\\""); break; case '\n': fprintf(F, "\\n"); break; case '\t': fprintf(F, "\\t"); break; case '\a': fprintf(F, "\\a"); break; case '\b': fprintf(F, "\\b"); break; } } fprintf(F, "\""); } void StmtDumper::VisitUnaryOperator(UnaryOperator *Node) { DumpExpr(Node); fprintf(F, " %s '%s'", Node->isPostfix() ? "postfix" : "prefix", UnaryOperator::getOpcodeStr(Node->getOpcode())); } void StmtDumper::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *Node) { DumpExpr(Node); fprintf(F, " %s ", Node->isSizeOf() ? "sizeof" : "alignof"); if (Node->isArgumentType()) DumpType(Node->getArgumentType()); } void StmtDumper::VisitMemberExpr(MemberExpr *Node) { DumpExpr(Node); fprintf(F, " %s%s %p", Node->isArrow() ? "->" : ".", Node->getMemberDecl()->getNameAsString().c_str(), (void*)Node->getMemberDecl()); } void StmtDumper::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) { DumpExpr(Node); fprintf(F, " %s", Node->getAccessor().getName()); } void StmtDumper::VisitBinaryOperator(BinaryOperator *Node) { DumpExpr(Node); fprintf(F, " '%s'", BinaryOperator::getOpcodeStr(Node->getOpcode())); } void StmtDumper::VisitCompoundAssignOperator(CompoundAssignOperator *Node) { DumpExpr(Node); fprintf(F, " '%s' ComputeLHSTy=", BinaryOperator::getOpcodeStr(Node->getOpcode())); DumpType(Node->getComputationLHSType()); fprintf(F, " ComputeResultTy="); DumpType(Node->getComputationResultType()); } // GNU extensions. void StmtDumper::VisitAddrLabelExpr(AddrLabelExpr *Node) { DumpExpr(Node); fprintf(F, " %s %p", Node->getLabel()->getName(), (void*)Node->getLabel()); } void StmtDumper::VisitTypesCompatibleExpr(TypesCompatibleExpr *Node) { DumpExpr(Node); fprintf(F, " "); DumpType(Node->getArgType1()); fprintf(F, " "); DumpType(Node->getArgType2()); } //===----------------------------------------------------------------------===// // C++ Expressions //===----------------------------------------------------------------------===// void StmtDumper::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) { DumpExpr(Node); fprintf(F, " %s<%s>", Node->getCastName(), Node->getTypeAsWritten().getAsString().c_str()); } void StmtDumper::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) { DumpExpr(Node); fprintf(F, " %s", Node->getValue() ? "true" : "false"); } void StmtDumper::VisitCXXThisExpr(CXXThisExpr *Node) { DumpExpr(Node); fprintf(F, " this"); } void StmtDumper::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) { DumpExpr(Node); fprintf(F, " functional cast to %s", Node->getTypeAsWritten().getAsString().c_str()); } //===----------------------------------------------------------------------===// // Obj-C Expressions //===----------------------------------------------------------------------===// void StmtDumper::VisitObjCMessageExpr(ObjCMessageExpr* Node) { DumpExpr(Node); fprintf(F, " selector=%s", Node->getSelector().getAsString().c_str()); IdentifierInfo* clsName = Node->getClassName(); if (clsName) fprintf(F, " class=%s", clsName->getName()); } void StmtDumper::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) { DumpExpr(Node); fprintf(F, " "); DumpType(Node->getEncodedType()); } void StmtDumper::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) { DumpExpr(Node); fprintf(F, " "); fprintf(F, "%s", Node->getSelector().getAsString().c_str()); } void StmtDumper::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) { DumpExpr(Node); fprintf(F, " "); fprintf(F, "%s", Node->getProtocol()->getNameAsString().c_str()); } void StmtDumper::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) { DumpExpr(Node); fprintf(F, " Kind=PropertyRef Property=\"%s\"", Node->getProperty()->getNameAsString().c_str()); } void StmtDumper::VisitObjCKVCRefExpr(ObjCKVCRefExpr *Node) { DumpExpr(Node); ObjCMethodDecl *Getter = Node->getGetterMethod(); ObjCMethodDecl *Setter = Node->getSetterMethod(); fprintf(F, " Kind=MethodRef Getter=\"%s\" Setter=\"%s\"", Getter->getSelector().getAsString().c_str(), Setter ? Setter->getSelector().getAsString().c_str() : "(null)"); } void StmtDumper::VisitObjCSuperExpr(ObjCSuperExpr *Node) { DumpExpr(Node); fprintf(F, " super"); } //===----------------------------------------------------------------------===// // Stmt method implementations //===----------------------------------------------------------------------===// /// dump - This does a local dump of the specified AST fragment. It dumps the /// specified node and a few nodes underneath it, but not the whole subtree. /// This is useful in a debugger. void Stmt::dump(SourceManager &SM) const { StmtDumper P(&SM, stderr, 4); P.DumpSubTree(const_cast<Stmt*>(this)); fprintf(stderr, "\n"); } /// dump - This does a local dump of the specified AST fragment. It dumps the /// specified node and a few nodes underneath it, but not the whole subtree. /// This is useful in a debugger. void Stmt::dump() const { StmtDumper P(0, stderr, 4); P.DumpSubTree(const_cast<Stmt*>(this)); fprintf(stderr, "\n"); } /// dumpAll - This does a dump of the specified AST fragment and all subtrees. void Stmt::dumpAll(SourceManager &SM) const { StmtDumper P(&SM, stderr, ~0U); P.DumpSubTree(const_cast<Stmt*>(this)); fprintf(stderr, "\n"); } /// dumpAll - This does a dump of the specified AST fragment and all subtrees. void Stmt::dumpAll() const { StmtDumper P(0, stderr, ~0U); P.DumpSubTree(const_cast<Stmt*>(this)); fprintf(stderr, "\n"); } <file_sep>/test/Sema/nonnull.c // RUN: clang-cc -fsyntax-only -verify %s int f1(int x) __attribute__((nonnull)); // expected-warning{{'nonnull' attribute applied to function with no pointer arguments}} int f2(int *x) __attribute__ ((nonnull (1))); int f3(int *x) __attribute__ ((nonnull (0))); // expected-error {{'nonnull' attribute parameter 1 is out of bounds}} int f4(int *x, int *y) __attribute__ ((nonnull (1,2))); int f5(int *x, int *y) __attribute__ ((nonnull (2,1))); <file_sep>/test/CodeGen/address-space-cast.c // RUN: clang-cc -emit-llvm < %s volatile unsigned char* const __attribute__((address_space(1))) serial_ctrl = 0x02; <file_sep>/include/clang/AST/RecordLayout.h //===--- RecordLayout.h - Layout information for a struct/union -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the RecordLayout interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_LAYOUTINFO_H #define LLVM_CLANG_AST_LAYOUTINFO_H #include "llvm/Support/DataTypes.h" namespace clang { class ASTContext; class RecordDecl; /// ASTRecordLayout - /// This class contains layout information for one RecordDecl, /// which is a struct/union/class. The decl represented must be a definition, /// not a forward declaration. /// This class is also used to contain layout informaiton for one /// ObjCInterfaceDecl. FIXME - Find appropriate name. /// These objects are managed by ASTContext. class ASTRecordLayout { uint64_t Size; // Size of record in bits. unsigned Alignment; // Alignment of record in bits. unsigned FieldCount; // Number of fields uint64_t *FieldOffsets; friend class ASTContext; ASTRecordLayout(uint64_t S = 0, unsigned A = 8) : Size(S), Alignment(A), FieldCount(0) {} ~ASTRecordLayout() { delete [] FieldOffsets; } /// Initialize record layout. N is the number of fields in this record. void InitializeLayout(unsigned N) { FieldCount = N; FieldOffsets = new uint64_t[N]; } /// Finalize record layout. Adjust record size based on the alignment. void FinalizeLayout() { // Finally, round the size of the record up to the alignment of the // record itself. Size = (Size + (Alignment-1)) & ~(Alignment-1); } void SetFieldOffset(unsigned FieldNo, uint64_t Offset) { assert (FieldNo < FieldCount && "Invalid Field No"); FieldOffsets[FieldNo] = Offset; } void SetAlignment(unsigned A) { Alignment = A; } /// LayoutField - Field layout. StructPacking is the specified /// packing alignment (maximum alignment) in bits to use for the /// structure, or 0 if no packing alignment is specified. void LayoutField(const FieldDecl *FD, unsigned FieldNo, bool IsUnion, unsigned StructPacking, ASTContext &Context); ASTRecordLayout(const ASTRecordLayout&); // DO NOT IMPLEMENT void operator=(const ASTRecordLayout&); // DO NOT IMPLEMENT public: unsigned getAlignment() const { return Alignment; } uint64_t getSize() const { return Size; } uint64_t getFieldOffset(unsigned FieldNo) const { assert (FieldNo < FieldCount && "Invalid Field No"); return FieldOffsets[FieldNo]; } }; } // end namespace clang #endif <file_sep>/include/clang/Analysis/PathSensitive/GRCoreEngine.h //==- GRCoreEngine.h - Path-Sensitive Dataflow Engine ------------------*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a generic engine for intraprocedural, path-sensitive, // dataflow analysis via graph reachability. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_GRENGINE #define LLVM_CLANG_ANALYSIS_GRENGINE #include "clang/AST/Expr.h" #include "clang/Analysis/PathSensitive/ExplodedGraph.h" #include "clang/Analysis/PathSensitive/GRWorkList.h" #include "clang/Analysis/PathSensitive/GRBlockCounter.h" #include "clang/Analysis/PathSensitive/GRAuditor.h" #include "llvm/ADT/OwningPtr.h" namespace clang { class GRStmtNodeBuilderImpl; class GRBranchNodeBuilderImpl; class GRIndirectGotoNodeBuilderImpl; class GRSwitchNodeBuilderImpl; class GREndPathNodeBuilderImpl; class GRWorkList; //===----------------------------------------------------------------------===// /// GRCoreEngineImpl - Implements the core logic of the graph-reachability /// analysis. It traverses the CFG and generates the ExplodedGraph. /// Program "states" are treated as opaque void pointers. /// The template class GRCoreEngine (which subclasses GRCoreEngineImpl) /// provides the matching component to the engine that knows the actual types /// for states. Note that this engine only dispatches to transfer functions /// at the statement and block-level. The analyses themselves must implement /// any transfer function logic and the sub-expression level (if any). class GRCoreEngineImpl { protected: friend class GRStmtNodeBuilderImpl; friend class GRBranchNodeBuilderImpl; friend class GRIndirectGotoNodeBuilderImpl; friend class GRSwitchNodeBuilderImpl; friend class GREndPathNodeBuilderImpl; /// G - The simulation graph. Each node is a (location,state) pair. llvm::OwningPtr<ExplodedGraphImpl> G; /// WList - A set of queued nodes that need to be processed by the /// worklist algorithm. It is up to the implementation of WList to decide /// the order that nodes are processed. GRWorkList* WList; /// BCounterFactory - A factory object for created GRBlockCounter objects. /// These are used to record for key nodes in the ExplodedGraph the /// number of times different CFGBlocks have been visited along a path. GRBlockCounter::Factory BCounterFactory; void GenerateNode(const ProgramPoint& Loc, const void* State, ExplodedNodeImpl* Pred); /// getInitialState - Gets the void* representing the initial 'state' /// of the analysis. This is simply a wrapper (implemented /// in GRCoreEngine) that performs type erasure on the initial /// state returned by the checker object. virtual const void* getInitialState() = 0; void HandleBlockEdge(const BlockEdge& E, ExplodedNodeImpl* Pred); void HandleBlockEntrance(const BlockEntrance& E, ExplodedNodeImpl* Pred); void HandleBlockExit(CFGBlock* B, ExplodedNodeImpl* Pred); void HandlePostStmt(const PostStmt& S, CFGBlock* B, unsigned StmtIdx, ExplodedNodeImpl *Pred); void HandleBranch(Stmt* Cond, Stmt* Term, CFGBlock* B, ExplodedNodeImpl* Pred); virtual void ProcessEndPath(GREndPathNodeBuilderImpl& Builder) = 0; virtual bool ProcessBlockEntrance(CFGBlock* Blk, const void* State, GRBlockCounter BC) = 0; virtual void ProcessStmt(Stmt* S, GRStmtNodeBuilderImpl& Builder) = 0; virtual void ProcessBranch(Stmt* Condition, Stmt* Terminator, GRBranchNodeBuilderImpl& Builder) = 0; virtual void ProcessIndirectGoto(GRIndirectGotoNodeBuilderImpl& Builder) = 0; virtual void ProcessSwitch(GRSwitchNodeBuilderImpl& Builder) = 0; private: GRCoreEngineImpl(const GRCoreEngineImpl&); // Do not implement. GRCoreEngineImpl& operator=(const GRCoreEngineImpl&); protected: GRCoreEngineImpl(ExplodedGraphImpl* g, GRWorkList* wl) : G(g), WList(wl), BCounterFactory(g->getAllocator()) {} public: /// ExecuteWorkList - Run the worklist algorithm for a maximum number of /// steps. Returns true if there is still simulation state on the worklist. bool ExecuteWorkList(unsigned Steps); virtual ~GRCoreEngineImpl(); CFG& getCFG() { return G->getCFG(); } }; class GRStmtNodeBuilderImpl { GRCoreEngineImpl& Eng; CFGBlock& B; const unsigned Idx; ExplodedNodeImpl* Pred; ExplodedNodeImpl* LastNode; typedef llvm::SmallPtrSet<ExplodedNodeImpl*,5> DeferredTy; DeferredTy Deferred; void GenerateAutoTransition(ExplodedNodeImpl* N); public: GRStmtNodeBuilderImpl(CFGBlock* b, unsigned idx, ExplodedNodeImpl* N, GRCoreEngineImpl* e); ~GRStmtNodeBuilderImpl(); ExplodedNodeImpl* getBasePredecessor() const { return Pred; } ExplodedNodeImpl* getLastNode() const { return LastNode ? (LastNode->isSink() ? NULL : LastNode) : NULL; } GRBlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter();} unsigned getCurrentBlockCount() const { return getBlockCounter().getNumVisited(B.getBlockID()); } ExplodedNodeImpl* generateNodeImpl(PostStmt PP, const void* State, ExplodedNodeImpl* Pred); ExplodedNodeImpl* generateNodeImpl(Stmt* S, const void* State, ExplodedNodeImpl* Pred, ProgramPoint::Kind K = ProgramPoint::PostStmtKind, const void *tag = 0); ExplodedNodeImpl* generateNodeImpl(Stmt* S, const void* State, ProgramPoint::Kind K = ProgramPoint::PostStmtKind, const void *tag = 0) { ExplodedNodeImpl* N = getLastNode(); assert (N && "Predecessor of new node is infeasible."); return generateNodeImpl(S, State, N, K, tag); } ExplodedNodeImpl* generateNodeImpl(Stmt* S, const void* State, const void *tag = 0) { ExplodedNodeImpl* N = getLastNode(); assert (N && "Predecessor of new node is infeasible."); return generateNodeImpl(S, State, N, ProgramPoint::PostStmtKind, tag); } /// getStmt - Return the current block-level expression associated with /// this builder. Stmt* getStmt() const { return B[Idx]; } /// getBlock - Return the CFGBlock associated with the block-level expression /// of this builder. CFGBlock* getBlock() const { return &B; } }; template<typename STATE> class GRStmtNodeBuilder { public: typedef STATE StateTy; typedef typename StateTy::ManagerTy StateManagerTy; typedef ExplodedNode<StateTy> NodeTy; private: GRStmtNodeBuilderImpl& NB; StateManagerTy& Mgr; const StateTy* CleanedState; GRAuditor<StateTy>* Auditor; public: GRStmtNodeBuilder(GRStmtNodeBuilderImpl& nb, StateManagerTy& mgr) : NB(nb), Mgr(mgr), Auditor(0), PurgingDeadSymbols(false), BuildSinks(false), HasGeneratedNode(false), PointKind(ProgramPoint::PostStmtKind), Tag(0) { CleanedState = getLastNode()->getState(); } void setAuditor(GRAuditor<StateTy>* A) { Auditor = A; } NodeTy* getLastNode() const { return static_cast<NodeTy*>(NB.getLastNode()); } NodeTy* generateNode(PostStmt PP, const StateTy* St, NodeTy* Pred) { return static_cast<NodeTy*>(NB.generateNodeImpl(PP, St, Pred)); } NodeTy* generateNode(Stmt* S, const StateTy* St, NodeTy* Pred, ProgramPoint::Kind K) { HasGeneratedNode = true; if (PurgingDeadSymbols) K = ProgramPoint::PostPurgeDeadSymbolsKind; return static_cast<NodeTy*>(NB.generateNodeImpl(S, St, Pred, K, Tag)); } NodeTy* generateNode(Stmt* S, const StateTy* St, NodeTy* Pred) { return generateNode(S, St, Pred, PointKind); } NodeTy* generateNode(Stmt* S, const StateTy* St, ProgramPoint::Kind K) { HasGeneratedNode = true; if (PurgingDeadSymbols) K = ProgramPoint::PostPurgeDeadSymbolsKind; return static_cast<NodeTy*>(NB.generateNodeImpl(S, St, K, Tag)); } NodeTy* generateNode(Stmt* S, const StateTy* St) { return generateNode(S, St, PointKind); } GRBlockCounter getBlockCounter() const { return NB.getBlockCounter(); } unsigned getCurrentBlockCount() const { return NB.getCurrentBlockCount(); } const StateTy* GetState(NodeTy* Pred) const { if ((ExplodedNodeImpl*) Pred == NB.getBasePredecessor()) return CleanedState; else return Pred->getState(); } void SetCleanedState(const StateTy* St) { CleanedState = St; } NodeTy* MakeNode(ExplodedNodeSet<StateTy>& Dst, Stmt* S, NodeTy* Pred, const StateTy* St) { return MakeNode(Dst, S, Pred, St, PointKind); } NodeTy* MakeNode(ExplodedNodeSet<StateTy>& Dst, Stmt* S, NodeTy* Pred, const StateTy* St, ProgramPoint::Kind K) { const StateTy* PredState = GetState(Pred); // If the state hasn't changed, don't generate a new node. if (!BuildSinks && St == PredState && Auditor == 0) { Dst.Add(Pred); return NULL; } NodeTy* N = generateNode(S, St, Pred, K); if (N) { if (BuildSinks) N->markAsSink(); else { if (Auditor && Auditor->Audit(N, Mgr)) N->markAsSink(); Dst.Add(N); } } return N; } NodeTy* MakeSinkNode(ExplodedNodeSet<StateTy>& Dst, Stmt* S, NodeTy* Pred, const StateTy* St) { bool Tmp = BuildSinks; BuildSinks = true; NodeTy* N = MakeNode(Dst, S, Pred, St); BuildSinks = Tmp; return N; } bool PurgingDeadSymbols; bool BuildSinks; bool HasGeneratedNode; ProgramPoint::Kind PointKind; const void *Tag; }; class GRBranchNodeBuilderImpl { GRCoreEngineImpl& Eng; CFGBlock* Src; CFGBlock* DstT; CFGBlock* DstF; ExplodedNodeImpl* Pred; typedef llvm::SmallVector<ExplodedNodeImpl*,3> DeferredTy; DeferredTy Deferred; bool GeneratedTrue; bool GeneratedFalse; public: GRBranchNodeBuilderImpl(CFGBlock* src, CFGBlock* dstT, CFGBlock* dstF, ExplodedNodeImpl* pred, GRCoreEngineImpl* e) : Eng(*e), Src(src), DstT(dstT), DstF(dstF), Pred(pred), GeneratedTrue(false), GeneratedFalse(false) {} ~GRBranchNodeBuilderImpl(); ExplodedNodeImpl* getPredecessor() const { return Pred; } const ExplodedGraphImpl& getGraph() const { return *Eng.G; } GRBlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter();} ExplodedNodeImpl* generateNodeImpl(const void* State, bool branch); CFGBlock* getTargetBlock(bool branch) const { return branch ? DstT : DstF; } void markInfeasible(bool branch) { if (branch) GeneratedTrue = true; else GeneratedFalse = true; } }; template<typename STATE> class GRBranchNodeBuilder { typedef STATE StateTy; typedef ExplodedGraph<StateTy> GraphTy; typedef typename GraphTy::NodeTy NodeTy; GRBranchNodeBuilderImpl& NB; public: GRBranchNodeBuilder(GRBranchNodeBuilderImpl& nb) : NB(nb) {} const GraphTy& getGraph() const { return static_cast<const GraphTy&>(NB.getGraph()); } NodeTy* getPredecessor() const { return static_cast<NodeTy*>(NB.getPredecessor()); } const StateTy* getState() const { return getPredecessor()->getState(); } NodeTy* generateNode(const StateTy* St, bool branch) { return static_cast<NodeTy*>(NB.generateNodeImpl(St, branch)); } GRBlockCounter getBlockCounter() const { return NB.getBlockCounter(); } CFGBlock* getTargetBlock(bool branch) const { return NB.getTargetBlock(branch); } void markInfeasible(bool branch) { NB.markInfeasible(branch); } }; class GRIndirectGotoNodeBuilderImpl { GRCoreEngineImpl& Eng; CFGBlock* Src; CFGBlock& DispatchBlock; Expr* E; ExplodedNodeImpl* Pred; public: GRIndirectGotoNodeBuilderImpl(ExplodedNodeImpl* pred, CFGBlock* src, Expr* e, CFGBlock* dispatch, GRCoreEngineImpl* eng) : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {} class Iterator { CFGBlock::succ_iterator I; friend class GRIndirectGotoNodeBuilderImpl; Iterator(CFGBlock::succ_iterator i) : I(i) {} public: Iterator& operator++() { ++I; return *this; } bool operator!=(const Iterator& X) const { return I != X.I; } LabelStmt* getLabel() const { return llvm::cast<LabelStmt>((*I)->getLabel()); } CFGBlock* getBlock() const { return *I; } }; Iterator begin() { return Iterator(DispatchBlock.succ_begin()); } Iterator end() { return Iterator(DispatchBlock.succ_end()); } ExplodedNodeImpl* generateNodeImpl(const Iterator& I, const void* State, bool isSink); Expr* getTarget() const { return E; } const void* getState() const { return Pred->State; } }; template<typename STATE> class GRIndirectGotoNodeBuilder { typedef STATE StateTy; typedef ExplodedGraph<StateTy> GraphTy; typedef typename GraphTy::NodeTy NodeTy; GRIndirectGotoNodeBuilderImpl& NB; public: GRIndirectGotoNodeBuilder(GRIndirectGotoNodeBuilderImpl& nb) : NB(nb) {} typedef GRIndirectGotoNodeBuilderImpl::Iterator iterator; iterator begin() { return NB.begin(); } iterator end() { return NB.end(); } Expr* getTarget() const { return NB.getTarget(); } NodeTy* generateNode(const iterator& I, const StateTy* St, bool isSink=false){ return static_cast<NodeTy*>(NB.generateNodeImpl(I, St, isSink)); } const StateTy* getState() const { return static_cast<const StateTy*>(NB.getState()); } }; class GRSwitchNodeBuilderImpl { GRCoreEngineImpl& Eng; CFGBlock* Src; Expr* Condition; ExplodedNodeImpl* Pred; public: GRSwitchNodeBuilderImpl(ExplodedNodeImpl* pred, CFGBlock* src, Expr* condition, GRCoreEngineImpl* eng) : Eng(*eng), Src(src), Condition(condition), Pred(pred) {} class Iterator { CFGBlock::succ_reverse_iterator I; friend class GRSwitchNodeBuilderImpl; Iterator(CFGBlock::succ_reverse_iterator i) : I(i) {} public: Iterator& operator++() { ++I; return *this; } bool operator!=(const Iterator& X) const { return I != X.I; } CaseStmt* getCase() const { return llvm::cast<CaseStmt>((*I)->getLabel()); } CFGBlock* getBlock() const { return *I; } }; Iterator begin() { return Iterator(Src->succ_rbegin()+1); } Iterator end() { return Iterator(Src->succ_rend()); } ExplodedNodeImpl* generateCaseStmtNodeImpl(const Iterator& I, const void* State); ExplodedNodeImpl* generateDefaultCaseNodeImpl(const void* State, bool isSink); Expr* getCondition() const { return Condition; } const void* getState() const { return Pred->State; } }; template<typename STATE> class GRSwitchNodeBuilder { typedef STATE StateTy; typedef ExplodedGraph<StateTy> GraphTy; typedef typename GraphTy::NodeTy NodeTy; GRSwitchNodeBuilderImpl& NB; public: GRSwitchNodeBuilder(GRSwitchNodeBuilderImpl& nb) : NB(nb) {} typedef GRSwitchNodeBuilderImpl::Iterator iterator; iterator begin() { return NB.begin(); } iterator end() { return NB.end(); } Expr* getCondition() const { return NB.getCondition(); } NodeTy* generateCaseStmtNode(const iterator& I, const StateTy* St) { return static_cast<NodeTy*>(NB.generateCaseStmtNodeImpl(I, St)); } NodeTy* generateDefaultCaseNode(const StateTy* St, bool isSink = false) { return static_cast<NodeTy*>(NB.generateDefaultCaseNodeImpl(St, isSink)); } const StateTy* getState() const { return static_cast<const StateTy*>(NB.getState()); } }; class GREndPathNodeBuilderImpl { GRCoreEngineImpl& Eng; CFGBlock& B; ExplodedNodeImpl* Pred; bool HasGeneratedNode; public: GREndPathNodeBuilderImpl(CFGBlock* b, ExplodedNodeImpl* N, GRCoreEngineImpl* e) : Eng(*e), B(*b), Pred(N), HasGeneratedNode(false) {} ~GREndPathNodeBuilderImpl(); ExplodedNodeImpl* getPredecessor() const { return Pred; } GRBlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter();} unsigned getCurrentBlockCount() const { return getBlockCounter().getNumVisited(B.getBlockID()); } ExplodedNodeImpl* generateNodeImpl(const void* State); CFGBlock* getBlock() const { return &B; } }; template<typename STATE> class GREndPathNodeBuilder { typedef STATE StateTy; typedef ExplodedNode<StateTy> NodeTy; GREndPathNodeBuilderImpl& NB; public: GREndPathNodeBuilder(GREndPathNodeBuilderImpl& nb) : NB(nb) {} NodeTy* getPredecessor() const { return static_cast<NodeTy*>(NB.getPredecessor()); } GRBlockCounter getBlockCounter() const { return NB.getBlockCounter(); } unsigned getCurrentBlockCount() const { return NB.getCurrentBlockCount(); } const StateTy* getState() const { return getPredecessor()->getState(); } NodeTy* MakeNode(const StateTy* St) { return static_cast<NodeTy*>(NB.generateNodeImpl(St)); } }; template<typename SUBENGINE> class GRCoreEngine : public GRCoreEngineImpl { public: typedef SUBENGINE SubEngineTy; typedef typename SubEngineTy::StateTy StateTy; typedef typename StateTy::ManagerTy StateManagerTy; typedef ExplodedGraph<StateTy> GraphTy; typedef typename GraphTy::NodeTy NodeTy; protected: SubEngineTy& SubEngine; virtual const void* getInitialState() { return SubEngine.getInitialState(); } virtual void ProcessEndPath(GREndPathNodeBuilderImpl& BuilderImpl) { GREndPathNodeBuilder<StateTy> Builder(BuilderImpl); SubEngine.ProcessEndPath(Builder); } virtual void ProcessStmt(Stmt* S, GRStmtNodeBuilderImpl& BuilderImpl) { GRStmtNodeBuilder<StateTy> Builder(BuilderImpl,SubEngine.getStateManager()); SubEngine.ProcessStmt(S, Builder); } virtual bool ProcessBlockEntrance(CFGBlock* Blk, const void* State, GRBlockCounter BC) { return SubEngine.ProcessBlockEntrance(Blk, static_cast<const StateTy*>(State), BC); } virtual void ProcessBranch(Stmt* Condition, Stmt* Terminator, GRBranchNodeBuilderImpl& BuilderImpl) { GRBranchNodeBuilder<StateTy> Builder(BuilderImpl); SubEngine.ProcessBranch(Condition, Terminator, Builder); } virtual void ProcessIndirectGoto(GRIndirectGotoNodeBuilderImpl& BuilderImpl) { GRIndirectGotoNodeBuilder<StateTy> Builder(BuilderImpl); SubEngine.ProcessIndirectGoto(Builder); } virtual void ProcessSwitch(GRSwitchNodeBuilderImpl& BuilderImpl) { GRSwitchNodeBuilder<StateTy> Builder(BuilderImpl); SubEngine.ProcessSwitch(Builder); } public: /// Construct a GRCoreEngine object to analyze the provided CFG using /// a DFS exploration of the exploded graph. GRCoreEngine(CFG& cfg, Decl& cd, ASTContext& ctx, SubEngineTy& subengine) : GRCoreEngineImpl(new GraphTy(cfg, cd, ctx), GRWorkList::MakeBFSBlockDFSContents()), SubEngine(subengine) {} /// Construct a GRCoreEngine object to analyze the provided CFG and to /// use the provided worklist object to execute the worklist algorithm. /// The GRCoreEngine object assumes ownership of 'wlist'. GRCoreEngine(CFG& cfg, Decl& cd, ASTContext& ctx, GRWorkList* wlist, SubEngineTy& subengine) : GRCoreEngineImpl(new GraphTy(cfg, cd, ctx), wlist), SubEngine(subengine) {} virtual ~GRCoreEngine() {} /// getGraph - Returns the exploded graph. GraphTy& getGraph() { return *static_cast<GraphTy*>(G.get()); } /// takeGraph - Returns the exploded graph. Ownership of the graph is /// transfered to the caller. GraphTy* takeGraph() { return static_cast<GraphTy*>(G.take()); } }; } // end clang namespace #endif <file_sep>/test/Lexer/cxx0x_keyword_as_cxx98.cpp // RUN: clang-cc %s -fsyntax-only int static_assert; <file_sep>/test/SemaCXX/warn-for-var-in-else.cpp // RUN: clang-cc -fsyntax-only -verify %s // rdar://6425550 int bar(); void do_something(int); int foo() { if (int X = bar()) { return X; } else { do_something(X); // expected-warning{{'X' is always zero in this context}} } } bool foo2() { if (bool B = bar()) { if (int Y = bar()) { return B; } else { do_something(Y); // expected-warning{{'Y' is always zero in this context}} return B; } } else { if (bool B2 = B) { // expected-warning{{'B' is always false in this context}} do_something(B); // expected-warning{{'B' is always false in this context}} } else if (B2) { // expected-warning{{'B2' is always false in this context}} do_something(B); // expected-warning{{'B' is always false in this context}} } return B; // expected-warning{{'B' is always false in this context}} } } <file_sep>/lib/Analysis/SimpleConstraintManager.h //== SimpleConstraintManager.h ----------------------------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Code shared between BasicConstraintManager and RangeConstraintManager. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_SIMPLE_CONSTRAINT_MANAGER_H #define LLVM_CLANG_ANALYSIS_SIMPLE_CONSTRAINT_MANAGER_H #include "clang/Analysis/PathSensitive/ConstraintManager.h" #include "clang/Analysis/PathSensitive/GRState.h" namespace clang { class SimpleConstraintManager : public ConstraintManager { protected: GRStateManager& StateMgr; public: SimpleConstraintManager(GRStateManager& statemgr) : StateMgr(statemgr) {} virtual ~SimpleConstraintManager(); bool canReasonAbout(SVal X) const; virtual const GRState* Assume(const GRState* St, SVal Cond, bool Assumption, bool& isFeasible); const GRState* Assume(const GRState* St, Loc Cond, bool Assumption, bool& isFeasible); const GRState* AssumeAux(const GRState* St, Loc Cond,bool Assumption, bool& isFeasible); const GRState* Assume(const GRState* St, NonLoc Cond, bool Assumption, bool& isFeasible); const GRState* AssumeAux(const GRState* St, NonLoc Cond, bool Assumption, bool& isFeasible); const GRState* AssumeSymInt(const GRState* St, bool Assumption, const SymIntExpr *SE, bool& isFeasible); virtual const GRState* AssumeSymNE(const GRState* St, SymbolRef sym, const llvm::APSInt& V, bool& isFeasible) = 0; virtual const GRState* AssumeSymEQ(const GRState* St, SymbolRef sym, const llvm::APSInt& V, bool& isFeasible) = 0; virtual const GRState* AssumeSymLT(const GRState* St, SymbolRef sym, const llvm::APSInt& V, bool& isFeasible) = 0; virtual const GRState* AssumeSymGT(const GRState* St, SymbolRef sym, const llvm::APSInt& V, bool& isFeasible) = 0; virtual const GRState* AssumeSymLE(const GRState* St, SymbolRef sym, const llvm::APSInt& V, bool& isFeasible) = 0; virtual const GRState* AssumeSymGE(const GRState* St, SymbolRef sym, const llvm::APSInt& V, bool& isFeasible) = 0; const GRState* AssumeInBound(const GRState* St, SVal Idx, SVal UpperBound, bool Assumption, bool& isFeasible); private: BasicValueFactory& getBasicVals() { return StateMgr.getBasicVals(); } SymbolManager& getSymbolManager() const { return StateMgr.getSymbolManager(); } }; } // end clang namespace #endif <file_sep>/lib/Analysis/GRTransferFuncs.cpp //== GRTransferFuncs.cpp - Path-Sens. Transfer Functions Interface -*- C++ -*--= // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines GRTransferFuncs, which provides a base-class that // defines an interface for transfer functions used by GRExprEngine. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/GRTransferFuncs.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" using namespace clang; void GRTransferFuncs::EvalBinOpNN(GRStateSet& OStates, GRExprEngine& Eng, const GRState *St, Expr* Ex, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, QualType T) { OStates.Add(Eng.getStateManager().BindExpr(St, Ex, DetermEvalBinOpNN(Eng, Op, L, R, T))); } <file_sep>/test/CodeGen/function-attributes.c // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm -o %t %s && // RUN: grep 'define signext i8 @f0(i32 %x) nounwind' %t && // RUN: grep 'define zeroext i8 @f1(i32 %x) nounwind' %t && // RUN: grep 'define void @f2(i8 signext %x) nounwind' %t && // RUN: grep 'define void @f3(i8 zeroext %x) nounwind' %t && // RUN: grep 'define signext i16 @f4(i32 %x) nounwind' %t && // RUN: grep 'define zeroext i16 @f5(i32 %x) nounwind' %t && // RUN: grep 'define void @f6(i16 signext %x) nounwind' %t && // RUN: grep 'define void @f7(i16 zeroext %x) nounwind' %t && signed char f0(int x) { return x; } unsigned char f1(int x) { return x; } void f2(signed char x) { } void f3(unsigned char x) { } signed short f4(int x) { return x; } unsigned short f5(int x) { return x; } void f6(signed short x) { } void f7(unsigned short x) { } // F8 is dead so it should not be emitted. // RUN: not grep '@f8' %t && void __attribute__((always_inline)) f8(void) { } // RUN: grep 'call void @f9_t() noreturn' %t && void __attribute__((noreturn)) f9_t(void); void f9(void) { f9_t(); } // FIXME: We should be setting nounwind on calls. // RUN: grep 'call i32 @f10_t() readnone' %t && int __attribute__((const)) f10_t(void); int f10(void) { return f10_t(); } int f11(void) { exit: return f10_t(); } int f12(int arg) { return arg ? 0 : f10_t(); } // RUN: grep 'define void @f13() nounwind readnone' %t && void f13(void) __attribute__((pure)) __attribute__((const)); void f13(void){} // RUN: true <file_sep>/include/clang/Parse/Action.h //===--- Action.h - Parser Action Interface ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Action and EmptyAction interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_ACTION_H #define LLVM_CLANG_PARSE_ACTION_H #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Parse/AccessSpecifier.h" #include "clang/Parse/DeclSpec.h" #include "clang/Parse/Ownership.h" #include "llvm/Support/PrettyStackTrace.h" namespace clang { // Semantic. class DeclSpec; class ObjCDeclSpec; class CXXScopeSpec; class Declarator; class AttributeList; struct FieldDeclarator; // Parse. class Scope; class Action; class Selector; class Designation; class InitListDesignations; // Lex. class Preprocessor; class Token; // We can re-use the low bit of expression, statement, base, and // member-initializer pointers for the "invalid" flag of // ActionResult. template<> struct IsResultPtrLowBitFree<0> { static const bool value = true;}; template<> struct IsResultPtrLowBitFree<1> { static const bool value = true;}; template<> struct IsResultPtrLowBitFree<3> { static const bool value = true;}; template<> struct IsResultPtrLowBitFree<4> { static const bool value = true;}; template<> struct IsResultPtrLowBitFree<5> { static const bool value = true;}; /// Action - As the parser reads the input file and recognizes the productions /// of the grammar, it invokes methods on this class to turn the parsed input /// into something useful: e.g. a parse tree. /// /// The callback methods that this class provides are phrased as actions that /// the parser has just done or is about to do when the method is called. They /// are not requests that the actions module do the specified action. /// /// All of the methods here are optional except getTypeName() and /// isCurrentClassName(), which must be specified in order for the /// parse to complete accurately. The MinimalAction class does this /// bare-minimum of tracking to implement this functionality. class Action : public ActionBase { public: /// Out-of-line virtual destructor to provide home for this class. virtual ~Action(); // Types - Though these don't actually enforce strong typing, they document // what types are required to be identical for the actions. typedef ActionBase::ExprTy ExprTy; typedef ActionBase::StmtTy StmtTy; /// Expr/Stmt/Type/BaseResult - Provide a unique type to wrap /// ExprTy/StmtTy/TypeTy/BaseTy, providing strong typing and /// allowing for failure. typedef ActionResult<0> ExprResult; typedef ActionResult<1> StmtResult; typedef ActionResult<2> TypeResult; typedef ActionResult<3> BaseResult; typedef ActionResult<4> MemInitResult; typedef ActionResult<5, DeclPtrTy> DeclResult; /// Same, but with ownership. typedef ASTOwningResult<&ActionBase::DeleteExpr> OwningExprResult; typedef ASTOwningResult<&ActionBase::DeleteStmt> OwningStmtResult; // Note that these will replace ExprResult and StmtResult when the transition // is complete. /// Single expressions or statements as arguments. #if !defined(DISABLE_SMART_POINTERS) typedef ASTOwningResult<&ActionBase::DeleteExpr> ExprArg; typedef ASTOwningResult<&ActionBase::DeleteStmt> StmtArg; #else typedef ASTOwningPtr<&ActionBase::DeleteExpr> ExprArg; typedef ASTOwningPtr<&ActionBase::DeleteStmt> StmtArg; #endif /// Multiple expressions or statements as arguments. typedef ASTMultiPtr<&ActionBase::DeleteExpr> MultiExprArg; typedef ASTMultiPtr<&ActionBase::DeleteStmt> MultiStmtArg; typedef ASTMultiPtr<&ActionBase::DeleteTemplateParams> MultiTemplateParamsArg; // Utilities for Action implementations to return smart results. OwningExprResult ExprError() { return OwningExprResult(*this, true); } OwningStmtResult StmtError() { return OwningStmtResult(*this, true); } OwningExprResult ExprError(const DiagnosticBuilder&) { return ExprError(); } OwningStmtResult StmtError(const DiagnosticBuilder&) { return StmtError(); } OwningExprResult ExprEmpty() { return OwningExprResult(*this, false); } OwningStmtResult StmtEmpty() { return OwningStmtResult(*this, false); } /// Statistics. virtual void PrintStats() const {} /// getDeclName - Return a pretty name for the specified decl if possible, or /// an empty string if not. This is used for pretty crash reporting. virtual std::string getDeclName(DeclPtrTy D) { return ""; } //===--------------------------------------------------------------------===// // Declaration Tracking Callbacks. //===--------------------------------------------------------------------===// /// ConvertDeclToDeclGroup - If the parser has one decl in a context where it /// needs a decl group, it calls this to convert between the two /// representations. virtual DeclGroupPtrTy ConvertDeclToDeclGroup(DeclPtrTy Ptr) { return DeclGroupPtrTy(); } /// getTypeName - Return non-null if the specified identifier is a type name /// in the current scope. /// An optional CXXScopeSpec can be passed to indicate the C++ scope (class or /// namespace) that the identifier must be a member of. /// i.e. for "foo::bar", 'II' will be "bar" and 'SS' will be "foo::". virtual TypeTy *getTypeName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, const CXXScopeSpec *SS = 0) = 0; /// isTagName() - This method is called *for error recovery purposes only* /// to determine if the specified name is a valid tag name ("struct foo"). If /// so, this returns the TST for the tag corresponding to it (TST_enum, /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C /// where the user forgot to specify the tag. virtual DeclSpec::TST isTagName(IdentifierInfo &II, Scope *S) { return DeclSpec::TST_unspecified; } /// isCurrentClassName - Return true if the specified name is the /// name of the innermost C++ class type currently being defined. virtual bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = 0) = 0; /// \brief Determines whether the identifier II is a template name /// in the current scope. If so, the kind of template name is /// returned, and \p TemplateDecl receives the declaration. An /// optional CXXScope can be passed to indicate the C++ scope in /// which the identifier will be found. virtual TemplateNameKind isTemplateName(const IdentifierInfo &II, Scope *S, TemplateTy &Template, const CXXScopeSpec *SS = 0) = 0; /// ActOnCXXGlobalScopeSpecifier - Return the object that represents the /// global scope ('::'). virtual CXXScopeTy *ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc) { return 0; } /// ActOnCXXNestedNameSpecifier - Called during parsing of a /// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now /// we want to resolve "bar::". 'SS' is empty or the previously parsed /// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar', /// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'. /// Returns a CXXScopeTy* object representing the C++ scope. virtual CXXScopeTy *ActOnCXXNestedNameSpecifier(Scope *S, const CXXScopeSpec &SS, SourceLocation IdLoc, SourceLocation CCLoc, IdentifierInfo &II) { return 0; } /// ActOnCXXNestedNameSpecifier - Called during parsing of a /// nested-name-specifier that involves a template-id, e.g., /// "foo::bar<int, float>::", and now we need to build a scope /// specifier. \p SS is empty or the previously parsed nested-name /// part ("foo::"), \p Type is the already-parsed class template /// specialization (or other template-id that names a type), \p /// TypeRange is the source range where the type is located, and \p /// CCLoc is the location of the trailing '::'. virtual CXXScopeTy *ActOnCXXNestedNameSpecifier(Scope *S, const CXXScopeSpec &SS, TypeTy *Type, SourceRange TypeRange, SourceLocation CCLoc) { return 0; } /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. virtual void ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) { } /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. virtual void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) { } /// ActOnDeclarator - This callback is invoked when a declarator is parsed and /// 'Init' specifies the initializer if any. This is for things like: /// "int X = 4" or "typedef int foo". /// virtual DeclPtrTy ActOnDeclarator(Scope *S, Declarator &D) { return DeclPtrTy(); } /// ActOnParamDeclarator - This callback is invoked when a parameter /// declarator is parsed. This callback only occurs for functions /// with prototypes. S is the function prototype scope for the /// parameters (C++ [basic.scope.proto]). virtual DeclPtrTy ActOnParamDeclarator(Scope *S, Declarator &D) { return DeclPtrTy(); } /// AddInitializerToDecl - This action is called immediately after /// ActOnDeclarator (when an initializer is present). The code is factored /// this way to make sure we are able to handle the following: /// void func() { int xx = xx; } /// This allows ActOnDeclarator to register "xx" prior to parsing the /// initializer. The declaration above should still result in a warning, /// since the reference to "xx" is uninitialized. virtual void AddInitializerToDecl(DeclPtrTy Dcl, ExprArg Init) { return; } /// SetDeclDeleted - This action is called immediately after ActOnDeclarator /// if =delete is parsed. C++0x [dcl.fct.def]p10 /// Note that this can be called even for variable declarations. It's the /// action's job to reject it. virtual void SetDeclDeleted(DeclPtrTy Dcl, SourceLocation DelLoc) { return; } /// ActOnUninitializedDecl - This action is called immediately after /// ActOnDeclarator (when an initializer is *not* present). virtual void ActOnUninitializedDecl(DeclPtrTy Dcl) { return; } /// FinalizeDeclaratorGroup - After a sequence of declarators are parsed, this /// gives the actions implementation a chance to process the group as a whole. virtual DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, DeclPtrTy *Group, unsigned NumDecls) { return DeclGroupPtrTy(); } /// @brief Indicates that all K&R-style parameter declarations have /// been parsed prior to a function definition. /// @param S The function prototype scope. /// @param D The function declarator. virtual void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls) { } /// ActOnStartOfFunctionDef - This is called at the start of a function /// definition, instead of calling ActOnDeclarator. The Declarator includes /// information about formal arguments that are part of this function. virtual DeclPtrTy ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { // Default to ActOnDeclarator. return ActOnStartOfFunctionDef(FnBodyScope, ActOnDeclarator(FnBodyScope, D)); } /// ActOnStartOfFunctionDef - This is called at the start of a function /// definition, after the FunctionDecl has already been created. virtual DeclPtrTy ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) { return D; } virtual void ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) { return; } /// ActOnFinishFunctionBody - This is called when a function body has /// completed parsing. Decl is returned by ParseStartOfFunctionDef. virtual DeclPtrTy ActOnFinishFunctionBody(DeclPtrTy Decl, StmtArg Body) { return Decl; } virtual DeclPtrTy ActOnFileScopeAsmDecl(SourceLocation Loc, ExprArg AsmString) { return DeclPtrTy(); } /// ActOnPopScope - This callback is called immediately before the specified /// scope is popped and deleted. virtual void ActOnPopScope(SourceLocation Loc, Scope *S) {} /// ActOnTranslationUnitScope - This callback is called once, immediately /// after creating the translation unit scope (in Parser::Initialize). virtual void ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {} /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with /// no declarator (e.g. "struct foo;") is parsed. virtual DeclPtrTy ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { return DeclPtrTy(); } /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ /// linkage specification, including the language and (if present) /// the '{'. ExternLoc is the location of the 'extern', LangLoc is /// the location of the language string literal, which is provided /// by Lang/StrSize. LBraceLoc, if valid, provides the location of /// the '{' brace. Otherwise, this linkage specification does not /// have any braces. virtual DeclPtrTy ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, SourceLocation LangLoc, const char *Lang, unsigned StrSize, SourceLocation LBraceLoc) { return DeclPtrTy(); } /// ActOnFinishLinkageSpecification - Completely the definition of /// the C++ linkage specification LinkageSpec. If RBraceLoc is /// valid, it's the position of the closing '}' brace in a linkage /// specification that uses braces. virtual DeclPtrTy ActOnFinishLinkageSpecification(Scope *S, DeclPtrTy LinkageSpec, SourceLocation RBraceLoc) { return LinkageSpec; } /// ActOnEndOfTranslationUnit - This is called at the very end of the /// translation unit when EOF is reached and all but the top-level scope is /// popped. virtual void ActOnEndOfTranslationUnit() {} //===--------------------------------------------------------------------===// // Type Parsing Callbacks. //===--------------------------------------------------------------------===// /// ActOnTypeName - A type-name (type-id in C++) was parsed. virtual TypeResult ActOnTypeName(Scope *S, Declarator &D) { return TypeResult(); } enum TagKind { TK_Reference, // Reference to a tag: 'struct foo *X;' TK_Declaration, // Fwd decl of a tag: 'struct foo;' TK_Definition // Definition of a tag: 'struct foo { int X; } Y;' }; virtual DeclPtrTy ActOnTag(Scope *S, unsigned TagSpec, TagKind TK, SourceLocation KWLoc, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, AccessSpecifier AS) { // TagType is an instance of DeclSpec::TST, indicating what kind of tag this // is (struct/union/enum/class). return DeclPtrTy(); } /// Act on @defs() element found when parsing a structure. ClassName is the /// name of the referenced class. virtual void ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, llvm::SmallVectorImpl<DeclPtrTy> &Decls) {} virtual DeclPtrTy ActOnField(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart, Declarator &D, ExprTy *BitfieldWidth) { return DeclPtrTy(); } virtual DeclPtrTy ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, ExprTy *BitfieldWidth, tok::ObjCKeywordKind visibility) { return DeclPtrTy(); } virtual void ActOnFields(Scope* S, SourceLocation RecLoc, DeclPtrTy TagDecl, DeclPtrTy *Fields, unsigned NumFields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList) {} /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). virtual void ActOnTagStartDefinition(Scope *S, DeclPtrTy TagDecl) { } /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). virtual void ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagDecl) { } virtual DeclPtrTy ActOnEnumConstant(Scope *S, DeclPtrTy EnumDecl, DeclPtrTy LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, SourceLocation EqualLoc, ExprTy *Val) { return DeclPtrTy(); } virtual void ActOnEnumBody(SourceLocation EnumLoc, DeclPtrTy EnumDecl, DeclPtrTy *Elements, unsigned NumElements) {} //===--------------------------------------------------------------------===// // Statement Parsing Callbacks. //===--------------------------------------------------------------------===// virtual OwningStmtResult ActOnNullStmt(SourceLocation SemiLoc) { return StmtEmpty(); } virtual OwningStmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, MultiStmtArg Elts, bool isStmtExpr) { return StmtEmpty(); } virtual OwningStmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc) { return StmtEmpty(); } virtual OwningStmtResult ActOnExprStmt(ExprArg Expr) { return OwningStmtResult(*this, Expr.release()); } /// ActOnCaseStmt - Note that this handles the GNU 'case 1 ... 4' extension, /// which can specify an RHS value. The sub-statement of the case is /// specified in a separate action. virtual OwningStmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprArg LHSVal, SourceLocation DotDotDotLoc, ExprArg RHSVal, SourceLocation ColonLoc) { return StmtEmpty(); } /// ActOnCaseStmtBody - This installs a statement as the body of a case. virtual void ActOnCaseStmtBody(StmtTy *CaseStmt, StmtArg SubStmt) {} virtual OwningStmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, StmtArg SubStmt, Scope *CurScope){ return StmtEmpty(); } virtual OwningStmtResult ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation ColonLoc, StmtArg SubStmt) { return StmtEmpty(); } virtual OwningStmtResult ActOnIfStmt(SourceLocation IfLoc, ExprArg CondVal, StmtArg ThenVal, SourceLocation ElseLoc, StmtArg ElseVal) { return StmtEmpty(); } virtual OwningStmtResult ActOnStartOfSwitchStmt(ExprArg Cond) { return StmtEmpty(); } virtual OwningStmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch, StmtArg Body) { return StmtEmpty(); } virtual OwningStmtResult ActOnWhileStmt(SourceLocation WhileLoc, ExprArg Cond, StmtArg Body) { return StmtEmpty(); } virtual OwningStmtResult ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, SourceLocation WhileLoc, ExprArg Cond) { return StmtEmpty(); } virtual OwningStmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, StmtArg First, ExprArg Second, ExprArg Third, SourceLocation RParenLoc, StmtArg Body) { return StmtEmpty(); } virtual OwningStmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, SourceLocation LParenLoc, StmtArg First, ExprArg Second, SourceLocation RParenLoc, StmtArg Body) { return StmtEmpty(); } virtual OwningStmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, IdentifierInfo *LabelII) { return StmtEmpty(); } virtual OwningStmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, ExprArg DestExp) { return StmtEmpty(); } virtual OwningStmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { return StmtEmpty(); } virtual OwningStmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope) { return StmtEmpty(); } virtual OwningStmtResult ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg RetValExp) { return StmtEmpty(); } virtual OwningStmtResult ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, std::string *Names, MultiExprArg Constraints, MultiExprArg Exprs, ExprArg AsmString, MultiExprArg Clobbers, SourceLocation RParenLoc) { return StmtEmpty(); } // Objective-c statements virtual OwningStmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, DeclPtrTy Parm, StmtArg Body, StmtArg CatchList) { return StmtEmpty(); } virtual OwningStmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) { return StmtEmpty(); } virtual OwningStmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, StmtArg Try, StmtArg Catch, StmtArg Finally) { return StmtEmpty(); } virtual OwningStmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw, Scope *CurScope) { return StmtEmpty(); } virtual OwningStmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr, StmtArg SynchBody) { return StmtEmpty(); } // C++ Statements virtual DeclPtrTy ActOnExceptionDeclarator(Scope *S, Declarator &D) { return DeclPtrTy(); } virtual OwningStmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExceptionDecl, StmtArg HandlerBlock) { return StmtEmpty(); } virtual OwningStmtResult ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock, MultiStmtArg Handlers) { return StmtEmpty(); } //===--------------------------------------------------------------------===// // Expression Parsing Callbacks. //===--------------------------------------------------------------------===// // Primary Expressions. /// \brief Retrieve the source range that corresponds to the given /// expression. virtual SourceRange getExprRange(ExprTy *E) const { return SourceRange(); } /// ActOnIdentifierExpr - Parse an identifier in expression context. /// 'HasTrailingLParen' indicates whether or not the identifier has a '(' /// token immediately after it. /// An optional CXXScopeSpec can be passed to indicate the C++ scope (class or /// namespace) that the identifier must be a member of. /// i.e. for "foo::bar", 'II' will be "bar" and 'SS' will be "foo::". virtual OwningExprResult ActOnIdentifierExpr(Scope *S, SourceLocation Loc, IdentifierInfo &II, bool HasTrailingLParen, const CXXScopeSpec *SS = 0, bool isAddressOfOperand = false){ return ExprEmpty(); } /// ActOnOperatorFunctionIdExpr - Parse a C++ overloaded operator /// name (e.g., @c operator+ ) as an expression. This is very /// similar to ActOnIdentifierExpr, except that instead of providing /// an identifier the parser provides the kind of overloaded /// operator that was parsed. virtual OwningExprResult ActOnCXXOperatorFunctionIdExpr( Scope *S, SourceLocation OperatorLoc, OverloadedOperatorKind Op, bool HasTrailingLParen, const CXXScopeSpec &SS, bool isAddressOfOperand = false) { return ExprEmpty(); } /// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function /// name (e.g., @c operator void const *) as an expression. This is /// very similar to ActOnIdentifierExpr, except that instead of /// providing an identifier the parser provides the type of the /// conversion function. virtual OwningExprResult ActOnCXXConversionFunctionExpr( Scope *S, SourceLocation OperatorLoc, TypeTy *Type, bool HasTrailingLParen, const CXXScopeSpec &SS, bool isAddressOfOperand = false) { return ExprEmpty(); } virtual OwningExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { return ExprEmpty(); } virtual OwningExprResult ActOnCharacterConstant(const Token &) { return ExprEmpty(); } virtual OwningExprResult ActOnNumericConstant(const Token &) { return ExprEmpty(); } /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). virtual OwningExprResult ActOnStringLiteral(const Token *Toks, unsigned NumToks) { return ExprEmpty(); } virtual OwningExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, ExprArg Val) { return move(Val); // Default impl returns operand. } // Postfix Expressions. virtual OwningExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, ExprArg Input) { return ExprEmpty(); } virtual OwningExprResult ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, ExprArg Idx, SourceLocation RLoc) { return ExprEmpty(); } virtual OwningExprResult ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation MemberLoc, IdentifierInfo &Member, DeclPtrTy ObjCImpDecl) { return ExprEmpty(); } /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. There are guaranteed to be one fewer commas than arguments, /// unless there are zero arguments. virtual OwningExprResult ActOnCallExpr(Scope *S, ExprArg Fn, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation *CommaLocs, SourceLocation RParenLoc) { return ExprEmpty(); } // Unary Operators. 'Tok' is the token for the operator. virtual OwningExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, ExprArg Input) { return ExprEmpty(); } virtual OwningExprResult ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, void *TyOrEx, const SourceRange &ArgRange) { return ExprEmpty(); } virtual OwningExprResult ActOnCompoundLiteral(SourceLocation LParen, TypeTy *Ty, SourceLocation RParen, ExprArg Op) { return ExprEmpty(); } virtual OwningExprResult ActOnInitList(SourceLocation LParenLoc, MultiExprArg InitList, SourceLocation RParenLoc) { return ExprEmpty(); } /// @brief Parsed a C99 designated initializer. /// /// @param Desig Contains the designation with one or more designators. /// /// @param Loc The location of the '=' or ':' prior to the /// initialization expression. /// /// @param GNUSyntax If true, then this designated initializer used /// the deprecated GNU syntax @c fieldname:foo or @c [expr]foo rather /// than the C99 syntax @c .fieldname=foo or @c [expr]=foo. /// /// @param Init The value that the entity (or entities) described by /// the designation will be initialized with. virtual OwningExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation Loc, bool GNUSyntax, OwningExprResult Init) { return ExprEmpty(); } virtual OwningExprResult ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, SourceLocation RParenLoc, ExprArg Op) { return ExprEmpty(); } virtual OwningExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, ExprArg LHS, ExprArg RHS) { return ExprEmpty(); } /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. virtual OwningExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, ExprArg Cond, ExprArg LHS, ExprArg RHS) { return ExprEmpty(); } //===---------------------- GNU Extension Expressions -------------------===// virtual OwningExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, IdentifierInfo *LabelII) { // "&&foo" return ExprEmpty(); } virtual OwningExprResult ActOnStmtExpr(SourceLocation LPLoc, StmtArg SubStmt, SourceLocation RPLoc) { // "({..})" return ExprEmpty(); } // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; ExprTy *E; } U; }; virtual OwningExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, TypeTy *Arg1, OffsetOfComponent *CompPtr, unsigned NumComponents, SourceLocation RParenLoc) { return ExprEmpty(); } // __builtin_types_compatible_p(type1, type2) virtual OwningExprResult ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, TypeTy *arg1, TypeTy *arg2, SourceLocation RPLoc) { return ExprEmpty(); } // __builtin_choose_expr(constExpr, expr1, expr2) virtual OwningExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, ExprArg cond, ExprArg expr1, ExprArg expr2, SourceLocation RPLoc){ return ExprEmpty(); } // __builtin_va_arg(expr, type) virtual OwningExprResult ActOnVAArg(SourceLocation BuiltinLoc, ExprArg expr, TypeTy *type, SourceLocation RPLoc) { return ExprEmpty(); } /// ActOnGNUNullExpr - Parsed the GNU __null expression, the token /// for which is at position TokenLoc. virtual OwningExprResult ActOnGNUNullExpr(SourceLocation TokenLoc) { return ExprEmpty(); } //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. The result pointer is passed into the block finalizers. virtual void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {} /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. virtual void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {} /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. virtual void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {} /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} virtual OwningExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtArg Body, Scope *CurScope) { return ExprEmpty(); } //===------------------------- C++ Declarations -------------------------===// /// ActOnStartNamespaceDef - This is called at the start of a namespace /// definition. virtual DeclPtrTy ActOnStartNamespaceDef(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace) { return DeclPtrTy(); } /// ActOnFinishNamespaceDef - This callback is called after a namespace is /// exited. Decl is returned by ActOnStartNamespaceDef. virtual void ActOnFinishNamespaceDef(DeclPtrTy Dcl, SourceLocation RBrace) { return; } /// ActOnUsingDirective - This is called when using-directive is parsed. virtual DeclPtrTy ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, const CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, AttributeList *AttrList); /// ActOnNamespaceAliasDef - This is called when a namespace alias definition /// is parsed. virtual DeclPtrTy ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, const CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident) { return DeclPtrTy(); } /// ActOnParamDefaultArgument - Parse default argument for function parameter virtual void ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, ExprArg defarg) { } /// ActOnParamUnparsedDefaultArgument - We've seen a default /// argument for a function parameter, but we can't parse it yet /// because we're inside a class definition. Note that this default /// argument will be parsed later. virtual void ActOnParamUnparsedDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc) { } /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of /// the default argument for the parameter param failed. virtual void ActOnParamDefaultArgumentError(DeclPtrTy param) { } /// AddCXXDirectInitializerToDecl - This action is called immediately after /// ActOnDeclarator, when a C++ direct initializer is present. /// e.g: "int x(1);" virtual void AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { return; } /// ActOnStartDelayedCXXMethodDeclaration - We have completed /// parsing a top-level (non-nested) C++ class, and we are now /// parsing those parts of the given Method declaration that could /// not be parsed earlier (C++ [class.mem]p2), such as default /// arguments. This action should enter the scope of the given /// Method declaration as if we had just parsed the qualified method /// name. However, it should not bring the parameters into scope; /// that will be performed by ActOnDelayedCXXMethodParameter. virtual void ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy Method) { } /// ActOnDelayedCXXMethodParameter - We've already started a delayed /// C++ method declaration. We're (re-)introducing the given /// function parameter into scope for use in parsing later parts of /// the method declaration. For example, we could see an /// ActOnParamDefaultArgument event for this parameter. virtual void ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy Param) { } /// ActOnFinishDelayedCXXMethodDeclaration - We have finished /// processing the delayed method declaration for Method. The method /// declaration is now considered finished. There may be a separate /// ActOnStartOfFunctionDef action later (not necessarily /// immediately!) for this method, if it was also defined inside the /// class body. virtual void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy Method) { } /// ActOnStaticAssertDeclaration - Parse a C++0x static_assert declaration. virtual DeclPtrTy ActOnStaticAssertDeclaration(SourceLocation AssertLoc, ExprArg AssertExpr, ExprArg AssertMessageExpr) { return DeclPtrTy(); } //===------------------------- C++ Expressions --------------------------===// /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. virtual OwningExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, TypeTy *Ty, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, ExprArg Op, SourceLocation RParenLoc) { return ExprEmpty(); } /// ActOnCXXTypeidOfType - Parse typeid( type-id ). virtual OwningExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc) { return ExprEmpty(); } /// ActOnCXXThis - Parse the C++ 'this' pointer. virtual OwningExprResult ActOnCXXThis(SourceLocation ThisLoc) { return ExprEmpty(); } /// ActOnCXXBoolLiteral - Parse {true,false} literals. virtual OwningExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { return ExprEmpty(); } /// ActOnCXXThrow - Parse throw expressions. virtual OwningExprResult ActOnCXXThrow(SourceLocation OpLoc, ExprArg Op) { return ExprEmpty(); } /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). virtual OwningExprResult ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { return ExprEmpty(); } /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a /// C++ if/switch/while/for statement. /// e.g: "if (int x = f()) {...}" virtual OwningExprResult ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, Declarator &D, SourceLocation EqualLoc, ExprArg AssignExprVal) { return ExprEmpty(); } /// ActOnCXXNew - Parsed a C++ 'new' expression. UseGlobal is true if the /// new was qualified (::new). In a full new like /// @code new (p1, p2) type(c1, c2) @endcode /// the p1 and p2 expressions will be in PlacementArgs and the c1 and c2 /// expressions in ConstructorArgs. The type is passed as a declarator. virtual OwningExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, bool ParenTypeId, Declarator &D, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { return ExprEmpty(); } /// ActOnCXXDelete - Parsed a C++ 'delete' expression. UseGlobal is true if /// the delete was qualified (::delete). ArrayForm is true if the array form /// was used (delete[]). virtual OwningExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, ExprArg Operand) { return ExprEmpty(); } virtual OwningExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, SourceLocation KWLoc, SourceLocation LParen, TypeTy *Ty, SourceLocation RParen) { return ExprEmpty(); } //===---------------------------- C++ Classes ---------------------------===// /// ActOnBaseSpecifier - Parsed a base specifier virtual BaseResult ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeTy *basetype, SourceLocation BaseLoc) { return BaseResult(); } virtual void ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, unsigned NumBases) { } /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member /// declarator is parsed. 'AS' is the access specifier, 'BitfieldWidth' /// specifies the bitfield width if there is one and 'Init' specifies the /// initializer if any. 'Deleted' is true if there's a =delete /// specifier on the function. virtual DeclPtrTy ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, ExprTy *BitfieldWidth, ExprTy *Init, bool Deleted = false) { return DeclPtrTy(); } virtual MemInitResult ActOnMemInitializer(DeclPtrTy ConstructorDecl, Scope *S, IdentifierInfo *MemberOrBase, SourceLocation IdLoc, SourceLocation LParenLoc, ExprTy **Args, unsigned NumArgs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { return true; } /// ActOnMemInitializers - This is invoked when all of the member /// initializers of a constructor have been parsed. ConstructorDecl /// is the function declaration (which will be a C++ constructor in /// a well-formed program), ColonLoc is the location of the ':' that /// starts the constructor initializer, and MemInit/NumMemInits /// contains the individual member (and base) initializers. virtual void ActOnMemInitializers(DeclPtrTy ConstructorDecl, SourceLocation ColonLoc, MemInitTy **MemInits, unsigned NumMemInits){ } /// ActOnFinishCXXMemberSpecification - Invoked after all member declarators /// are parsed but *before* parsing of inline method definitions. virtual void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, DeclPtrTy TagDecl, SourceLocation LBrac, SourceLocation RBrac) { } //===---------------------------C++ Templates----------------------------===// /// ActOnTypeParameter - Called when a C++ template type parameter /// (e.g., "typename T") has been parsed. Typename specifies whether /// the keyword "typename" was used to declare the type parameter /// (otherwise, "class" was used), and KeyLoc is the location of the /// "class" or "typename" keyword. ParamName is the name of the /// parameter (NULL indicates an unnamed template parameter) and /// ParamNameLoc is the location of the parameter name (if any). /// If the type parameter has a default argument, it will be added /// later via ActOnTypeParameterDefault. Depth and Position provide /// the number of enclosing templates (see /// ActOnTemplateParameterList) and the number of previous /// parameters within this template parameter list. virtual DeclPtrTy ActOnTypeParameter(Scope *S, bool Typename, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position) { return DeclPtrTy(); } /// ActOnTypeParameterDefault - Adds a default argument (the type /// Default) to the given template type parameter (TypeParam). virtual void ActOnTypeParameterDefault(DeclPtrTy TypeParam, SourceLocation EqualLoc, SourceLocation DefaultLoc, TypeTy *Default) { } /// ActOnNonTypeTemplateParameter - Called when a C++ non-type /// template parameter (e.g., "int Size" in "template<int Size> /// class Array") has been parsed. S is the current scope and D is /// the parsed declarator. Depth and Position provide the number of /// enclosing templates (see /// ActOnTemplateParameterList) and the number of previous /// parameters within this template parameter list. virtual DeclPtrTy ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position) { return DeclPtrTy(); } /// \brief Adds a default argument to the given non-type template /// parameter. virtual void ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParam, SourceLocation EqualLoc, ExprArg Default) { } /// ActOnTemplateTemplateParameter - Called when a C++ template template /// parameter (e.g., "int T" in "template<template <typename> class T> class /// Array") has been parsed. TmpLoc is the location of the "template" keyword, /// TemplateParams is the sequence of parameters required by the template, /// ParamName is the name of the parameter (null if unnamed), and ParamNameLoc /// is the source location of the identifier (if given). virtual DeclPtrTy ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParamsTy *Params, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position) { return DeclPtrTy(); } /// \brief Adds a default argument to the given template template /// parameter. virtual void ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParam, SourceLocation EqualLoc, ExprArg Default) { } /// ActOnTemplateParameterList - Called when a complete template /// parameter list has been parsed, e.g., /// /// @code /// export template<typename T, T Size> /// @endcode /// /// Depth is the number of enclosing template parameter lists. This /// value does not include templates from outer scopes. For example: /// /// @code /// template<typename T> // depth = 0 /// class A { /// template<typename U> // depth = 0 /// class B; /// }; /// /// template<typename T> // depth = 0 /// template<typename U> // depth = 1 /// class A<T>::B { ... }; /// @endcode /// /// ExportLoc, if valid, is the position of the "export" /// keyword. Otherwise, "export" was not specified. /// TemplateLoc is the position of the template keyword, LAngleLoc /// is the position of the left angle bracket, and RAngleLoc is the /// position of the corresponding right angle bracket. /// Params/NumParams provides the template parameters that were /// parsed as part of the template-parameter-list. virtual TemplateParamsTy * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, DeclPtrTy *Params, unsigned NumParams, SourceLocation RAngleLoc) { return 0; } /// \brief Process the declaration or definition of a class template /// with the given template parameter lists. virtual DeclResult ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK, SourceLocation KWLoc, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, MultiTemplateParamsArg TemplateParameterLists, AccessSpecifier AS) { return DeclResult(); } /// \brief Form a type from a template and a list of template /// arguments. /// /// This action merely forms the type for the template-id, possibly /// checking well-formedness of the template arguments. It does not /// imply the declaration of any entity. /// /// \param Template A template whose specialization results in a /// type, e.g., a class template or template template parameter. /// /// \param IsSpecialization true when we are naming the class /// template specialization as part of an explicit class /// specialization or class template partial specialization. virtual TypeResult ActOnTemplateIdType(TemplateTy Template, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation *TemplateArgLocs, SourceLocation RAngleLoc) { return TypeResult(); }; /// \brief Form a dependent template name. /// /// This action forms a dependent template name given the template /// name and its (presumably dependent) scope specifier. For /// example, given "MetaFun::template apply", the scope specifier \p /// SS will be "MetaFun::", \p TemplateKWLoc contains the location /// of the "template" keyword, and "apply" is the \p Name. virtual TemplateTy ActOnDependentTemplateName(SourceLocation TemplateKWLoc, const IdentifierInfo &Name, SourceLocation NameLoc, const CXXScopeSpec &SS) { return TemplateTy(); } /// \brief Process the declaration or definition of an explicit /// class template specialization or a class template partial /// specialization. /// /// This routine is invoked when an explicit class template /// specialization or a class template partial specialization is /// declared or defined, to introduce the (partial) specialization /// and produce a declaration for it. In the following example, /// ActOnClassTemplateSpecialization will be invoked for the /// declarations at both A and B: /// /// \code /// template<typename T> class X; /// template<> class X<int> { }; // A: explicit specialization /// template<typename T> class X<T*> { }; // B: partial specialization /// \endcode /// /// Note that it is the job of semantic analysis to determine which /// of the two cases actually occurred in the source code, since /// they are parsed through the same path. The formulation of the /// template parameter lists describes which case we are in. /// /// \param S the current scope /// /// \param TagSpec whether this declares a class, struct, or union /// (template) /// /// \param TK whether this is a declaration or a definition /// /// \param KWLoc the location of the 'class', 'struct', or 'union' /// keyword. /// /// \param SS the scope specifier preceding the template-id /// /// \param Template the declaration of the class template that we /// are specializing. /// /// \param Attr attributes on the specialization /// /// \param TemplateParameterLists the set of template parameter /// lists that apply to this declaration. In a well-formed program, /// the number of template parameter lists will be one more than the /// number of template-ids in the scope specifier. However, it is /// common for users to provide the wrong number of template /// parameter lists (such as a missing \c template<> prior to a /// specialization); the parser does not check this condition. virtual DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation *TemplateArgLocs, SourceLocation RAngleLoc, AttributeList *Attr, MultiTemplateParamsArg TemplateParameterLists) { return DeclResult(); } /// \brief Called when the parser has parsed a C++ typename /// specifier that ends in an identifier, e.g., "typename T::type". /// /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. virtual TypeResult ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc) { return TypeResult(); } /// \brief Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param Ty the type that the typename specifier refers to. virtual TypeResult ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TypeTy *Ty) { return TypeResult(); } //===----------------------- Obj-C Declarations -------------------------===// // ActOnStartClassInterface - this action is called immediately after parsing // the prologue for a class interface (before parsing the instance // variables). Instance variables are processed by ActOnFields(). virtual DeclPtrTy ActOnStartClassInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc, AttributeList *AttrList) { return DeclPtrTy(); } /// ActOnCompatiblityAlias - this action is called after complete parsing of /// @compaatibility_alias declaration. It sets up the alias relationships. virtual DeclPtrTy ActOnCompatiblityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation) { return DeclPtrTy(); } // ActOnStartProtocolInterface - this action is called immdiately after // parsing the prologue for a protocol interface. virtual DeclPtrTy ActOnStartProtocolInterface(SourceLocation AtProtoLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc, AttributeList *AttrList) { return DeclPtrTy(); } // ActOnStartCategoryInterface - this action is called immdiately after // parsing the prologue for a category interface. virtual DeclPtrTy ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc) { return DeclPtrTy(); } // ActOnStartClassImplementation - this action is called immdiately after // parsing the prologue for a class implementation. Instance variables are // processed by ActOnFields(). virtual DeclPtrTy ActOnStartClassImplementation( SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc) { return DeclPtrTy(); } // ActOnStartCategoryImplementation - this action is called immdiately after // parsing the prologue for a category implementation. virtual DeclPtrTy ActOnStartCategoryImplementation( SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc) { return DeclPtrTy(); } // ActOnPropertyImplDecl - called for every property implementation virtual DeclPtrTy ActOnPropertyImplDecl( SourceLocation AtLoc, // location of the @synthesize/@dynamic SourceLocation PropertyNameLoc, // location for the property name bool ImplKind, // true for @synthesize, false for // @dynamic DeclPtrTy ClassImplDecl, // class or category implementation IdentifierInfo *propertyId, // name of property IdentifierInfo *propertyIvar) { // name of the ivar return DeclPtrTy(); } struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. TypeTy *Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. AttributeList *ArgAttrs; }; // ActOnMethodDeclaration - called for all method declarations. virtual DeclPtrTy ActOnMethodDeclaration( SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, // tok::minus for instance, tok::plus for class. DeclPtrTy ClassDecl, // class this methods belongs to. ObjCDeclSpec &ReturnQT, // for return type's in inout etc. TypeTy *ReturnType, // the method return type. Selector Sel, // a unique name for the method. ObjCArgInfo *ArgInfo, // ArgInfo: Has 'Sel.getNumArgs()' entries. llvm::SmallVectorImpl<Declarator> &Cdecls, // c-style args AttributeList *MethodAttrList, // optional // tok::objc_not_keyword, tok::objc_optional, tok::objc_required tok::ObjCKeywordKind impKind, bool isVariadic = false) { return DeclPtrTy(); } // ActOnAtEnd - called to mark the @end. For declarations (interfaces, // protocols, categories), the parser passes all methods/properties. // For class implementations, these values default to 0. For implementations, // methods are processed incrementally (by ActOnMethodDeclaration above). virtual void ActOnAtEnd(SourceLocation AtEndLoc, DeclPtrTy classDecl, DeclPtrTy *allMethods = 0, unsigned allNum = 0, DeclPtrTy *allProperties = 0, unsigned pNum = 0, DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0) { } // ActOnProperty - called to build one property AST virtual DeclPtrTy ActOnProperty(Scope *S, SourceLocation AtLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, DeclPtrTy ClassCategory, bool *OverridingProperty, tok::ObjCKeywordKind MethodImplKind) { return DeclPtrTy(); } virtual OwningExprResult ActOnClassPropertyRefExpr( IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation &receiverNameLoc, SourceLocation &propertyNameLoc) { return ExprEmpty(); } // ActOnClassMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from NumArgs. virtual ExprResult ActOnClassMessage( Scope *S, IdentifierInfo *receivingClassName, Selector Sel, SourceLocation lbrac, SourceLocation receiverLoc, SourceLocation selectorLoc, SourceLocation rbrac, ExprTy **ArgExprs, unsigned NumArgs) { return ExprResult(); } // ActOnInstanceMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from NumArgs. virtual ExprResult ActOnInstanceMessage( ExprTy *receiver, Selector Sel, SourceLocation lbrac, SourceLocation selectorLoc, SourceLocation rbrac, ExprTy **ArgExprs, unsigned NumArgs) { return ExprResult(); } virtual DeclPtrTy ActOnForwardClassDeclaration( SourceLocation AtClassLoc, IdentifierInfo **IdentList, unsigned NumElts) { return DeclPtrTy(); } virtual DeclPtrTy ActOnForwardProtocolDeclaration( SourceLocation AtProtocolLoc, const IdentifierLocPair*IdentList, unsigned NumElts, AttributeList *AttrList) { return DeclPtrTy(); } /// FindProtocolDeclaration - This routine looks up protocols and /// issues error if they are not declared. It returns list of valid /// protocols found. virtual void FindProtocolDeclaration(bool WarnOnDeclarations, const IdentifierLocPair *ProtocolId, unsigned NumProtocols, llvm::SmallVectorImpl<DeclPtrTy> &ResProtos) { } //===----------------------- Obj-C Expressions --------------------------===// virtual ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ExprTy **Strings, unsigned NumStrings) { return ExprResult(); } virtual ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncLoc, SourceLocation LParenLoc, TypeTy *Ty, SourceLocation RParenLoc) { return ExprResult(); } virtual ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { return ExprResult(); } virtual ExprResult ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { return ExprResult(); } //===---------------------------- Pragmas -------------------------------===// enum PragmaPackKind { PPK_Default, // #pragma pack([n]) PPK_Show, // #pragma pack(show), only supported by MSVC. PPK_Push, // #pragma pack(push, [identifier], [n]) PPK_Pop // #pragma pack(pop, [identifier], [n]) }; /// ActOnPragmaPack - Called on well formed #pragma pack(...). virtual void ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, ExprTy *Alignment, SourceLocation PragmaLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { return; } /// ActOnPragmaPack - Called on well formed #pragma pack(...). virtual void ActOnPragmaUnused(ExprTy **Exprs, unsigned NumExprs, SourceLocation PragmaLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { return; } }; /// MinimalAction - Minimal actions are used by light-weight clients of the /// parser that do not need name resolution or significant semantic analysis to /// be performed. The actions implemented here are in the form of unresolved /// identifiers. By using a simpler interface than the SemanticAction class, /// the parser doesn't have to build complex data structures and thus runs more /// quickly. class MinimalAction : public Action { /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; IdentifierTable &Idents; Preprocessor &PP; void *TypeNameInfoTablePtr; public: MinimalAction(Preprocessor &pp); ~MinimalAction(); /// getTypeName - This looks at the IdentifierInfo::FETokenInfo field to /// determine whether the name is a typedef or not in this scope. virtual TypeTy *getTypeName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, const CXXScopeSpec *SS); /// isCurrentClassName - Always returns false, because MinimalAction /// does not support C++ classes with constructors. virtual bool isCurrentClassName(const IdentifierInfo& II, Scope *S, const CXXScopeSpec *SS); virtual TemplateNameKind isTemplateName(const IdentifierInfo &II, Scope *S, TemplateTy &Template, const CXXScopeSpec *SS = 0); /// ActOnDeclarator - If this is a typedef declarator, we modify the /// IdentifierInfo::FETokenInfo field to keep track of this fact, until S is /// popped. virtual DeclPtrTy ActOnDeclarator(Scope *S, Declarator &D); /// ActOnPopScope - When a scope is popped, if any typedefs are now /// out-of-scope, they are removed from the IdentifierInfo::FETokenInfo field. virtual void ActOnPopScope(SourceLocation Loc, Scope *S); virtual void ActOnTranslationUnitScope(SourceLocation Loc, Scope *S); virtual DeclPtrTy ActOnForwardClassDeclaration(SourceLocation AtClassLoc, IdentifierInfo **IdentList, unsigned NumElts); virtual DeclPtrTy ActOnStartClassInterface(SourceLocation interLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc, AttributeList *AttrList); }; /// PrettyStackTraceActionsDecl - If a crash occurs in the parser while parsing /// something related to a virtualized decl, include that virtualized decl in /// the stack trace. class PrettyStackTraceActionsDecl : public llvm::PrettyStackTraceEntry { Action::DeclPtrTy TheDecl; SourceLocation Loc; Action &Actions; SourceManager &SM; const char *Message; public: PrettyStackTraceActionsDecl(Action::DeclPtrTy Decl, SourceLocation L, Action &actions, SourceManager &sm, const char *Msg) : TheDecl(Decl), Loc(L), Actions(actions), SM(sm), Message(Msg) {} virtual void print(llvm::raw_ostream &OS) const; }; } // end namespace clang #endif <file_sep>/test/Preprocessor/output_paste_avoid.c // RUN: clang-cc -E %s | grep '+ + - - + + = = =' && // RUN: clang-cc -E %s | not grep -F '...' && // RUN: clang-cc -E %s | not grep -F 'L"str"' // This should print as ".. ." to avoid turning into ... #define y(a) ..a y(.) #define PLUS + #define EMPTY #define f(x) =x= +PLUS -EMPTY- PLUS+ f(=) // Should expand to L "str" not L"str" #define test(x) L#x test(str) <file_sep>/test/CodeGen/global-decls.c // RUN: clang-cc -arch i386 -emit-llvm -o %t %s && // RUN: grep '@g0_ext = extern_weak global i32' %t && extern int g0_ext __attribute__((weak)); // RUN: grep 'declare extern_weak i32 @g1_ext()' %t && extern int __attribute__((weak)) g1_ext (void); // RUN: grep '@g0_common = weak global i32' %t && int g0_common __attribute__((weak)); // RUN: grep '@g0_def = weak global i32' %t && int g0_def __attribute__((weak)) = 52; // RUN: grep 'define weak i32 @g1_def()' %t && int __attribute__((weak)) g1_def (void) {} // Force _ext references void f0() { int a = g0_ext; int b = g1_ext(); } // RUN: true <file_sep>/lib/CodeGen/CGDebugInfo.h //===--- CGDebugInfo.h - DebugInfo for LLVM CodeGen -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the source level debug info generator for llvm translation. // //===----------------------------------------------------------------------===// #ifndef CLANG_CODEGEN_CGDEBUGINFO_H #define CLANG_CODEGEN_CGDEBUGINFO_H #include "clang/AST/Type.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Analysis/DebugInfo.h" #include <map> #include "CGBuilder.h" namespace clang { class VarDecl; class ObjCInterfaceDecl; namespace CodeGen { class CodeGenModule; /// CGDebugInfo - This class gathers all debug information during compilation /// and is responsible for emitting to llvm globals or pass directly to /// the backend. class CGDebugInfo { CodeGenModule *M; llvm::DIFactory DebugFactory; SourceLocation CurLoc, PrevLoc; /// CompileUnitCache - Cache of previously constructed CompileUnits. llvm::DenseMap<const FileEntry*, llvm::DICompileUnit> CompileUnitCache; /// TypeCache - Cache of previously constructed Types. // FIXME: Eliminate this map. Be careful of iterator invalidation. std::map<void *, llvm::DIType> TypeCache; std::vector<llvm::DIDescriptor> RegionStack; /// Helper functions for getOrCreateType. llvm::DIType CreateType(const BuiltinType *Ty, llvm::DICompileUnit U); llvm::DIType CreateCVRType(QualType Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const TypedefType *Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const PointerType *Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const FunctionType *Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const TagType *Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const RecordType *Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const ObjCInterfaceType *Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const EnumType *Ty, llvm::DICompileUnit U); llvm::DIType CreateType(const ArrayType *Ty, llvm::DICompileUnit U); public: CGDebugInfo(CodeGenModule *m); ~CGDebugInfo(); /// setLocation - Update the current source location. If \arg loc is /// invalid it is ignored. void setLocation(SourceLocation Loc); /// EmitStopPoint - Emit a call to llvm.dbg.stoppoint to indicate a change of /// source line. void EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder); /// EmitFunctionStart - Emit a call to llvm.dbg.function.start to indicate /// start of a new function. void EmitFunctionStart(const char *Name, QualType ReturnType, llvm::Function *Fn, CGBuilderTy &Builder); /// EmitRegionStart - Emit a call to llvm.dbg.region.start to indicate start /// of a new block. void EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder); /// EmitRegionEnd - Emit call to llvm.dbg.region.end to indicate end of a /// block. void EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder); /// EmitDeclareOfAutoVariable - Emit call to llvm.dbg.declare for an automatic /// variable declaration. void EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder); /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument /// variable declaration. void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder); /// EmitGlobalVariable - Emit information about a global variable. void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl); /// EmitGlobalVariable - Emit information about an objective-c interface. void EmitGlobalVariable(llvm::GlobalVariable *GV, ObjCInterfaceDecl *Decl); private: /// EmitDeclare - Emit call to llvm.dbg.declare for a variable declaration. void EmitDeclare(const VarDecl *decl, unsigned Tag, llvm::Value *AI, CGBuilderTy &Builder); /// getOrCreateCompileUnit - Get the compile unit from the cache or create a /// new one if necessary. llvm::DICompileUnit getOrCreateCompileUnit(SourceLocation Loc); /// getOrCreateType - Get the type from the cache or create a new type if /// necessary. llvm::DIType getOrCreateType(QualType Ty, llvm::DICompileUnit Unit); }; } // namespace CodeGen } // namespace clang #endif <file_sep>/test/CodeGen/x86_64-arguments.c // RUN: clang-cc -triple x86_64-unknown-unknown -emit-llvm -o %t %s && // RUN: grep 'define signext i8 @f0()' %t && // RUN: grep 'define signext i16 @f1()' %t && // RUN: grep 'define i32 @f2()' %t && // RUN: grep 'define float @f3()' %t && // RUN: grep 'define double @f4()' %t && // RUN: grep 'define x86_fp80 @f5()' %t && // RUN: grep 'define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8\* %a4)' %t && // RUN: grep 'define void @f7(i32 %a0)' %t && // RUN: grep 'type { i64, double }.*type .0' %t && // RUN: grep 'define .0 @f8_1()' %t && // RUN: grep 'define void @f8_2(.0)' %t char f0(void) { } short f1(void) { } int f2(void) { } float f3(void) { } double f4(void) { } long double f5(void) { } void f6(char a0, short a1, int a2, long long a3, void *a4) { } typedef enum { A, B, C } E; void f7(E a0) { } // Test merging/passing of upper eightbyte with X87 class. union u8 { long double a; int b; }; union u8 f8_1() {} void f8_2(union u8 a0) {} <file_sep>/test/CodeGen/PR3130-cond-constant.c // RUN: clang-cc -emit-llvm %s -o - int a = 2.0 ? 1 : 2; <file_sep>/tools/ccc/test/ccc/stdin.c // RUN: not xcc -### - &> %t && // RUN: grep 'E or -x required when input is from standard input' %t && // RUN: xcc -ccc-print-phases -### -E - &> %t && // RUN: grep '1: preprocessor.*, {0}, cpp-output' %t && // RUN: xcc -ccc-print-phases -### -ObjC -E - &> %t && // RUN: grep '1: preprocessor.*, {0}, objective-c-cpp-output' %t && // RUN: xcc -ccc-print-phases -### -ObjC -x c -E - &> %t && // RUN: grep '1: preprocessor.*, {0}, cpp-output' %t && // RUN: true <file_sep>/lib/Analysis/Environment.cpp //== Environment.cpp - Map from Stmt* to Locations/Values -------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defined the Environment and EnvironmentManager classes. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/Support/Streams.h" #include "llvm/Support/Compiler.h" using namespace clang; SVal Environment::GetSVal(Stmt* E, BasicValueFactory& BasicVals) const { for (;;) { switch (E->getStmtClass()) { case Stmt::AddrLabelExprClass: return Loc::MakeVal(cast<AddrLabelExpr>(E)); // ParenExprs are no-ops. case Stmt::ParenExprClass: E = cast<ParenExpr>(E)->getSubExpr(); continue; case Stmt::CharacterLiteralClass: { CharacterLiteral* C = cast<CharacterLiteral>(E); return NonLoc::MakeVal(BasicVals, C->getValue(), C->getType()); } case Stmt::IntegerLiteralClass: { return NonLoc::MakeVal(BasicVals, cast<IntegerLiteral>(E)); } // Casts where the source and target type are the same // are no-ops. We blast through these to get the descendant // subexpression that has a value. case Stmt::ImplicitCastExprClass: case Stmt::CStyleCastExprClass: { CastExpr* C = cast<CastExpr>(E); QualType CT = C->getType(); if (CT->isVoidType()) return UnknownVal(); break; } // Handle all other Stmt* using a lookup. default: break; }; break; } return LookupExpr(E); } SVal Environment::GetBlkExprSVal(Stmt* E, BasicValueFactory& BasicVals) const { while (1) { switch (E->getStmtClass()) { case Stmt::ParenExprClass: E = cast<ParenExpr>(E)->getSubExpr(); continue; case Stmt::CharacterLiteralClass: { CharacterLiteral* C = cast<CharacterLiteral>(E); return NonLoc::MakeVal(BasicVals, C->getValue(), C->getType()); } case Stmt::IntegerLiteralClass: { return NonLoc::MakeVal(BasicVals, cast<IntegerLiteral>(E)); } default: return LookupBlkExpr(E); } } } Environment EnvironmentManager::BindExpr(const Environment& Env, Stmt* E,SVal V, bool isBlkExpr, bool Invalidate) { assert (E); if (V.isUnknown()) { if (Invalidate) return isBlkExpr ? RemoveBlkExpr(Env, E) : RemoveSubExpr(Env, E); else return Env; } return isBlkExpr ? AddBlkExpr(Env, E, V) : AddSubExpr(Env, E, V); } namespace { class VISIBILITY_HIDDEN MarkLiveCallback : public SymbolVisitor { SymbolReaper &SymReaper; public: MarkLiveCallback(SymbolReaper &symreaper) : SymReaper(symreaper) {} bool VisitSymbol(SymbolRef sym) { SymReaper.markLive(sym); return true; } }; } // end anonymous namespace // RemoveDeadBindings: // - Remove subexpression bindings. // - Remove dead block expression bindings. // - Keep live block expression bindings: // - Mark their reachable symbols live in SymbolReaper, // see ScanReachableSymbols. // - Mark the region in DRoots if the binding is a loc::MemRegionVal. Environment EnvironmentManager::RemoveDeadBindings(Environment Env, Stmt* Loc, SymbolReaper& SymReaper, GRStateManager& StateMgr, const GRState *state, llvm::SmallVectorImpl<const MemRegion*>& DRoots) { // Drop bindings for subexpressions. Env = RemoveSubExprBindings(Env); // Iterate over the block-expr bindings. for (Environment::beb_iterator I = Env.beb_begin(), E = Env.beb_end(); I != E; ++I) { Stmt* BlkExpr = I.getKey(); if (SymReaper.isLive(Loc, BlkExpr)) { SVal X = I.getData(); // If the block expr's value is a memory region, then mark that region. if (isa<loc::MemRegionVal>(X)) DRoots.push_back(cast<loc::MemRegionVal>(X).getRegion()); // Mark all symbols in the block expr's value live. MarkLiveCallback cb(SymReaper); StateMgr.scanReachableSymbols(X, state, cb); } else { // The block expr is dead. SVal X = I.getData(); // Do not misclean LogicalExpr or ConditionalOperator. It is dead at the // beginning of itself, but we need its UndefinedVal to determine its // SVal. if (X.isUndef() && cast<UndefinedVal>(X).getData()) continue; Env = RemoveBlkExpr(Env, BlkExpr); } } return Env; } <file_sep>/include/clang/AST/DeclTemplate.h //===-- DeclTemplate.h - Classes for representing C++ templates -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the C++ template declaration subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H #define LLVM_CLANG_AST_DECLTEMPLATE_H #include "clang/AST/DeclCXX.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/FoldingSet.h" namespace clang { class TemplateParameterList; class TemplateDecl; class FunctionTemplateDecl; class ClassTemplateDecl; class TemplateTypeParmDecl; class NonTypeTemplateParmDecl; class TemplateTemplateParmDecl; /// TemplateParameterList - Stores a list of template parameters for a /// TemplateDecl and its derived classes. class TemplateParameterList { /// The location of the 'template' keyword. SourceLocation TemplateLoc; /// The locations of the '<' and '>' angle brackets. SourceLocation LAngleLoc, RAngleLoc; /// The number of template parameters in this template /// parameter list. unsigned NumParams; TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc, Decl **Params, unsigned NumParams, SourceLocation RAngleLoc); public: static TemplateParameterList *Create(ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, Decl **Params, unsigned NumParams, SourceLocation RAngleLoc); /// iterator - Iterates through the template parameters in this list. typedef Decl** iterator; /// const_iterator - Iterates through the template parameters in this list. typedef Decl* const* const_iterator; iterator begin() { return reinterpret_cast<Decl **>(this + 1); } const_iterator begin() const { return reinterpret_cast<Decl * const *>(this + 1); } iterator end() { return begin() + NumParams; } const_iterator end() const { return begin() + NumParams; } unsigned size() const { return NumParams; } const Decl* getParam(unsigned Idx) const { assert(Idx < size() && "Template parameter index out-of-range"); return begin()[Idx]; } /// \btief Returns the minimum number of arguments needed to form a /// template specialization. This may be fewer than the number of /// template parameters, if some of the parameters have default /// arguments. unsigned getMinRequiredArguments() const; SourceLocation getTemplateLoc() const { return TemplateLoc; } SourceLocation getLAngleLoc() const { return LAngleLoc; } SourceLocation getRAngleLoc() const { return RAngleLoc; } SourceRange getSourceRange() const { return SourceRange(TemplateLoc, RAngleLoc); } }; //===----------------------------------------------------------------------===// // Kinds of Templates //===----------------------------------------------------------------------===// /// TemplateDecl - The base class of all kinds of template declarations (e.g., /// class, function, etc.). The TemplateDecl class stores the list of template /// parameters and a reference to the templated scoped declaration: the /// underlying AST node. class TemplateDecl : public NamedDecl { protected: // This is probably never used. TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name) : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(0) { } // Construct a template decl with the given name and parameters. // Used when there is not templated element (tt-params, alias?). TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params) : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(Params) { } // Construct a template decl with name, parameters, and templated element. TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl) : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl), TemplateParams(Params) { } public: ~TemplateDecl(); /// Get the list of template parameters TemplateParameterList *getTemplateParameters() const { return TemplateParams; } /// Get the underlying, templated declaration. NamedDecl *getTemplatedDecl() const { return TemplatedDecl; } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() >= TemplateFirst && D->getKind() <= TemplateLast; } static bool classof(const TemplateDecl *D) { return true; } static bool classof(const FunctionTemplateDecl *D) { return true; } static bool classof(const ClassTemplateDecl *D) { return true; } static bool classof(const TemplateTemplateParmDecl *D) { return true; } protected: NamedDecl *TemplatedDecl; TemplateParameterList* TemplateParams; }; /// Declaration of a template function. class FunctionTemplateDecl : public TemplateDecl { protected: FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl) : TemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl) { } public: /// Get the underling function declaration of the template. FunctionDecl *getTemplatedDecl() const { return static_cast<FunctionDecl*>(TemplatedDecl); } /// Create a template function node. static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl); // Implement isa/cast/dyncast support static bool classof(const Decl *D) { return D->getKind() == FunctionTemplate; } static bool classof(const FunctionTemplateDecl *D) { return true; } }; //===----------------------------------------------------------------------===// // Kinds of Template Parameters //===----------------------------------------------------------------------===// /// The TemplateParmPosition class defines the position of a template parameter /// within a template parameter list. Because template parameter can be listed /// sequentially for out-of-line template members, each template parameter is /// given a Depth - the nesting of template parameter scopes - and a Position - /// the occurrence within the parameter list. /// This class is inheritedly privately by different kinds of template /// parameters and is not part of the Decl hierarchy. Just a facility. class TemplateParmPosition { protected: // FIXME: This should probably never be called, but it's here as TemplateParmPosition() : Depth(0), Position(0) { /* assert(0 && "Cannot create positionless template parameter"); */ } TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) { } // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for // position? Maybe? unsigned Depth; unsigned Position; public: /// Get the nesting depth of the template parameter. unsigned getDepth() const { return Depth; } /// Get the position of the template parameter within its parameter list. unsigned getPosition() const { return Position; } }; /// TemplateTypeParmDecl - Declaration of a template type parameter, /// e.g., "T" in /// @code /// template<typename T> class vector; /// @endcode class TemplateTypeParmDecl : public TypeDecl { /// \brief Whether this template type parameter was declaration with /// the 'typename' keyword. If false, it was declared with the /// 'class' keyword. bool Typename : 1; /// \brief Whether this template type parameter inherited its /// default argument. bool InheritedDefault : 1; /// \brief The location of the default argument, if any. SourceLocation DefaultArgumentLoc; /// \brief The default template argument, if any. QualType DefaultArgument; TemplateTypeParmDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id, bool Typename, QualType Type) : TypeDecl(TemplateTypeParm, DC, L, Id), Typename(Typename), InheritedDefault(false), DefaultArgument() { TypeForDecl = Type.getTypePtr(); } public: static TemplateTypeParmDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename); /// \brief Whether this template type parameter was declared with /// the 'typename' keyword. If not, it was declared with the 'class' /// keyword. bool wasDeclaredWithTypename() const { return Typename; } /// \brief Determine whether this template parameter has a default /// argument. bool hasDefaultArgument() const { return !DefaultArgument.isNull(); } /// \brief Retrieve the default argument, if any. QualType getDefaultArgument() const { return DefaultArgument; } /// \brief Retrieve the location of the default argument, if any. SourceLocation getDefaultArgumentLoc() const { return DefaultArgumentLoc; } /// \brief Determines whether the default argument was inherited /// from a previous declaration of this template. bool defaultArgumentWasInherited() const { return InheritedDefault; } /// \brief Set the default argument for this template parameter, and /// whether that default argument was inherited from another /// declaration. void setDefaultArgument(QualType DefArg, SourceLocation DefArgLoc, bool Inherited) { DefaultArgument = DefArg; DefaultArgumentLoc = DefArgLoc; InheritedDefault = Inherited; } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == TemplateTypeParm; } static bool classof(const TemplateTypeParmDecl *D) { return true; } protected: /// Serialize this TemplateTypeParmDecl. Called by Decl::Emit. virtual void EmitImpl(llvm::Serializer& S) const; /// Deserialize a TemplateTypeParmDecl. Called by Decl::Create. static TemplateTypeParmDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C); friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C); }; /// NonTypeTemplateParmDecl - Declares a non-type template parameter, /// e.g., "Size" in /// @code /// template<int Size> class array { }; /// @endcode class NonTypeTemplateParmDecl : public VarDecl, protected TemplateParmPosition { /// \brief The default template argument, if any. Expr *DefaultArgument; NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, SourceLocation TSSL = SourceLocation()) : VarDecl(NonTypeTemplateParm, DC, L, Id, T, VarDecl::None, TSSL), TemplateParmPosition(D, P), DefaultArgument(0) { } public: static NonTypeTemplateParmDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, SourceLocation TypeSpecStartLoc = SourceLocation()); using TemplateParmPosition::getDepth; using TemplateParmPosition::getPosition; /// \brief Determine whether this template parameter has a default /// argument. bool hasDefaultArgument() const { return DefaultArgument; } /// \brief Retrieve the default argument, if any. Expr *getDefaultArgument() const { return DefaultArgument; } /// \brief Retrieve the location of the default argument, if any. SourceLocation getDefaultArgumentLoc() const; /// \brief Set the default argument for this template parameter. void setDefaultArgument(Expr *DefArg) { DefaultArgument = DefArg; } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == NonTypeTemplateParm; } static bool classof(const NonTypeTemplateParmDecl *D) { return true; } protected: /// EmitImpl - Serialize this TemplateTypeParmDecl. Called by Decl::Emit. virtual void EmitImpl(llvm::Serializer& S) const; /// CreateImpl - Deserialize a TemplateTypeParmDecl. Called by Decl::Create. static NonTypeTemplateParmDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C); friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C); }; /// TemplateTemplateParmDecl - Declares a template template parameter, /// e.g., "T" in /// @code /// template <template <typename> class T> class container { }; /// @endcode /// A template template parameter is a TemplateDecl because it defines the /// name of a template and the template parameters allowable for substitution. class TemplateTemplateParmDecl : public TemplateDecl, protected TemplateParmPosition { /// \brief The default template argument, if any. Expr *DefaultArgument; TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, TemplateParameterList *Params) : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params), TemplateParmPosition(D, P), DefaultArgument(0) { } public: static TemplateTemplateParmDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, IdentifierInfo *Id, TemplateParameterList *Params); using TemplateParmPosition::getDepth; using TemplateParmPosition::getPosition; /// \brief Determine whether this template parameter has a default /// argument. bool hasDefaultArgument() const { return DefaultArgument; } /// \brief Retrieve the default argument, if any. Expr *getDefaultArgument() const { return DefaultArgument; } /// \brief Retrieve the location of the default argument, if any. SourceLocation getDefaultArgumentLoc() const; /// \brief Set the default argument for this template parameter. void setDefaultArgument(Expr *DefArg) { DefaultArgument = DefArg; } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == TemplateTemplateParm; } static bool classof(const TemplateTemplateParmDecl *D) { return true; } protected: /// EmitImpl - Serialize this TemplateTypeParmDecl. Called by Decl::Emit. virtual void EmitImpl(llvm::Serializer& S) const; /// CreateImpl - Deserialize a TemplateTypeParmDecl. Called by Decl::Create. static TemplateTemplateParmDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C); friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C); }; /// \brief Represents a template argument within a class template /// specialization. class TemplateArgument { union { uintptr_t TypeOrValue; struct { char Value[sizeof(llvm::APSInt)]; void *Type; } Integer; }; /// \brief Location of the beginning of this template argument. SourceLocation StartLoc; public: /// \brief The type of template argument we're storing. enum ArgKind { /// The template argument is a type. It's value is stored in the /// TypeOrValue field. Type = 0, /// The template argument is a declaration Declaration = 1, /// The template argument is an integral value stored in an llvm::APSInt. Integral = 2, /// The template argument is a value- or type-dependent expression /// stored in an Expr*. Expression = 3 } Kind; /// \brief Construct an empty, invalid template argument. TemplateArgument() : TypeOrValue(0), StartLoc(), Kind(Type) { } /// \brief Construct a template type argument. TemplateArgument(SourceLocation Loc, QualType T) : Kind(Type) { TypeOrValue = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); StartLoc = Loc; } /// \brief Construct a template argument that refers to a /// declaration, which is either an external declaration or a /// template declaration. TemplateArgument(SourceLocation Loc, Decl *D) : Kind(Declaration) { // FIXME: Need to be sure we have the "canonical" declaration! TypeOrValue = reinterpret_cast<uintptr_t>(D); StartLoc = Loc; } /// \brief Construct an integral constant template argument. TemplateArgument(SourceLocation Loc, const llvm::APSInt &Value, QualType Type) : Kind(Integral) { new (Integer.Value) llvm::APSInt(Value); Integer.Type = Type.getAsOpaquePtr(); StartLoc = Loc; } /// \brief Construct a template argument that is an expression. /// /// This form of template argument only occurs in template argument /// lists used for dependent types and for expression; it will not /// occur in a non-dependent, canonical template argument list. TemplateArgument(Expr *E); /// \brief Copy constructor for a template argument. TemplateArgument(const TemplateArgument &Other) : Kind(Other.Kind) { if (Kind == Integral) { new (Integer.Value) llvm::APSInt(*Other.getAsIntegral()); Integer.Type = Other.Integer.Type; } else TypeOrValue = Other.TypeOrValue; StartLoc = Other.StartLoc; } TemplateArgument& operator=(const TemplateArgument& Other) { // FIXME: Does not provide the strong guarantee for exception // safety. using llvm::APSInt; if (Kind == Other.Kind && Kind == Integral) { // Copy integral values. *this->getAsIntegral() = *Other.getAsIntegral(); Integer.Type = Other.Integer.Type; } else { // Destroy the current integral value, if that's what we're holding. if (Kind == Integral) getAsIntegral()->~APSInt(); Kind = Other.Kind; if (Other.Kind == Integral) { new (Integer.Value) llvm::APSInt(*Other.getAsIntegral()); Integer.Type = Other.Integer.Type; } else TypeOrValue = Other.TypeOrValue; } StartLoc = Other.StartLoc; return *this; } ~TemplateArgument() { using llvm::APSInt; if (Kind == Integral) getAsIntegral()->~APSInt(); } /// \brief Return the kind of stored template argument. ArgKind getKind() const { return Kind; } /// \brief Retrieve the template argument as a type. QualType getAsType() const { if (Kind != Type) return QualType(); return QualType::getFromOpaquePtr( reinterpret_cast<void*>(TypeOrValue)); } /// \brief Retrieve the template argument as a declaration. Decl *getAsDecl() const { if (Kind != Declaration) return 0; return reinterpret_cast<Decl *>(TypeOrValue); } /// \brief Retrieve the template argument as an integral value. llvm::APSInt *getAsIntegral() { if (Kind != Integral) return 0; return reinterpret_cast<llvm::APSInt*>(&Integer.Value[0]); } const llvm::APSInt *getAsIntegral() const { return const_cast<TemplateArgument*>(this)->getAsIntegral(); } /// \brief Retrieve the type of the integral value. QualType getIntegralType() const { if (Kind != Integral) return QualType(); return QualType::getFromOpaquePtr(Integer.Type); } /// \brief Retrieve the template argument as an expression. Expr *getAsExpr() const { if (Kind != Expression) return 0; return reinterpret_cast<Expr *>(TypeOrValue); } /// \brief Retrieve the location where the template argument starts. SourceLocation getLocation() const { return StartLoc; } /// \brief Used to insert TemplateArguments into FoldingSets. void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(Kind); switch (Kind) { case Type: getAsType().Profile(ID); break; case Declaration: ID.AddPointer(getAsDecl()); // FIXME: Must be canonical! break; case Integral: getAsIntegral()->Profile(ID); getIntegralType().Profile(ID); break; case Expression: // FIXME: We need a canonical representation of expressions. ID.AddPointer(getAsExpr()); break; } } }; // \brief Describes the kind of template specialization that a // particular template specialization declaration represents. enum TemplateSpecializationKind { /// This template specialization was formed from a template-id but /// has not yet been declared, defined, or instantiated. TSK_Undeclared = 0, /// This template specialization was declared or defined by an /// explicit specialization (C++ [temp.expl.spec]). TSK_ExplicitSpecialization, /// This template specialization was implicitly instantiated from a /// template. (C++ [temp.inst]). TSK_ImplicitInstantiation, /// This template specialization was instantiated from a template /// due to an explicit instantiation request (C++ [temp.explicit]). TSK_ExplicitInstantiation }; /// \brief Represents a class template specialization, which refers to /// a class template with a given set of template arguments. /// /// Class template specializations represent both explicit /// specialization of class templates, as in the example below, and /// implicit instantiations of class templates. /// /// \code /// template<typename T> class array; /// /// template<> /// class array<bool> { }; // class template specialization array<bool> /// \endcode class ClassTemplateSpecializationDecl : public CXXRecordDecl, public llvm::FoldingSetNode { /// \brief The template that this specialization specializes ClassTemplateDecl *SpecializedTemplate; /// \brief The number of template arguments. The actual arguments /// are allocated after the ClassTemplateSpecializationDecl object. unsigned NumTemplateArgs : 16; /// \brief The kind of specialization this declaration refers to. /// Really a value of type TemplateSpecializationKind. unsigned SpecializationKind : 2; ClassTemplateSpecializationDecl(DeclContext *DC, SourceLocation L, ClassTemplateDecl *SpecializedTemplate, TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); public: static ClassTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation L, ClassTemplateDecl *SpecializedTemplate, TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, ClassTemplateSpecializationDecl *PrevDecl); /// \brief Retrieve the template that this specialization specializes. ClassTemplateDecl *getSpecializedTemplate() const { return SpecializedTemplate; } typedef const TemplateArgument * template_arg_iterator; template_arg_iterator template_arg_begin() const { return reinterpret_cast<template_arg_iterator>(this + 1); } template_arg_iterator template_arg_end() const { return template_arg_begin() + NumTemplateArgs; } const TemplateArgument *getTemplateArgs() const { return template_arg_begin(); } unsigned getNumTemplateArgs() const { return NumTemplateArgs; } /// \brief Determine the kind of specialization that this /// declaration represents. TemplateSpecializationKind getSpecializationKind() const { return static_cast<TemplateSpecializationKind>(SpecializationKind); } void setSpecializationKind(TemplateSpecializationKind TSK) { SpecializationKind = TSK; } void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, template_arg_begin(), getNumTemplateArgs()); } /// \brief Sets the type of this specialization as it was written by /// the user. This will be a class template specialization type. void setTypeAsWritten(QualType T) { TypeForDecl = T.getTypePtr(); } static void Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg) TemplateArgs[Arg].Profile(ID); } static bool classof(const Decl *D) { return D->getKind() == ClassTemplateSpecialization; } static bool classof(const ClassTemplateSpecializationDecl *) { return true; } }; /// Declaration of a class template. class ClassTemplateDecl : public TemplateDecl { protected: /// \brief Data that is common to all of the declarations of a given /// class template. struct Common { /// \brief The class template specializations for this class /// template, including explicit specializations and instantiations. llvm::FoldingSet<ClassTemplateSpecializationDecl> Specializations; }; /// \brief Previous declaration of this class template. ClassTemplateDecl *PreviousDeclaration; /// \brief Pointer to the data that is common to all of the /// declarations of this class template. /// /// The first declaration of a class template (e.g., the declaration /// with no "previous declaration") owns this pointer. Common *CommonPtr; ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl, ClassTemplateDecl *PrevDecl, Common *CommonPtr) : TemplateDecl(ClassTemplate, DC, L, Name, Params, Decl), PreviousDeclaration(PrevDecl), CommonPtr(CommonPtr) { } ~ClassTemplateDecl(); public: /// Get the underlying class declarations of the template. CXXRecordDecl *getTemplatedDecl() const { return static_cast<CXXRecordDecl *>(TemplatedDecl); } /// Create a class template node. static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl, ClassTemplateDecl *PrevDecl); /// \brief Retrieve the set of specializations of this class template. llvm::FoldingSet<ClassTemplateSpecializationDecl> &getSpecializations() { return CommonPtr->Specializations; } // Implement isa/cast/dyncast support static bool classof(const Decl *D) { return D->getKind() == ClassTemplate; } static bool classof(const ClassTemplateDecl *D) { return true; } virtual void Destroy(ASTContext& C); }; } /* end of namespace clang */ #endif <file_sep>/include/clang/AST/DeclCXX.h //===-- DeclCXX.h - Classes for representing C++ declarations -*- C++ -*-=====// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the C++ Decl subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_DECLCXX_H #define LLVM_CLANG_AST_DECLCXX_H #include "clang/AST/Decl.h" #include "llvm/ADT/SmallVector.h" namespace clang { class ClassTemplateDecl; class CXXRecordDecl; class CXXConstructorDecl; class CXXDestructorDecl; class CXXConversionDecl; class CXXMethodDecl; class ClassTemplateSpecializationDecl; /// OverloadedFunctionDecl - An instance of this class represents a /// set of overloaded functions. All of the functions have the same /// name and occur within the same scope. /// /// An OverloadedFunctionDecl has no ownership over the FunctionDecl /// nodes it contains. Rather, the FunctionDecls are owned by the /// enclosing scope (which also owns the OverloadedFunctionDecl /// node). OverloadedFunctionDecl is used primarily to store a set of /// overloaded functions for name lookup. class OverloadedFunctionDecl : public NamedDecl { protected: OverloadedFunctionDecl(DeclContext *DC, DeclarationName N) : NamedDecl(OverloadedFunction, DC, SourceLocation(), N) { } /// Functions - the set of overloaded functions contained in this /// overload set. llvm::SmallVector<FunctionDecl *, 4> Functions; public: typedef llvm::SmallVector<FunctionDecl *, 4>::iterator function_iterator; typedef llvm::SmallVector<FunctionDecl *, 4>::const_iterator function_const_iterator; static OverloadedFunctionDecl *Create(ASTContext &C, DeclContext *DC, DeclarationName N); /// addOverload - Add an overloaded function FD to this set of /// overloaded functions. void addOverload(FunctionDecl *FD) { assert((FD->getDeclName() == getDeclName() || isa<CXXConversionDecl>(FD) || isa<CXXConstructorDecl>(FD)) && "Overloaded functions must have the same name"); Functions.push_back(FD); // An overloaded function declaration always has the location of // the most-recently-added function declaration. if (FD->getLocation().isValid()) this->setLocation(FD->getLocation()); } function_iterator function_begin() { return Functions.begin(); } function_iterator function_end() { return Functions.end(); } function_const_iterator function_begin() const { return Functions.begin(); } function_const_iterator function_end() const { return Functions.end(); } /// getNumFunctions - the number of overloaded functions stored in /// this set. unsigned getNumFunctions() const { return Functions.size(); } /// getFunction - retrieve the ith function in the overload set. const FunctionDecl *getFunction(unsigned i) const { assert(i < getNumFunctions() && "Illegal function #"); return Functions[i]; } FunctionDecl *getFunction(unsigned i) { assert(i < getNumFunctions() && "Illegal function #"); return Functions[i]; } // getDeclContext - Get the context of these overloaded functions. DeclContext *getDeclContext() { assert(getNumFunctions() > 0 && "Context of an empty overload set"); return getFunction(0)->getDeclContext(); } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == OverloadedFunction; } static bool classof(const OverloadedFunctionDecl *D) { return true; } protected: /// EmitImpl - Serialize this FunctionDecl. Called by Decl::Emit. virtual void EmitImpl(llvm::Serializer& S) const; /// CreateImpl - Deserialize an OverloadedFunctionDecl. Called by /// Decl::Create. static OverloadedFunctionDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C); friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C); friend class CXXRecordDecl; }; /// CXXBaseSpecifier - A base class of a C++ class. /// /// Each CXXBaseSpecifier represents a single, direct base class (or /// struct) of a C++ class (or struct). It specifies the type of that /// base class, whether it is a virtual or non-virtual base, and what /// level of access (public, protected, private) is used for the /// derivation. For example: /// /// @code /// class A { }; /// class B { }; /// class C : public virtual A, protected B { }; /// @endcode /// /// In this code, C will have two CXXBaseSpecifiers, one for "public /// virtual A" and the other for "protected B". class CXXBaseSpecifier { /// Range - The source code range that covers the full base /// specifier, including the "virtual" (if present) and access /// specifier (if present). SourceRange Range; /// Virtual - Whether this is a virtual base class or not. bool Virtual : 1; /// BaseOfClass - Whether this is the base of a class (true) or of a /// struct (false). This determines the mapping from the access /// specifier as written in the source code to the access specifier /// used for semantic analysis. bool BaseOfClass : 1; /// Access - Access specifier as written in the source code (which /// may be AS_none). The actual type of data stored here is an /// AccessSpecifier, but we use "unsigned" here to work around a /// VC++ bug. unsigned Access : 2; /// BaseType - The type of the base class. This will be a class or /// struct (or a typedef of such). QualType BaseType; public: CXXBaseSpecifier() { } CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A, QualType T) : Range(R), Virtual(V), BaseOfClass(BC), Access(A), BaseType(T) { } /// getSourceRange - Retrieves the source range that contains the /// entire base specifier. SourceRange getSourceRange() const { return Range; } /// isVirtual - Determines whether the base class is a virtual base /// class (or not). bool isVirtual() const { return Virtual; } /// getAccessSpecifier - Returns the access specifier for this base /// specifier. This is the actual base specifier as used for /// semantic analysis, so the result can never be AS_none. To /// retrieve the access specifier as written in the source code, use /// getAccessSpecifierAsWritten(). AccessSpecifier getAccessSpecifier() const { if ((AccessSpecifier)Access == AS_none) return BaseOfClass? AS_private : AS_public; else return (AccessSpecifier)Access; } /// getAccessSpecifierAsWritten - Retrieves the access specifier as /// written in the source code (which may mean that no access /// specifier was explicitly written). Use getAccessSpecifier() to /// retrieve the access specifier for use in semantic analysis. AccessSpecifier getAccessSpecifierAsWritten() const { return (AccessSpecifier)Access; } /// getType - Retrieves the type of the base class. This type will /// always be an unqualified class type. QualType getType() const { return BaseType; } }; /// CXXRecordDecl - Represents a C++ struct/union/class. /// FIXME: This class will disappear once we've properly taught RecordDecl /// to deal with C++-specific things. class CXXRecordDecl : public RecordDecl { /// UserDeclaredConstructor - True when this class has a /// user-declared constructor. bool UserDeclaredConstructor : 1; /// UserDeclaredCopyConstructor - True when this class has a /// user-declared copy constructor. bool UserDeclaredCopyConstructor : 1; /// UserDeclaredCopyAssignment - True when this class has a /// user-declared copy assignment operator. bool UserDeclaredCopyAssignment : 1; /// UserDeclaredDestructor - True when this class has a /// user-declared destructor. bool UserDeclaredDestructor : 1; /// Aggregate - True when this class is an aggregate. bool Aggregate : 1; /// PlainOldData - True when this class is a POD-type. bool PlainOldData : 1; /// Polymorphic - True when this class is polymorphic, i.e. has at least one /// virtual member or derives from a polymorphic class. bool Polymorphic : 1; /// Abstract - True when this class is abstract, i.e. has at least one /// pure virtual function, (that can come from a base class). bool Abstract : 1; /// HasTrivialConstructor - True when this class has a trivial constructor bool HasTrivialConstructor : 1; /// Bases - Base classes of this class. /// FIXME: This is wasted space for a union. CXXBaseSpecifier *Bases; /// NumBases - The number of base class specifiers in Bases. unsigned NumBases; /// Conversions - Overload set containing the conversion functions /// of this C++ class (but not its inherited conversion /// functions). Each of the entries in this overload set is a /// CXXConversionDecl. OverloadedFunctionDecl Conversions; /// \brief The template or declaration that is declaration is /// instantiated from. /// /// For non-templates, this value will be NULL. For record /// declarations that describe a class template, this will be a /// pointer to a ClassTemplateDecl. For member /// classes of class template specializations, this will be the /// RecordDecl from which the member class was instantiated. llvm::PointerUnion<ClassTemplateDecl*, CXXRecordDecl*>TemplateOrInstantiation; protected: CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id); ~CXXRecordDecl(); public: /// base_class_iterator - Iterator that traverses the base classes /// of a clas. typedef CXXBaseSpecifier* base_class_iterator; /// base_class_const_iterator - Iterator that traverses the base /// classes of a clas. typedef const CXXBaseSpecifier* base_class_const_iterator; static CXXRecordDecl *Create(ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, CXXRecordDecl* PrevDecl=0); /// setBases - Sets the base classes of this struct or class. void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases); /// getNumBases - Retrieves the number of base classes of this /// class. unsigned getNumBases() const { return NumBases; } base_class_iterator bases_begin() { return Bases; } base_class_const_iterator bases_begin() const { return Bases; } base_class_iterator bases_end() { return Bases + NumBases; } base_class_const_iterator bases_end() const { return Bases + NumBases; } /// hasConstCopyConstructor - Determines whether this class has a /// copy constructor that accepts a const-qualified argument. bool hasConstCopyConstructor(ASTContext &Context) const; /// hasConstCopyAssignment - Determines whether this class has a /// copy assignment operator that accepts a const-qualified argument. bool hasConstCopyAssignment(ASTContext &Context) const; /// addedConstructor - Notify the class that another constructor has /// been added. This routine helps maintain information about the /// class based on which constructors have been added. void addedConstructor(ASTContext &Context, CXXConstructorDecl *ConDecl); /// hasUserDeclaredConstructor - Whether this class has any /// user-declared constructors. When true, a default constructor /// will not be implicitly declared. bool hasUserDeclaredConstructor() const { return UserDeclaredConstructor; } /// hasUserDeclaredCopyConstructor - Whether this class has a /// user-declared copy constructor. When false, a copy constructor /// will be implicitly declared. bool hasUserDeclaredCopyConstructor() const { return UserDeclaredCopyConstructor; } /// addedAssignmentOperator - Notify the class that another assignment /// operator has been added. This routine helps maintain information about the /// class based on which operators have been added. void addedAssignmentOperator(ASTContext &Context, CXXMethodDecl *OpDecl); /// hasUserDeclaredCopyAssignment - Whether this class has a /// user-declared copy assignment operator. When false, a copy /// assigment operator will be implicitly declared. bool hasUserDeclaredCopyAssignment() const { return UserDeclaredCopyAssignment; } /// hasUserDeclaredDestructor - Whether this class has a /// user-declared destructor. When false, a destructor will be /// implicitly declared. bool hasUserDeclaredDestructor() const { return UserDeclaredDestructor; } /// setUserDeclaredDestructor - Set whether this class has a /// user-declared destructor. If not set by the time the class is /// fully defined, a destructor will be implicitly declared. void setUserDeclaredDestructor(bool UCD = true) { UserDeclaredDestructor = UCD; } /// getConversions - Retrieve the overload set containing all of the /// conversion functions in this class. OverloadedFunctionDecl *getConversionFunctions() { return &Conversions; } const OverloadedFunctionDecl *getConversionFunctions() const { return &Conversions; } /// addConversionFunction - Add a new conversion function to the /// list of conversion functions. void addConversionFunction(ASTContext &Context, CXXConversionDecl *ConvDecl); /// isAggregate - Whether this class is an aggregate (C++ /// [dcl.init.aggr]), which is a class with no user-declared /// constructors, no private or protected non-static data members, /// no base classes, and no virtual functions (C++ [dcl.init.aggr]p1). bool isAggregate() const { return Aggregate; } /// setAggregate - Set whether this class is an aggregate (C++ /// [dcl.init.aggr]). void setAggregate(bool Agg) { Aggregate = Agg; } /// isPOD - Whether this class is a POD-type (C++ [class]p4), which is a class /// that is an aggregate that has no non-static non-POD data members, no /// reference data members, no user-defined copy assignment operator and no /// user-defined destructor. bool isPOD() const { return PlainOldData; } /// setPOD - Set whether this class is a POD-type (C++ [class]p4). void setPOD(bool POD) { PlainOldData = POD; } /// isPolymorphic - Whether this class is polymorphic (C++ [class.virtual]), /// which means that the class contains or inherits a virtual function. bool isPolymorphic() const { return Polymorphic; } /// setPolymorphic - Set whether this class is polymorphic (C++ /// [class.virtual]). void setPolymorphic(bool Poly) { Polymorphic = Poly; } /// isAbstract - Whether this class is abstract (C++ [class.abstract]), /// which means that the class contains or inherits a pure virtual function. bool isAbstract() const { return Abstract; } /// setAbstract - Set whether this class is abstract (C++ [class.abstract]) void setAbstract(bool Abs) { Abstract = Abs; } // hasTrivialConstructor - Whether this class has a trivial constructor // (C++ [class.ctor]p5) bool hasTrivialConstructor() const { return HasTrivialConstructor; } // setHasTrivialConstructor - Set whether this class has a trivial constructor // (C++ [class.ctor]p5) void setHasTrivialConstructor(bool TC) { HasTrivialConstructor = TC; } /// \brief If this record is an instantiation of a member class, /// retrieves the member class from which it was instantiated. /// /// This routine will return non-NULL for (non-templated) member /// classes of class templates. For example, given: /// /// \code /// template<typename T> /// struct X { /// struct A { }; /// }; /// \endcode /// /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl /// whose parent is the class template specialization X<int>. For /// this declaration, getInstantiatedFromMemberClass() will return /// the CXXRecordDecl X<T>::A. When a complete definition of /// X<int>::A is required, it will be instantiated from the /// declaration returned by getInstantiatedFromMemberClass(). CXXRecordDecl *getInstantiatedFromMemberClass() { return TemplateOrInstantiation.dyn_cast<CXXRecordDecl*>(); } /// \brief Specify that this record is an instantiation of the /// member class RD. void setInstantiationOfMemberClass(CXXRecordDecl *RD) { TemplateOrInstantiation = RD; } /// \brief Retrieves the class template that is described by this /// class declaration. /// /// Every class template is represented as a ClassTemplateDecl and a /// CXXRecordDecl. The former contains template properties (such as /// the template parameter lists) while the latter contains the /// actual description of the template's /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the /// CXXRecordDecl that from a ClassTemplateDecl, while /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from /// a CXXRecordDecl. ClassTemplateDecl *getDescribedClassTemplate() { return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl*>(); } void setDescribedClassTemplate(ClassTemplateDecl *Template) { TemplateOrInstantiation = Template; } /// viewInheritance - Renders and displays an inheritance diagram /// for this C++ class and all of its base classes (transitively) using /// GraphViz. void viewInheritance(ASTContext& Context) const; static bool classof(const Decl *D) { return D->getKind() == CXXRecord || D->getKind() == ClassTemplateSpecialization; } static bool classof(const CXXRecordDecl *D) { return true; } static bool classof(const ClassTemplateSpecializationDecl *D) { return true; } protected: /// EmitImpl - Serialize this CXXRecordDecl. Called by Decl::Emit. // FIXME: Implement this. //virtual void EmitImpl(llvm::Serializer& S) const; /// CreateImpl - Deserialize a CXXRecordDecl. Called by Decl::Create. // FIXME: Implement this. static CXXRecordDecl* CreateImpl(Kind DK, llvm::Deserializer& D, ASTContext& C); friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C); }; /// CXXMethodDecl - Represents a static or instance method of a /// struct/union/class. class CXXMethodDecl : public FunctionDecl { protected: CXXMethodDecl(Kind DK, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isStatic, bool isInline) : FunctionDecl(DK, RD, L, N, T, (isStatic ? Static : None), isInline) {} public: static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isStatic = false, bool isInline = false); bool isStatic() const { return getStorageClass() == Static; } bool isInstance() const { return !isStatic(); } bool isOutOfLineDefinition() const { return getLexicalDeclContext() != getDeclContext(); } /// getParent - Returns the parent of this method declaration, which /// is the class in which this method is defined. const CXXRecordDecl *getParent() const { return cast<CXXRecordDecl>(FunctionDecl::getParent()); } /// getParent - Returns the parent of this method declaration, which /// is the class in which this method is defined. CXXRecordDecl *getParent() { return const_cast<CXXRecordDecl *>( cast<CXXRecordDecl>(FunctionDecl::getParent())); } /// getThisType - Returns the type of 'this' pointer. /// Should only be called for instance methods. QualType getThisType(ASTContext &C) const; unsigned getTypeQualifiers() const { return getType()->getAsFunctionProtoType()->getTypeQuals(); } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() >= CXXMethod && D->getKind() <= CXXConversion; } static bool classof(const CXXMethodDecl *D) { return true; } protected: /// EmitImpl - Serialize this CXXMethodDecl. Called by Decl::Emit. // FIXME: Implement this. //virtual void EmitImpl(llvm::Serializer& S) const; /// CreateImpl - Deserialize a CXXMethodDecl. Called by Decl::Create. // FIXME: Implement this. static CXXMethodDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C); friend Decl* Decl::Create(llvm::Deserializer& D, ASTContext& C); }; /// CXXBaseOrMemberInitializer - Represents a C++ base or member /// initializer, which is part of a constructor initializer that /// initializes one non-static member variable or one base class. For /// example, in the following, both 'A(a)' and 'f(3.14159)' are member /// initializers: /// /// @code /// class A { }; /// class B : public A { /// float f; /// public: /// B(A& a) : A(a), f(3.14159) { } /// }; class CXXBaseOrMemberInitializer { /// BaseOrMember - This points to the entity being initialized, /// which is either a base class (a Type) or a non-static data /// member. When the low bit is 1, it's a base /// class; when the low bit is 0, it's a member. uintptr_t BaseOrMember; /// Args - The arguments used to initialize the base or member. Expr **Args; unsigned NumArgs; public: /// CXXBaseOrMemberInitializer - Creates a new base-class initializer. explicit CXXBaseOrMemberInitializer(QualType BaseType, Expr **Args, unsigned NumArgs); /// CXXBaseOrMemberInitializer - Creates a new member initializer. explicit CXXBaseOrMemberInitializer(FieldDecl *Member, Expr **Args, unsigned NumArgs); /// ~CXXBaseOrMemberInitializer - Destroy the base or member initializer. ~CXXBaseOrMemberInitializer(); /// arg_iterator - Iterates through the member initialization /// arguments. typedef Expr **arg_iterator; /// arg_const_iterator - Iterates through the member initialization /// arguments. typedef Expr * const * arg_const_iterator; /// isBaseInitializer - Returns true when this initializer is /// initializing a base class. bool isBaseInitializer() const { return (BaseOrMember & 0x1) != 0; } /// isMemberInitializer - Returns true when this initializer is /// initializing a non-static data member. bool isMemberInitializer() const { return (BaseOrMember & 0x1) == 0; } /// getBaseClass - If this is a base class initializer, returns the /// type used to specify the initializer. The resulting type will be /// a class type or a typedef of a class type. If this is not a base /// class initializer, returns NULL. Type *getBaseClass() { if (isBaseInitializer()) return reinterpret_cast<Type*>(BaseOrMember & ~0x01); else return 0; } /// getBaseClass - If this is a base class initializer, returns the /// type used to specify the initializer. The resulting type will be /// a class type or a typedef of a class type. If this is not a base /// class initializer, returns NULL. const Type *getBaseClass() const { if (isBaseInitializer()) return reinterpret_cast<const Type*>(BaseOrMember & ~0x01); else return 0; } /// getMember - If this is a member initializer, returns the /// declaration of the non-static data member being /// initialized. Otherwise, returns NULL. FieldDecl *getMember() { if (isMemberInitializer()) return reinterpret_cast<FieldDecl *>(BaseOrMember); else return 0; } /// begin() - Retrieve an iterator to the first initializer argument. arg_iterator begin() { return Args; } /// begin() - Retrieve an iterator to the first initializer argument. arg_const_iterator begin() const { return Args; } /// end() - Retrieve an iterator past the last initializer argument. arg_iterator end() { return Args + NumArgs; } /// end() - Retrieve an iterator past the last initializer argument. arg_const_iterator end() const { return Args + NumArgs; } /// getNumArgs - Determine the number of arguments used to /// initialize the member or base. unsigned getNumArgs() const { return NumArgs; } }; /// CXXConstructorDecl - Represents a C++ constructor within a /// class. For example: /// /// @code /// class X { /// public: /// explicit X(int); // represented by a CXXConstructorDecl. /// }; /// @endcode class CXXConstructorDecl : public CXXMethodDecl { /// Explicit - Whether this constructor is explicit. bool Explicit : 1; /// ImplicitlyDefined - Whether this constructor was implicitly /// defined by the compiler. When false, the constructor was defined /// by the user. In C++03, this flag will have the same value as /// Implicit. In C++0x, however, a constructor that is /// explicitly defaulted (i.e., defined with " = default") will have /// @c !Implicit && ImplicitlyDefined. bool ImplicitlyDefined : 1; /// FIXME: Add support for base and member initializers. CXXConstructorDecl(CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isExplicit, bool isInline, bool isImplicitlyDeclared) : CXXMethodDecl(CXXConstructor, RD, L, N, T, false, isInline), Explicit(isExplicit), ImplicitlyDefined(false) { setImplicit(isImplicitlyDeclared); } public: static CXXConstructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isExplicit, bool isInline, bool isImplicitlyDeclared); /// isExplicit - Whether this constructor was marked "explicit" or not. bool isExplicit() const { return Explicit; } /// isImplicitlyDefined - Whether this constructor was implicitly /// defined. If false, then this constructor was defined by the /// user. This operation can only be invoked if the constructor has /// already been defined. bool isImplicitlyDefined() const { assert(getBody() != 0 && "Can only get the implicit-definition flag once the constructor has been defined"); return ImplicitlyDefined; } /// setImplicitlyDefined - Set whether this constructor was /// implicitly defined or not. void setImplicitlyDefined(bool ID) { assert(getBody() != 0 && "Can only set the implicit-definition flag once the constructor has been defined"); ImplicitlyDefined = ID; } /// isDefaultConstructor - Whether this constructor is a default /// constructor (C++ [class.ctor]p5), which can be used to /// default-initialize a class of this type. bool isDefaultConstructor() const; /// isCopyConstructor - Whether this constructor is a copy /// constructor (C++ [class.copy]p2, which can be used to copy the /// class. @p TypeQuals will be set to the qualifiers on the /// argument type. For example, @p TypeQuals would be set to @c /// QualType::Const for the following copy constructor: /// /// @code /// class X { /// public: /// X(const X&); /// }; /// @endcode bool isCopyConstructor(ASTContext &Context, unsigned &TypeQuals) const; /// isCopyConstructor - Whether this constructor is a copy /// constructor (C++ [class.copy]p2, which can be used to copy the /// class. bool isCopyConstructor(ASTContext &Context) const { unsigned TypeQuals = 0; return isCopyConstructor(Context, TypeQuals); } /// isConvertingConstructor - Whether this constructor is a /// converting constructor (C++ [class.conv.ctor]), which can be /// used for user-defined conversions. bool isConvertingConstructor() const; // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == CXXConstructor; } static bool classof(const CXXConstructorDecl *D) { return true; } /// EmitImpl - Serialize this CXXConstructorDecl. Called by Decl::Emit. // FIXME: Implement this. //virtual void EmitImpl(llvm::Serializer& S) const; /// CreateImpl - Deserialize a CXXConstructorDecl. Called by Decl::Create. // FIXME: Implement this. static CXXConstructorDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// CXXDestructorDecl - Represents a C++ destructor within a /// class. For example: /// /// @code /// class X { /// public: /// ~X(); // represented by a CXXDestructorDecl. /// }; /// @endcode class CXXDestructorDecl : public CXXMethodDecl { /// ImplicitlyDefined - Whether this destructor was implicitly /// defined by the compiler. When false, the destructor was defined /// by the user. In C++03, this flag will have the same value as /// Implicit. In C++0x, however, a destructor that is /// explicitly defaulted (i.e., defined with " = default") will have /// @c !Implicit && ImplicitlyDefined. bool ImplicitlyDefined : 1; CXXDestructorDecl(CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isInline, bool isImplicitlyDeclared) : CXXMethodDecl(CXXDestructor, RD, L, N, T, false, isInline), ImplicitlyDefined(false) { setImplicit(isImplicitlyDeclared); } public: static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isInline, bool isImplicitlyDeclared); /// isImplicitlyDefined - Whether this destructor was implicitly /// defined. If false, then this destructor was defined by the /// user. This operation can only be invoked if the destructor has /// already been defined. bool isImplicitlyDefined() const { assert(getBody() != 0 && "Can only get the implicit-definition flag once the destructor has been defined"); return ImplicitlyDefined; } /// setImplicitlyDefined - Set whether this destructor was /// implicitly defined or not. void setImplicitlyDefined(bool ID) { assert(getBody() != 0 && "Can only set the implicit-definition flag once the destructor has been defined"); ImplicitlyDefined = ID; } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == CXXDestructor; } static bool classof(const CXXDestructorDecl *D) { return true; } /// EmitImpl - Serialize this CXXDestructorDecl. Called by Decl::Emit. // FIXME: Implement this. //virtual void EmitImpl(llvm::Serializer& S) const; /// CreateImpl - Deserialize a CXXDestructorDecl. Called by Decl::Create. // FIXME: Implement this. static CXXDestructorDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// CXXConversionDecl - Represents a C++ conversion function within a /// class. For example: /// /// @code /// class X { /// public: /// operator bool(); /// }; /// @endcode class CXXConversionDecl : public CXXMethodDecl { /// Explicit - Whether this conversion function is marked /// "explicit", meaning that it can only be applied when the user /// explicitly wrote a cast. This is a C++0x feature. bool Explicit : 1; CXXConversionDecl(CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isInline, bool isExplicit) : CXXMethodDecl(CXXConversion, RD, L, N, T, false, isInline), Explicit(isExplicit) { } public: static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation L, DeclarationName N, QualType T, bool isInline, bool isExplicit); /// isExplicit - Whether this is an explicit conversion operator /// (C++0x only). Explicit conversion operators are only considered /// when the user has explicitly written a cast. bool isExplicit() const { return Explicit; } /// getConversionType - Returns the type that this conversion /// function is converting to. QualType getConversionType() const { return getType()->getAsFunctionType()->getResultType(); } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == CXXConversion; } static bool classof(const CXXConversionDecl *D) { return true; } /// EmitImpl - Serialize this CXXConversionDecl. Called by Decl::Emit. // FIXME: Implement this. //virtual void EmitImpl(llvm::Serializer& S) const; /// CreateImpl - Deserialize a CXXConversionDecl. Called by Decl::Create. // FIXME: Implement this. static CXXConversionDecl* CreateImpl(llvm::Deserializer& D, ASTContext& C); }; /// LinkageSpecDecl - This represents a linkage specification. For example: /// extern "C" void foo(); /// class LinkageSpecDecl : public Decl, public DeclContext { public: /// LanguageIDs - Used to represent the language in a linkage /// specification. The values are part of the serialization abi for /// ASTs and cannot be changed without altering that abi. To help /// ensure a stable abi for this, we choose the DW_LANG_ encodings /// from the dwarf standard. enum LanguageIDs { lang_c = /* DW_LANG_C */ 0x0002, lang_cxx = /* DW_LANG_C_plus_plus */ 0x0004 }; private: /// Language - The language for this linkage specification. LanguageIDs Language; /// HadBraces - Whether this linkage specification had curly braces or not. bool HadBraces : 1; LinkageSpecDecl(DeclContext *DC, SourceLocation L, LanguageIDs lang, bool Braces) : Decl(LinkageSpec, DC, L), DeclContext(LinkageSpec), Language(lang), HadBraces(Braces) { } public: static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, LanguageIDs Lang, bool Braces); LanguageIDs getLanguage() const { return Language; } /// hasBraces - Determines whether this linkage specification had /// braces in its syntactic form. bool hasBraces() const { return HadBraces; } static bool classof(const Decl *D) { return D->getKind() == LinkageSpec; } static bool classof(const LinkageSpecDecl *D) { return true; } static DeclContext *castToDeclContext(const LinkageSpecDecl *D) { return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D)); } static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) { return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC)); } protected: void EmitInRec(llvm::Serializer& S) const; void ReadInRec(llvm::Deserializer& D, ASTContext& C); }; /// UsingDirectiveDecl - Represents C++ using-directive. For example: /// /// using namespace std; /// // NB: UsingDirectiveDecl should be Decl not NamedDecl, but we provide // artificial name, for all using-directives in order to store // them in DeclContext effectively. class UsingDirectiveDecl : public NamedDecl { /// SourceLocation - Location of 'namespace' token. SourceLocation NamespaceLoc; /// IdentLoc - Location of nominated namespace-name identifier. // FIXME: We don't store location of scope specifier. SourceLocation IdentLoc; /// NominatedNamespace - Namespace nominated by using-directive. NamespaceDecl *NominatedNamespace; /// Enclosing context containing both using-directive and nomintated /// namespace. DeclContext *CommonAncestor; /// getUsingDirectiveName - Returns special DeclarationName used by /// using-directives. This is only used by DeclContext for storing /// UsingDirectiveDecls in its lookup structure. static DeclarationName getName() { return DeclarationName::getUsingDirectiveName(); } UsingDirectiveDecl(DeclContext *DC, SourceLocation L, SourceLocation NamespcLoc, SourceLocation IdentLoc, NamespaceDecl *Nominated, DeclContext *CommonAncestor) : NamedDecl(Decl::UsingDirective, DC, L, getName()), NamespaceLoc(NamespcLoc), IdentLoc(IdentLoc), NominatedNamespace(Nominated? Nominated->getOriginalNamespace() : 0), CommonAncestor(CommonAncestor) { } public: /// getNominatedNamespace - Returns namespace nominated by using-directive. NamespaceDecl *getNominatedNamespace() { return NominatedNamespace; } const NamespaceDecl *getNominatedNamespace() const { return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace(); } /// getCommonAncestor - returns common ancestor context of using-directive, /// and nominated by it namespace. DeclContext *getCommonAncestor() { return CommonAncestor; } const DeclContext *getCommonAncestor() const { return CommonAncestor; } /// getNamespaceKeyLocation - Returns location of namespace keyword. SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; } /// getIdentLocation - Returns location of identifier. SourceLocation getIdentLocation() const { return IdentLoc; } static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, SourceLocation NamespaceLoc, SourceLocation IdentLoc, NamespaceDecl *Nominated, DeclContext *CommonAncestor); static bool classof(const Decl *D) { return D->getKind() == Decl::UsingDirective; } static bool classof(const UsingDirectiveDecl *D) { return true; } // Friend for getUsingDirectiveName. friend class DeclContext; }; /// NamespaceAliasDecl - Represents a C++ namespace alias. For example: /// /// @code /// namespace Foo = Bar; /// @endcode class NamespaceAliasDecl : public NamedDecl { SourceLocation AliasLoc; /// IdentLoc - Location of namespace identifier. /// FIXME: We don't store location of scope specifier. SourceLocation IdentLoc; /// Namespace - The Decl that this alias points to. Can either be a /// NamespaceDecl or a NamespaceAliasDecl. NamedDecl *Namespace; NamespaceAliasDecl(DeclContext *DC, SourceLocation L, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation IdentLoc, NamedDecl *Namespace) : NamedDecl(Decl::NamespaceAlias, DC, L, Alias), AliasLoc(AliasLoc), IdentLoc(IdentLoc), Namespace(Namespace) { } public: NamespaceDecl *getNamespace() { if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Namespace)) return AD->getNamespace(); return cast<NamespaceDecl>(Namespace); } const NamespaceDecl *getNamespace() const { return const_cast<NamespaceAliasDecl*>(this)->getNamespace(); } static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation IdentLoc, NamedDecl *Namespace); static bool classof(const Decl *D) { return D->getKind() == Decl::NamespaceAlias; } static bool classof(const NamespaceAliasDecl *D) { return true; } }; class StaticAssertDecl : public Decl { Expr *AssertExpr; StringLiteral *Message; StaticAssertDecl(DeclContext *DC, SourceLocation L, Expr *assertexpr, StringLiteral *message) : Decl(StaticAssert, DC, L), AssertExpr(assertexpr), Message(message) { } public: static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, Expr *AssertExpr, StringLiteral *Message); Expr *getAssertExpr() { return AssertExpr; } const Expr *getAssertExpr() const { return AssertExpr; } StringLiteral *getMessage() { return Message; } const StringLiteral *getMessage() const { return Message; } virtual ~StaticAssertDecl(); virtual void Destroy(ASTContext& C); static bool classof(const Decl *D) { return D->getKind() == Decl::StaticAssert; } static bool classof(StaticAssertDecl *D) { return true; } }; /// Insertion operator for diagnostics. This allows sending AccessSpecifier's /// into a diagnostic with <<. const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, AccessSpecifier AS); } // end namespace clang #endif <file_sep>/lib/Sema/SemaLookup.cpp //===--------------------- SemaLookup.cpp - Name Lookup ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements name lookup for C, C++, Objective-C, and // Objective-C++. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "SemaInherit.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Expr.h" #include "clang/Parse/DeclSpec.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include <set> #include <vector> #include <iterator> #include <utility> #include <algorithm> using namespace clang; typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy; typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet; typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy; /// UsingDirAncestorCompare - Implements strict weak ordering of /// UsingDirectives. It orders them by address of its common ancestor. struct UsingDirAncestorCompare { /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext. bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const { return U->getCommonAncestor() < Ctx; } /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext. bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const { return Ctx < U->getCommonAncestor(); } /// @brief Compares UsingDirectiveDecl common ancestors. bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const { return U1->getCommonAncestor() < U2->getCommonAncestor(); } }; /// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs /// (ordered by common ancestors), found in namespace NS, /// including all found (recursively) in their nominated namespaces. void AddNamespaceUsingDirectives(ASTContext &Context, DeclContext *NS, UsingDirectivesTy &UDirs, NamespaceSet &Visited) { DeclContext::udir_iterator I, End; for (llvm::tie(I, End) = NS->getUsingDirectives(Context); I !=End; ++I) { UDirs.push_back(*I); std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare()); NamespaceDecl *Nominated = (*I)->getNominatedNamespace(); if (Visited.insert(Nominated).second) AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited); } } /// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S, /// including all found in the namespaces they nominate. static void AddScopeUsingDirectives(ASTContext &Context, Scope *S, UsingDirectivesTy &UDirs) { NamespaceSet VisitedNS; if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) { if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx)) VisitedNS.insert(NS); AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS); } else { Scope::udir_iterator I = S->using_directives_begin(), End = S->using_directives_end(); for (; I != End; ++I) { UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>(); UDirs.push_back(UD); std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare()); NamespaceDecl *Nominated = UD->getNominatedNamespace(); if (!VisitedNS.count(Nominated)) { VisitedNS.insert(Nominated); AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ VisitedNS); } } } } /// MaybeConstructOverloadSet - Name lookup has determined that the /// elements in [I, IEnd) have the name that we are looking for, and /// *I is a match for the namespace. This routine returns an /// appropriate Decl for name lookup, which may either be *I or an /// OverloadedFunctionDecl that represents the overloaded functions in /// [I, IEnd). /// /// The existance of this routine is temporary; users of LookupResult /// should be able to handle multiple results, to deal with cases of /// ambiguity and overloaded functions without needing to create a /// Decl node. template<typename DeclIterator> static NamedDecl * MaybeConstructOverloadSet(ASTContext &Context, DeclIterator I, DeclIterator IEnd) { assert(I != IEnd && "Iterator range cannot be empty"); assert(!isa<OverloadedFunctionDecl>(*I) && "Cannot have an overloaded function"); if (isa<FunctionDecl>(*I)) { // If we found a function, there might be more functions. If // so, collect them into an overload set. DeclIterator Last = I; OverloadedFunctionDecl *Ovl = 0; for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) { if (!Ovl) { // FIXME: We leak this overload set. Eventually, we want to // stop building the declarations for these overload sets, so // there will be nothing to leak. Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(), (*I)->getDeclName()); Ovl->addOverload(cast<FunctionDecl>(*I)); } Ovl->addOverload(cast<FunctionDecl>(*Last)); } // If we had more than one function, we built an overload // set. Return it. if (Ovl) return Ovl; } return *I; } /// Merges together multiple LookupResults dealing with duplicated Decl's. static Sema::LookupResult MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) { typedef Sema::LookupResult LResult; typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy; // Remove duplicated Decl pointing at same Decl, by storing them in // associative collection. This might be case for code like: // // namespace A { int i; } // namespace B { using namespace A; } // namespace C { using namespace A; } // // void foo() { // using namespace B; // using namespace C; // ++i; // finds A::i, from both namespace B and C at global scope // } // // C++ [namespace.qual].p3: // The same declaration found more than once is not an ambiguity // (because it is still a unique declaration). DeclsSetTy FoundDecls; // Counter of tag names, and functions for resolving ambiguity // and name hiding. std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0; LookupResultsTy::iterator I = Results.begin(), End = Results.end(); // No name lookup results, return early. if (I == End) return LResult::CreateLookupResult(Context, 0); // Keep track of the tag declaration we found. We only use this if // we find a single tag declaration. TagDecl *TagFound = 0; for (; I != End; ++I) { switch (I->getKind()) { case LResult::NotFound: assert(false && "Should be always successful name lookup result here."); break; case LResult::AmbiguousReference: case LResult::AmbiguousBaseSubobjectTypes: case LResult::AmbiguousBaseSubobjects: assert(false && "Shouldn't get ambiguous lookup here."); break; case LResult::Found: { NamedDecl *ND = I->getAsDecl(); if (TagDecl *TD = dyn_cast<TagDecl>(ND)) { TagFound = Context.getCanonicalDecl(TD); TagNames += FoundDecls.insert(TagFound)? 1 : 0; } else if (isa<FunctionDecl>(ND)) Functions += FoundDecls.insert(ND)? 1 : 0; else FoundDecls.insert(ND); break; } case LResult::FoundOverloaded: for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI) Functions += FoundDecls.insert(*FI)? 1 : 0; break; } } OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions; bool Ambiguous = false, NameHidesTags = false; if (FoundDecls.size() == 1) { // 1) Exactly one result. } else if (TagNames > 1) { // 2) Multiple tag names (even though they may be hidden by an // object name). Ambiguous = true; } else if (FoundDecls.size() - TagNames == 1) { // 3) Ordinary name hides (optional) tag. NameHidesTags = TagFound; } else if (Functions) { // C++ [basic.lookup].p1: // ... Name lookup may associate more than one declaration with // a name if it finds the name to be a function name; the declarations // are said to form a set of overloaded functions (13.1). // Overload resolution (13.3) takes place after name lookup has succeeded. // if (!OrdinaryNonFunc) { // 4) Functions hide tag names. NameHidesTags = TagFound; } else { // 5) Functions + ordinary names. Ambiguous = true; } } else { // 6) Multiple non-tag names Ambiguous = true; } if (Ambiguous) return LResult::CreateLookupResult(Context, FoundDecls.begin(), FoundDecls.size()); if (NameHidesTags) { // There's only one tag, TagFound. Remove it. assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?"); FoundDecls.erase(TagFound); } // Return successful name lookup result. return LResult::CreateLookupResult(Context, MaybeConstructOverloadSet(Context, FoundDecls.begin(), FoundDecls.end())); } // Retrieve the set of identifier namespaces that correspond to a // specific kind of name lookup. inline unsigned getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind, bool CPlusPlus) { unsigned IDNS = 0; switch (NameKind) { case Sema::LookupOrdinaryName: case Sema::LookupOperatorName: case Sema::LookupRedeclarationWithLinkage: IDNS = Decl::IDNS_Ordinary; if (CPlusPlus) IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member; break; case Sema::LookupTagName: IDNS = Decl::IDNS_Tag; break; case Sema::LookupMemberName: IDNS = Decl::IDNS_Member; if (CPlusPlus) IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; break; case Sema::LookupNestedNameSpecifierName: case Sema::LookupNamespaceName: IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member; break; } return IDNS; } Sema::LookupResult Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) { LookupResult Result; Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))? OverloadedDeclSingleDecl : SingleDecl; Result.First = reinterpret_cast<uintptr_t>(D); Result.Last = 0; Result.Context = &Context; return Result; } /// @brief Moves the name-lookup results from Other to this LookupResult. Sema::LookupResult Sema::LookupResult::CreateLookupResult(ASTContext &Context, IdentifierResolver::iterator F, IdentifierResolver::iterator L) { LookupResult Result; Result.Context = &Context; if (F != L && isa<FunctionDecl>(*F)) { IdentifierResolver::iterator Next = F; ++Next; if (Next != L && isa<FunctionDecl>(*Next)) { Result.StoredKind = OverloadedDeclFromIdResolver; Result.First = F.getAsOpaqueValue(); Result.Last = L.getAsOpaqueValue(); return Result; } } Result.StoredKind = SingleDecl; Result.First = reinterpret_cast<uintptr_t>(*F); Result.Last = 0; return Result; } Sema::LookupResult Sema::LookupResult::CreateLookupResult(ASTContext &Context, DeclContext::lookup_iterator F, DeclContext::lookup_iterator L) { LookupResult Result; Result.Context = &Context; if (F != L && isa<FunctionDecl>(*F)) { DeclContext::lookup_iterator Next = F; ++Next; if (Next != L && isa<FunctionDecl>(*Next)) { Result.StoredKind = OverloadedDeclFromDeclContext; Result.First = reinterpret_cast<uintptr_t>(F); Result.Last = reinterpret_cast<uintptr_t>(L); return Result; } } Result.StoredKind = SingleDecl; Result.First = reinterpret_cast<uintptr_t>(*F); Result.Last = 0; return Result; } /// @brief Determine the result of name lookup. Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const { switch (StoredKind) { case SingleDecl: return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound; case OverloadedDeclSingleDecl: case OverloadedDeclFromIdResolver: case OverloadedDeclFromDeclContext: return FoundOverloaded; case AmbiguousLookupStoresBasePaths: return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects; case AmbiguousLookupStoresDecls: return AmbiguousReference; } // We can't ever get here. return NotFound; } /// @brief Converts the result of name lookup into a single (possible /// NULL) pointer to a declaration. /// /// The resulting declaration will either be the declaration we found /// (if only a single declaration was found), an /// OverloadedFunctionDecl (if an overloaded function was found), or /// NULL (if no declaration was found). This conversion must not be /// used anywhere where name lookup could result in an ambiguity. /// /// The OverloadedFunctionDecl conversion is meant as a stop-gap /// solution, since it causes the OverloadedFunctionDecl to be /// leaked. FIXME: Eventually, there will be a better way to iterate /// over the set of overloaded functions returned by name lookup. NamedDecl *Sema::LookupResult::getAsDecl() const { switch (StoredKind) { case SingleDecl: return reinterpret_cast<NamedDecl *>(First); case OverloadedDeclFromIdResolver: return MaybeConstructOverloadSet(*Context, IdentifierResolver::iterator::getFromOpaqueValue(First), IdentifierResolver::iterator::getFromOpaqueValue(Last)); case OverloadedDeclFromDeclContext: return MaybeConstructOverloadSet(*Context, reinterpret_cast<DeclContext::lookup_iterator>(First), reinterpret_cast<DeclContext::lookup_iterator>(Last)); case OverloadedDeclSingleDecl: return reinterpret_cast<OverloadedFunctionDecl*>(First); case AmbiguousLookupStoresDecls: case AmbiguousLookupStoresBasePaths: assert(false && "Name lookup returned an ambiguity that could not be handled"); break; } return 0; } /// @brief Retrieves the BasePaths structure describing an ambiguous /// name lookup, or null. BasePaths *Sema::LookupResult::getBasePaths() const { if (StoredKind == AmbiguousLookupStoresBasePaths) return reinterpret_cast<BasePaths *>(First); return 0; } Sema::LookupResult::iterator::reference Sema::LookupResult::iterator::operator*() const { switch (Result->StoredKind) { case SingleDecl: return reinterpret_cast<NamedDecl*>(Current); case OverloadedDeclSingleDecl: return *reinterpret_cast<NamedDecl**>(Current); case OverloadedDeclFromIdResolver: return *IdentifierResolver::iterator::getFromOpaqueValue(Current); case AmbiguousLookupStoresBasePaths: if (Result->Last) return *reinterpret_cast<NamedDecl**>(Current); // Fall through to handle the DeclContext::lookup_iterator we're // storing. case OverloadedDeclFromDeclContext: case AmbiguousLookupStoresDecls: return *reinterpret_cast<DeclContext::lookup_iterator>(Current); } return 0; } Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() { switch (Result->StoredKind) { case SingleDecl: Current = reinterpret_cast<uintptr_t>((NamedDecl*)0); break; case OverloadedDeclSingleDecl: { NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current); ++I; Current = reinterpret_cast<uintptr_t>(I); break; } case OverloadedDeclFromIdResolver: { IdentifierResolver::iterator I = IdentifierResolver::iterator::getFromOpaqueValue(Current); ++I; Current = I.getAsOpaqueValue(); break; } case AmbiguousLookupStoresBasePaths: if (Result->Last) { NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current); ++I; Current = reinterpret_cast<uintptr_t>(I); break; } // Fall through to handle the DeclContext::lookup_iterator we're // storing. case OverloadedDeclFromDeclContext: case AmbiguousLookupStoresDecls: { DeclContext::lookup_iterator I = reinterpret_cast<DeclContext::lookup_iterator>(Current); ++I; Current = reinterpret_cast<uintptr_t>(I); break; } } return *this; } Sema::LookupResult::iterator Sema::LookupResult::begin() { switch (StoredKind) { case SingleDecl: case OverloadedDeclFromIdResolver: case OverloadedDeclFromDeclContext: case AmbiguousLookupStoresDecls: return iterator(this, First); case OverloadedDeclSingleDecl: { OverloadedFunctionDecl * Ovl = reinterpret_cast<OverloadedFunctionDecl*>(First); return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_begin()))); } case AmbiguousLookupStoresBasePaths: if (Last) return iterator(this, reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin())); else return iterator(this, reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first)); } // Required to suppress GCC warning. return iterator(); } Sema::LookupResult::iterator Sema::LookupResult::end() { switch (StoredKind) { case SingleDecl: case OverloadedDeclFromIdResolver: case OverloadedDeclFromDeclContext: case AmbiguousLookupStoresDecls: return iterator(this, Last); case OverloadedDeclSingleDecl: { OverloadedFunctionDecl * Ovl = reinterpret_cast<OverloadedFunctionDecl*>(First); return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_end()))); } case AmbiguousLookupStoresBasePaths: if (Last) return iterator(this, reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end())); else return iterator(this, reinterpret_cast<uintptr_t>( getBasePaths()->front().Decls.second)); } // Required to suppress GCC warning. return iterator(); } void Sema::LookupResult::Destroy() { if (BasePaths *Paths = getBasePaths()) delete Paths; else if (getKind() == AmbiguousReference) delete[] reinterpret_cast<NamedDecl **>(First); } static void CppNamespaceLookup(ASTContext &Context, DeclContext *NS, DeclarationName Name, Sema::LookupNameKind NameKind, unsigned IDNS, LookupResultsTy &Results, UsingDirectivesTy *UDirs = 0) { assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); // Perform qualified name lookup into the LookupCtx. DeclContext::lookup_iterator I, E; for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I) if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) { Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E)); break; } if (UDirs) { // For each UsingDirectiveDecl, which common ancestor is equal // to NS, we preform qualified name lookup into namespace nominated by it. UsingDirectivesTy::const_iterator UI, UEnd; llvm::tie(UI, UEnd) = std::equal_range(UDirs->begin(), UDirs->end(), NS, UsingDirAncestorCompare()); for (; UI != UEnd; ++UI) CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(), Name, NameKind, IDNS, Results); } } static bool isNamespaceOrTranslationUnitScope(Scope *S) { if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) return Ctx->isFileContext(); return false; } std::pair<bool, Sema::LookupResult> Sema::CppLookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind, bool RedeclarationOnly) { assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup"); unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true); Scope *Initial = S; DeclContext *OutOfLineCtx = 0; IdentifierResolver::iterator I = IdResolver.begin(Name), IEnd = IdResolver.end(); // First we lookup local scope. // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] // ...During unqualified name lookup (3.4.1), the names appear as if // they were declared in the nearest enclosing namespace which contains // both the using-directive and the nominated namespace. // [Note: in this context, “contains” means “contains directly or // indirectly”. // // For example: // namespace A { int i; } // void foo() { // int i; // { // using namespace A; // ++i; // finds local 'i', A::i appears at global scope // } // } // for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { // Check whether the IdResolver has anything in this scope. for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) { if (isAcceptableLookupResult(*I, NameKind, IDNS)) { // We found something. Look for anything else in our scope // with this same name and in an acceptable identifier // namespace, so that we can construct an overload set if we // need to. IdentifierResolver::iterator LastI = I; for (++LastI; LastI != IEnd; ++LastI) { if (!S->isDeclScope(DeclPtrTy::make(*LastI))) break; } LookupResult Result = LookupResult::CreateLookupResult(Context, I, LastI); return std::make_pair(true, Result); } } if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) { LookupResult R; // Perform member lookup into struct. // FIXME: In some cases, we know that every name that could be // found by this qualified name lookup will also be on the // identifier chain. For example, inside a class without any // base classes, we never need to perform qualified lookup // because all of the members are on top of the identifier // chain. if (isa<RecordDecl>(Ctx)) { R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly); if (R || RedeclarationOnly) return std::make_pair(true, R); } if (Ctx->getParent() != Ctx->getLexicalParent()) { // It is out of line defined C++ method or struct, we continue // doing name lookup in parent context. Once we will find namespace // or translation-unit we save it for possible checking // using-directives later. for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext(); OutOfLineCtx = OutOfLineCtx->getParent()) { R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly); if (R || RedeclarationOnly) return std::make_pair(true, R); } } } } // Collect UsingDirectiveDecls in all scopes, and recursively all // nominated namespaces by those using-directives. // UsingDirectives are pushed to heap, in common ancestor pointer // value order. // FIXME: Cache this sorted list in Scope structure, and DeclContext, // so we don't build it for each lookup! UsingDirectivesTy UDirs; for (Scope *SC = Initial; SC; SC = SC->getParent()) if (SC->getFlags() & Scope::DeclScope) AddScopeUsingDirectives(Context, SC, UDirs); // Sort heapified UsingDirectiveDecls. std::sort_heap(UDirs.begin(), UDirs.end()); // Lookup namespace scope, and global scope. // Unqualified name lookup in C++ requires looking into scopes // that aren't strictly lexical, and therefore we walk through the // context as well as walking through the scopes. LookupResultsTy LookupResults; assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) && "We should have been looking only at file context here already."); bool LookedInCtx = false; LookupResult Result; while (OutOfLineCtx && OutOfLineCtx != S->getEntity() && OutOfLineCtx->isNamespace()) { LookedInCtx = true; // Look into context considering using-directives. CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS, LookupResults, &UDirs); if ((Result = MergeLookupResults(Context, LookupResults)) || (RedeclarationOnly && !OutOfLineCtx->isTransparentContext())) return std::make_pair(true, Result); OutOfLineCtx = OutOfLineCtx->getParent(); } for (; S; S = S->getParent()) { DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); assert(Ctx && Ctx->isFileContext() && "We should have been looking only at file context here already."); // Check whether the IdResolver has anything in this scope. for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) { if (isAcceptableLookupResult(*I, NameKind, IDNS)) { // We found something. Look for anything else in our scope // with this same name and in an acceptable identifier // namespace, so that we can construct an overload set if we // need to. IdentifierResolver::iterator LastI = I; for (++LastI; LastI != IEnd; ++LastI) { if (!S->isDeclScope(DeclPtrTy::make(*LastI))) break; } // We store name lookup result, and continue trying to look into // associated context, and maybe namespaces nominated by // using-directives. LookupResults.push_back( LookupResult::CreateLookupResult(Context, I, LastI)); break; } } LookedInCtx = true; // Look into context considering using-directives. CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS, LookupResults, &UDirs); if ((Result = MergeLookupResults(Context, LookupResults)) || (RedeclarationOnly && !Ctx->isTransparentContext())) return std::make_pair(true, Result); } if (!(LookedInCtx || LookupResults.empty())) { // We didn't Performed lookup in Scope entity, so we return // result form IdentifierResolver. assert((LookupResults.size() == 1) && "Wrong size!"); return std::make_pair(true, LookupResults.front()); } return std::make_pair(false, LookupResult()); } /// @brief Perform unqualified name lookup starting from a given /// scope. /// /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is /// used to find names within the current scope. For example, 'x' in /// @code /// int x; /// int f() { /// return x; // unqualified name look finds 'x' in the global scope /// } /// @endcode /// /// Different lookup criteria can find different names. For example, a /// particular scope can have both a struct and a function of the same /// name, and each can be found by certain lookup criteria. For more /// information about lookup criteria, see the documentation for the /// class LookupCriteria. /// /// @param S The scope from which unqualified name lookup will /// begin. If the lookup criteria permits, name lookup may also search /// in the parent scopes. /// /// @param Name The name of the entity that we are searching for. /// /// @param Loc If provided, the source location where we're performing /// name lookup. At present, this is only used to produce diagnostics when /// C library functions (like "malloc") are implicitly declared. /// /// @returns The result of name lookup, which includes zero or more /// declarations and possibly additional information used to diagnose /// ambiguities. Sema::LookupResult Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind, bool RedeclarationOnly, bool AllowBuiltinCreation, SourceLocation Loc) { if (!Name) return LookupResult::CreateLookupResult(Context, 0); if (!getLangOptions().CPlusPlus) { // Unqualified name lookup in C/Objective-C is purely lexical, so // search in the declarations attached to the name. unsigned IDNS = 0; switch (NameKind) { case Sema::LookupOrdinaryName: IDNS = Decl::IDNS_Ordinary; break; case Sema::LookupTagName: IDNS = Decl::IDNS_Tag; break; case Sema::LookupMemberName: IDNS = Decl::IDNS_Member; break; case Sema::LookupOperatorName: case Sema::LookupNestedNameSpecifierName: case Sema::LookupNamespaceName: assert(false && "C does not perform these kinds of name lookup"); break; case Sema::LookupRedeclarationWithLinkage: // Find the nearest non-transparent declaration scope. while (!(S->getFlags() & Scope::DeclScope) || (S->getEntity() && static_cast<DeclContext *>(S->getEntity()) ->isTransparentContext())) S = S->getParent(); IDNS = Decl::IDNS_Ordinary; break; } // Scan up the scope chain looking for a decl that matches this // identifier that is in the appropriate namespace. This search // should not take long, as shadowing of names is uncommon, and // deep shadowing is extremely uncommon. bool LeftStartingScope = false; for (IdentifierResolver::iterator I = IdResolver.begin(Name), IEnd = IdResolver.end(); I != IEnd; ++I) if ((*I)->isInIdentifierNamespace(IDNS)) { if (NameKind == LookupRedeclarationWithLinkage) { // Determine whether this (or a previous) declaration is // out-of-scope. if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I))) LeftStartingScope = true; // If we found something outside of our starting scope that // does not have linkage, skip it. if (LeftStartingScope && !((*I)->hasLinkage())) continue; } if ((*I)->getAttr<OverloadableAttr>()) { // If this declaration has the "overloadable" attribute, we // might have a set of overloaded functions. // Figure out what scope the identifier is in. while (!(S->getFlags() & Scope::DeclScope) || !S->isDeclScope(DeclPtrTy::make(*I))) S = S->getParent(); // Find the last declaration in this scope (with the same // name, naturally). IdentifierResolver::iterator LastI = I; for (++LastI; LastI != IEnd; ++LastI) { if (!S->isDeclScope(DeclPtrTy::make(*LastI))) break; } return LookupResult::CreateLookupResult(Context, I, LastI); } // We have a single lookup result. return LookupResult::CreateLookupResult(Context, *I); } /// If the context has an external AST source attached, look at /// translation unit scope. if (Context.getExternalSource()) { DeclContext::lookup_iterator I, E; for (llvm::tie(I, E) = Context.getTranslationUnitDecl()->lookup(Context, Name); I != E; ++I) if (isAcceptableLookupResult(*I, NameKind, IDNS)) return LookupResult::CreateLookupResult(Context, I, E); } } else { // Perform C++ unqualified name lookup. std::pair<bool, LookupResult> MaybeResult = CppLookupName(S, Name, NameKind, RedeclarationOnly); if (MaybeResult.first) return MaybeResult.second; } // If we didn't find a use of this identifier, and if the identifier // corresponds to a compiler builtin, create the decl object for the builtin // now, injecting it into translation unit scope, and return it. if (NameKind == LookupOrdinaryName || NameKind == LookupRedeclarationWithLinkage) { IdentifierInfo *II = Name.getAsIdentifierInfo(); if (II && AllowBuiltinCreation) { // If this is a builtin on this (or all) targets, create the decl. if (unsigned BuiltinID = II->getBuiltinID()) { // In C++, we don't have any predefined library functions like // 'malloc'. Instead, we'll just error. if (getLangOptions().CPlusPlus && Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) return LookupResult::CreateLookupResult(Context, 0); return LookupResult::CreateLookupResult(Context, LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S, RedeclarationOnly, Loc)); } } if (getLangOptions().ObjC1 && II) { // @interface and @compatibility_alias introduce typedef-like names. // Unlike typedef's, they can only be introduced at file-scope (and are // therefore not scoped decls). They can, however, be shadowed by // other names in IDNS_Ordinary. ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II); if (IDI != ObjCInterfaceDecls.end()) return LookupResult::CreateLookupResult(Context, IDI->second); ObjCAliasTy::iterator I = ObjCAliasDecls.find(II); if (I != ObjCAliasDecls.end()) return LookupResult::CreateLookupResult(Context, I->second->getClassInterface()); } } return LookupResult::CreateLookupResult(Context, 0); } /// @brief Perform qualified name lookup into a given context. /// /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find /// names when the context of those names is explicit specified, e.g., /// "std::vector" or "x->member". /// /// Different lookup criteria can find different names. For example, a /// particular scope can have both a struct and a function of the same /// name, and each can be found by certain lookup criteria. For more /// information about lookup criteria, see the documentation for the /// class LookupCriteria. /// /// @param LookupCtx The context in which qualified name lookup will /// search. If the lookup criteria permits, name lookup may also search /// in the parent contexts or (for C++ classes) base classes. /// /// @param Name The name of the entity that we are searching for. /// /// @param Criteria The criteria that this routine will use to /// determine which names are visible and which names will be /// found. Note that name lookup will find a name that is visible by /// the given criteria, but the entity itself may not be semantically /// correct or even the kind of entity expected based on the /// lookup. For example, searching for a nested-name-specifier name /// might result in an EnumDecl, which is visible but is not permitted /// as a nested-name-specifier in C++03. /// /// @returns The result of name lookup, which includes zero or more /// declarations and possibly additional information used to diagnose /// ambiguities. Sema::LookupResult Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name, LookupNameKind NameKind, bool RedeclarationOnly) { assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); if (!Name) return LookupResult::CreateLookupResult(Context, 0); // If we're performing qualified name lookup (e.g., lookup into a // struct), find fields as part of ordinary name lookup. unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, getLangOptions().CPlusPlus); if (NameKind == LookupOrdinaryName) IDNS |= Decl::IDNS_Member; // Perform qualified name lookup into the LookupCtx. DeclContext::lookup_iterator I, E; for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I) if (isAcceptableLookupResult(*I, NameKind, IDNS)) return LookupResult::CreateLookupResult(Context, I, E); // If this isn't a C++ class or we aren't allowed to look into base // classes, we're done. if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx)) return LookupResult::CreateLookupResult(Context, 0); // Perform lookup into our base classes. BasePaths Paths; Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx))); // Look for this member in our base classes if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx), MemberLookupCriteria(Name, NameKind, IDNS), Paths)) return LookupResult::CreateLookupResult(Context, 0); // C++ [class.member.lookup]p2: // [...] If the resulting set of declarations are not all from // sub-objects of the same type, or the set has a nonstatic member // and includes members from distinct sub-objects, there is an // ambiguity and the program is ill-formed. Otherwise that set is // the result of the lookup. // FIXME: support using declarations! QualType SubobjectType; int SubobjectNumber = 0; for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); Path != PathEnd; ++Path) { const BasePathElement &PathElement = Path->back(); // Determine whether we're looking at a distinct sub-object or not. if (SubobjectType.isNull()) { // This is the first subobject we've looked at. Record it's type. SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); SubobjectNumber = PathElement.SubobjectNumber; } else if (SubobjectType != Context.getCanonicalType(PathElement.Base->getType())) { // We found members of the given name in two subobjects of // different types. This lookup is ambiguous. BasePaths *PathsOnHeap = new BasePaths; PathsOnHeap->swap(Paths); return LookupResult::CreateLookupResult(Context, PathsOnHeap, true); } else if (SubobjectNumber != PathElement.SubobjectNumber) { // We have a different subobject of the same type. // C++ [class.member.lookup]p5: // A static member, a nested type or an enumerator defined in // a base class T can unambiguously be found even if an object // has more than one base class subobject of type T. Decl *FirstDecl = *Path->Decls.first; if (isa<VarDecl>(FirstDecl) || isa<TypeDecl>(FirstDecl) || isa<EnumConstantDecl>(FirstDecl)) continue; if (isa<CXXMethodDecl>(FirstDecl)) { // Determine whether all of the methods are static. bool AllMethodsAreStatic = true; for (DeclContext::lookup_iterator Func = Path->Decls.first; Func != Path->Decls.second; ++Func) { if (!isa<CXXMethodDecl>(*Func)) { assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl"); break; } if (!cast<CXXMethodDecl>(*Func)->isStatic()) { AllMethodsAreStatic = false; break; } } if (AllMethodsAreStatic) continue; } // We have found a nonstatic member name in multiple, distinct // subobjects. Name lookup is ambiguous. BasePaths *PathsOnHeap = new BasePaths; PathsOnHeap->swap(Paths); return LookupResult::CreateLookupResult(Context, PathsOnHeap, false); } } // Lookup in a base class succeeded; return these results. // If we found a function declaration, return an overload set. if (isa<FunctionDecl>(*Paths.front().Decls.first)) return LookupResult::CreateLookupResult(Context, Paths.front().Decls.first, Paths.front().Decls.second); // We found a non-function declaration; return a single declaration. return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first); } /// @brief Performs name lookup for a name that was parsed in the /// source code, and may contain a C++ scope specifier. /// /// This routine is a convenience routine meant to be called from /// contexts that receive a name and an optional C++ scope specifier /// (e.g., "N::M::x"). It will then perform either qualified or /// unqualified name lookup (with LookupQualifiedName or LookupName, /// respectively) on the given name and return those results. /// /// @param S The scope from which unqualified name lookup will /// begin. /// /// @param SS An optional C++ scope-specified, e.g., "::N::M". /// /// @param Name The name of the entity that name lookup will /// search for. /// /// @param Loc If provided, the source location where we're performing /// name lookup. At present, this is only used to produce diagnostics when /// C library functions (like "malloc") are implicitly declared. /// /// @returns The result of qualified or unqualified name lookup. Sema::LookupResult Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS, DeclarationName Name, LookupNameKind NameKind, bool RedeclarationOnly, bool AllowBuiltinCreation, SourceLocation Loc) { if (SS) { if (SS->isInvalid() || RequireCompleteDeclContext(*SS)) return LookupResult::CreateLookupResult(Context, 0); if (SS->isSet()) { return LookupQualifiedName(computeDeclContext(*SS), Name, NameKind, RedeclarationOnly); } } return LookupName(S, Name, NameKind, RedeclarationOnly, AllowBuiltinCreation, Loc); } /// @brief Produce a diagnostic describing the ambiguity that resulted /// from name lookup. /// /// @param Result The ambiguous name lookup result. /// /// @param Name The name of the entity that name lookup was /// searching for. /// /// @param NameLoc The location of the name within the source code. /// /// @param LookupRange A source range that provides more /// source-location information concerning the lookup itself. For /// example, this range might highlight a nested-name-specifier that /// precedes the name. /// /// @returns true bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name, SourceLocation NameLoc, SourceRange LookupRange) { assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); if (BasePaths *Paths = Result.getBasePaths()) { if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) { QualType SubobjectType = Paths->front().back().Base->getType(); Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) << LookupRange; DeclContext::lookup_iterator Found = Paths->front().Decls.first; while (isa<CXXMethodDecl>(*Found) && cast<CXXMethodDecl>(*Found)->isStatic()) ++Found; Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); Result.Destroy(); return true; } assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes && "Unhandled form of name lookup ambiguity"); Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) << Name << LookupRange; std::set<Decl *> DeclsPrinted; for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end(); Path != PathEnd; ++Path) { Decl *D = *Path->Decls.first; if (DeclsPrinted.insert(D).second) Diag(D->getLocation(), diag::note_ambiguous_member_found); } Result.Destroy(); return true; } else if (Result.getKind() == LookupResult::AmbiguousReference) { Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First), **DEnd = reinterpret_cast<NamedDecl **>(Result.Last); for (; DI != DEnd; ++DI) Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI; Result.Destroy(); return true; } assert(false && "Unhandled form of name lookup ambiguity"); // We can't reach here. return true; } // \brief Add the associated classes and namespaces for // argument-dependent lookup with an argument of class type // (C++ [basic.lookup.koenig]p2). static void addAssociatedClassesAndNamespaces(CXXRecordDecl *Class, ASTContext &Context, Sema::AssociatedNamespaceSet &AssociatedNamespaces, Sema::AssociatedClassSet &AssociatedClasses) { // C++ [basic.lookup.koenig]p2: // [...] // -- If T is a class type (including unions), its associated // classes are: the class itself; the class of which it is a // member, if any; and its direct and indirect base // classes. Its associated namespaces are the namespaces in // which its associated classes are defined. // Add the class of which it is a member, if any. DeclContext *Ctx = Class->getDeclContext(); if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) AssociatedClasses.insert(EnclosingClass); // Add the associated namespace for this class. while (Ctx->isRecord()) Ctx = Ctx->getParent(); if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx)) AssociatedNamespaces.insert(EnclosingNamespace); // Add the class itself. If we've already seen this class, we don't // need to visit base classes. if (!AssociatedClasses.insert(Class)) return; // FIXME: Handle class template specializations // Add direct and indirect base classes along with their associated // namespaces. llvm::SmallVector<CXXRecordDecl *, 32> Bases; Bases.push_back(Class); while (!Bases.empty()) { // Pop this class off the stack. Class = Bases.back(); Bases.pop_back(); // Visit the base classes. for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(), BaseEnd = Class->bases_end(); Base != BaseEnd; ++Base) { const RecordType *BaseType = Base->getType()->getAsRecordType(); CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); if (AssociatedClasses.insert(BaseDecl)) { // Find the associated namespace for this base class. DeclContext *BaseCtx = BaseDecl->getDeclContext(); while (BaseCtx->isRecord()) BaseCtx = BaseCtx->getParent(); if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx)) AssociatedNamespaces.insert(EnclosingNamespace); // Make sure we visit the bases of this base class. if (BaseDecl->bases_begin() != BaseDecl->bases_end()) Bases.push_back(BaseDecl); } } } } // \brief Add the associated classes and namespaces for // argument-dependent lookup with an argument of type T // (C++ [basic.lookup.koenig]p2). static void addAssociatedClassesAndNamespaces(QualType T, ASTContext &Context, Sema::AssociatedNamespaceSet &AssociatedNamespaces, Sema::AssociatedClassSet &AssociatedClasses) { // C++ [basic.lookup.koenig]p2: // // For each argument type T in the function call, there is a set // of zero or more associated namespaces and a set of zero or more // associated classes to be considered. The sets of namespaces and // classes is determined entirely by the types of the function // arguments (and the namespace of any template template // argument). Typedef names and using-declarations used to specify // the types do not contribute to this set. The sets of namespaces // and classes are determined in the following way: T = Context.getCanonicalType(T).getUnqualifiedType(); // -- If T is a pointer to U or an array of U, its associated // namespaces and classes are those associated with U. // // We handle this by unwrapping pointer and array types immediately, // to avoid unnecessary recursion. while (true) { if (const PointerType *Ptr = T->getAsPointerType()) T = Ptr->getPointeeType(); else if (const ArrayType *Ptr = Context.getAsArrayType(T)) T = Ptr->getElementType(); else break; } // -- If T is a fundamental type, its associated sets of // namespaces and classes are both empty. if (T->getAsBuiltinType()) return; // -- If T is a class type (including unions), its associated // classes are: the class itself; the class of which it is a // member, if any; and its direct and indirect base // classes. Its associated namespaces are the namespaces in // which its associated classes are defined. if (const RecordType *ClassType = T->getAsRecordType()) if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) { addAssociatedClassesAndNamespaces(ClassDecl, Context, AssociatedNamespaces, AssociatedClasses); return; } // -- If T is an enumeration type, its associated namespace is // the namespace in which it is defined. If it is class // member, its associated class is the member’s class; else // it has no associated class. if (const EnumType *EnumT = T->getAsEnumType()) { EnumDecl *Enum = EnumT->getDecl(); DeclContext *Ctx = Enum->getDeclContext(); if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) AssociatedClasses.insert(EnclosingClass); // Add the associated namespace for this class. while (Ctx->isRecord()) Ctx = Ctx->getParent(); if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx)) AssociatedNamespaces.insert(EnclosingNamespace); return; } // -- If T is a function type, its associated namespaces and // classes are those associated with the function parameter // types and those associated with the return type. if (const FunctionType *FunctionType = T->getAsFunctionType()) { // Return type addAssociatedClassesAndNamespaces(FunctionType->getResultType(), Context, AssociatedNamespaces, AssociatedClasses); const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType); if (!Proto) return; // Argument types for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(), ArgEnd = Proto->arg_type_end(); Arg != ArgEnd; ++Arg) addAssociatedClassesAndNamespaces(*Arg, Context, AssociatedNamespaces, AssociatedClasses); return; } // -- If T is a pointer to a member function of a class X, its // associated namespaces and classes are those associated // with the function parameter types and return type, // together with those associated with X. // // -- If T is a pointer to a data member of class X, its // associated namespaces and classes are those associated // with the member type together with those associated with // X. if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) { // Handle the type that the pointer to member points to. addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(), Context, AssociatedNamespaces, AssociatedClasses); // Handle the class type into which this points. if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType()) addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()), Context, AssociatedNamespaces, AssociatedClasses); return; } // FIXME: What about block pointers? // FIXME: What about Objective-C message sends? } /// \brief Find the associated classes and namespaces for /// argument-dependent lookup for a call with the given set of /// arguments. /// /// This routine computes the sets of associated classes and associated /// namespaces searched by argument-dependent lookup /// (C++ [basic.lookup.argdep]) for a given set of arguments. void Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses) { AssociatedNamespaces.clear(); AssociatedClasses.clear(); // C++ [basic.lookup.koenig]p2: // For each argument type T in the function call, there is a set // of zero or more associated namespaces and a set of zero or more // associated classes to be considered. The sets of namespaces and // classes is determined entirely by the types of the function // arguments (and the namespace of any template template // argument). for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) { Expr *Arg = Args[ArgIdx]; if (Arg->getType() != Context.OverloadTy) { addAssociatedClassesAndNamespaces(Arg->getType(), Context, AssociatedNamespaces, AssociatedClasses); continue; } // [...] In addition, if the argument is the name or address of a // set of overloaded functions and/or function templates, its // associated classes and namespaces are the union of those // associated with each of the members of the set: the namespace // in which the function or function template is defined and the // classes and namespaces associated with its (non-dependent) // parameter types and return type. DeclRefExpr *DRE = 0; if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) { if (unaryOp->getOpcode() == UnaryOperator::AddrOf) DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr()); } else DRE = dyn_cast<DeclRefExpr>(Arg); if (!DRE) continue; OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl()); if (!Ovl) continue; for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), FuncEnd = Ovl->function_end(); Func != FuncEnd; ++Func) { FunctionDecl *FDecl = cast<FunctionDecl>(*Func); // Add the namespace in which this function was defined. Note // that, if this is a member function, we do *not* consider the // enclosing namespace of its class. DeclContext *Ctx = FDecl->getDeclContext(); if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx)) AssociatedNamespaces.insert(EnclosingNamespace); // Add the classes and namespaces associated with the parameter // types and return type of this function. addAssociatedClassesAndNamespaces(FDecl->getType(), Context, AssociatedNamespaces, AssociatedClasses); } } } /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is /// an acceptable non-member overloaded operator for a call whose /// arguments have types T1 (and, if non-empty, T2). This routine /// implements the check in C++ [over.match.oper]p3b2 concerning /// enumeration types. static bool IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, QualType T1, QualType T2, ASTContext &Context) { if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) return true; if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) return true; const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType(); if (Proto->getNumArgs() < 1) return false; if (T1->isEnumeralType()) { QualType ArgType = Proto->getArgType(0).getNonReferenceType(); if (Context.getCanonicalType(T1).getUnqualifiedType() == Context.getCanonicalType(ArgType).getUnqualifiedType()) return true; } if (Proto->getNumArgs() < 2) return false; if (!T2.isNull() && T2->isEnumeralType()) { QualType ArgType = Proto->getArgType(1).getNonReferenceType(); if (Context.getCanonicalType(T2).getUnqualifiedType() == Context.getCanonicalType(ArgType).getUnqualifiedType()) return true; } return false; } void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, FunctionSet &Functions) { // C++ [over.match.oper]p3: // -- The set of non-member candidates is the result of the // unqualified lookup of operator@ in the context of the // expression according to the usual rules for name lookup in // unqualified function calls (3.4.2) except that all member // functions are ignored. However, if no operand has a class // type, only those non-member functions in the lookup set // that have a first parameter of type T1 or “reference to // (possibly cv-qualified) T1”, when T1 is an enumeration // type, or (if there is a right operand) a second parameter // of type T2 or “reference to (possibly cv-qualified) T2”, // when T2 is an enumeration type, are candidate functions. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); LookupResult Operators = LookupName(S, OpName, LookupOperatorName); assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); if (!Operators) return; for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end(); Op != OpEnd; ++Op) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) Functions.insert(FD); // FIXME: canonical FD } } void Sema::ArgumentDependentLookup(DeclarationName Name, Expr **Args, unsigned NumArgs, FunctionSet &Functions) { // Find all of the associated namespaces and classes based on the // arguments we have. AssociatedNamespaceSet AssociatedNamespaces; AssociatedClassSet AssociatedClasses; FindAssociatedClassesAndNamespaces(Args, NumArgs, AssociatedNamespaces, AssociatedClasses); // C++ [basic.lookup.argdep]p3: // Let X be the lookup set produced by unqualified lookup (3.4.1) // and let Y be the lookup set produced by argument dependent // lookup (defined as follows). If X contains [...] then Y is // empty. Otherwise Y is the set of declarations found in the // namespaces associated with the argument types as described // below. The set of declarations found by the lookup of the name // is the union of X and Y. // // Here, we compute Y and add its members to the overloaded // candidate set. for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(), NSEnd = AssociatedNamespaces.end(); NS != NSEnd; ++NS) { // When considering an associated namespace, the lookup is the // same as the lookup performed when the associated namespace is // used as a qualifier (3.4.3.2) except that: // // -- Any using-directives in the associated namespace are // ignored. // // -- FIXME: Any namespace-scope friend functions declared in // associated classes are visible within their respective // namespaces even if they are not visible during an ordinary // lookup (11.4). DeclContext::lookup_iterator I, E; for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) { FunctionDecl *Func = dyn_cast<FunctionDecl>(*I); if (!Func) break; Functions.insert(Func); } } } <file_sep>/test/Preprocessor/_Pragma-syshdr.c // RUN: clang-cc %s -E 2>&1 | grep 'system_header ignored in main file' _Pragma ("GCC system_header") <file_sep>/include/clang/Basic/TargetInfo.h //===--- TargetInfo.h - Expose information about the target -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the TargetInfo interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_BASIC_TARGETINFO_H #define LLVM_CLANG_BASIC_TARGETINFO_H #include "llvm/Support/DataTypes.h" #include <vector> #include <string> namespace llvm { struct fltSemantics; } namespace clang { class Diagnostic; class SourceManager; class LangOptions; namespace Builtin { struct Info; } /// TargetInfo - This class exposes information about the current target. /// class TargetInfo { std::string Triple; protected: // Target values set by the ctor of the actual target implementation. Default // values are specified by the TargetInfo constructor. bool CharIsSigned; unsigned char PointerWidth, PointerAlign; unsigned char WCharWidth, WCharAlign; unsigned char IntWidth, IntAlign; unsigned char FloatWidth, FloatAlign; unsigned char DoubleWidth, DoubleAlign; unsigned char LongDoubleWidth, LongDoubleAlign; unsigned char LongWidth, LongAlign; unsigned char LongLongWidth, LongLongAlign; unsigned char IntMaxTWidth; const char *DescriptionString; const char *UserLabelPrefix; const llvm::fltSemantics *FloatFormat, *DoubleFormat, *LongDoubleFormat; unsigned char RegParmMax, SSERegParmMax; // TargetInfo Constructor. Default initializes all fields. TargetInfo(const std::string &T); public: /// CreateTargetInfo - Return the target info object for the specified target /// triple. static TargetInfo* CreateTargetInfo(const std::string &Triple); virtual ~TargetInfo(); ///===---- Target Data Type Query Methods -------------------------------===// enum IntType { NoInt = 0, SignedShort, UnsignedShort, SignedInt, UnsignedInt, SignedLong, UnsignedLong, SignedLongLong, UnsignedLongLong }; protected: IntType SizeType, IntMaxType, UIntMaxType, PtrDiffType, IntPtrType, WCharType; public: IntType getSizeType() const { return SizeType; } IntType getIntMaxType() const { return IntMaxType; } IntType getUIntMaxType() const { return UIntMaxType; } IntType getPtrDiffType(unsigned AddrSpace) const { return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace); } IntType getIntPtrType() const { return IntPtrType; } IntType getWCharType() const { return WCharType; } /// isCharSigned - Return true if 'char' is 'signed char' or false if it is /// treated as 'unsigned char'. This is implementation defined according to /// C99 6.2.5p15. In our implementation, this is target-specific. bool isCharSigned() const { return CharIsSigned; } /// getPointerWidth - Return the width of pointers on this target, for the /// specified address space. uint64_t getPointerWidth(unsigned AddrSpace) const { return AddrSpace == 0 ? PointerWidth : getPointerWidthV(AddrSpace); } uint64_t getPointerAlign(unsigned AddrSpace) const { return AddrSpace == 0 ? PointerAlign : getPointerAlignV(AddrSpace); } /// getBoolWidth/Align - Return the size of '_Bool' and C++ 'bool' for this /// target, in bits. unsigned getBoolWidth(bool isWide = false) const { return 8; } // FIXME unsigned getBoolAlign(bool isWide = false) const { return 8; } // FIXME unsigned getCharWidth(bool isWide = false) const { return isWide ? getWCharWidth() : 8; // FIXME } unsigned getCharAlign(bool isWide = false) const { return isWide ? getWCharAlign() : 8; // FIXME } /// getShortWidth/Align - Return the size of 'signed short' and /// 'unsigned short' for this target, in bits. unsigned getShortWidth() const { return 16; } // FIXME unsigned getShortAlign() const { return 16; } // FIXME /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for /// this target, in bits. unsigned getIntWidth() const { return IntWidth; } unsigned getIntAlign() const { return IntAlign; } /// getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' /// for this target, in bits. unsigned getLongWidth() const { return LongWidth; } unsigned getLongAlign() const { return LongAlign; } /// getLongLongWidth/Align - Return the size of 'signed long long' and /// 'unsigned long long' for this target, in bits. unsigned getLongLongWidth() const { return LongLongWidth; } unsigned getLongLongAlign() const { return LongLongAlign; } /// getWcharWidth/Align - Return the size of 'wchar_t' for this target, in /// bits. unsigned getWCharWidth() const { return WCharWidth; } unsigned getWCharAlign() const { return WCharAlign; } /// getFloatWidth/Align/Format - Return the size/align/format of 'float'. unsigned getFloatWidth() const { return FloatWidth; } unsigned getFloatAlign() const { return FloatAlign; } const llvm::fltSemantics &getFloatFormat() const { return *FloatFormat; } /// getDoubleWidth/Align/Format - Return the size/align/format of 'double'. unsigned getDoubleWidth() const { return DoubleWidth; } unsigned getDoubleAlign() const { return DoubleAlign; } const llvm::fltSemantics &getDoubleFormat() const { return *DoubleFormat; } /// getLongDoubleWidth/Align/Format - Return the size/align/format of 'long /// double'. unsigned getLongDoubleWidth() const { return LongDoubleWidth; } unsigned getLongDoubleAlign() const { return LongDoubleAlign; } const llvm::fltSemantics &getLongDoubleFormat() const { return *LongDoubleFormat; } /// getIntMaxTWidth - Return the size of intmax_t and uintmax_t for this /// target, in bits. unsigned getIntMaxTWidth() const { return IntMaxTWidth; } /// getUserLabelPrefix - This returns the default value of the /// __USER_LABEL_PREFIX__ macro, which is the prefix given to user symbols by /// default. On most platforms this is "_", but it is "" on some, and "." on /// others. const char *getUserLabelPrefix() const { return UserLabelPrefix; } /// getTypeName - Return the user string for the specified integer type enum. /// For example, SignedShort -> "short". static const char *getTypeName(IntType T); ///===---- Other target property query methods --------------------------===// /// getTargetDefines - Appends the target-specific #define values for this /// target set to the specified buffer. virtual void getTargetDefines(const LangOptions &Opts, std::vector<char> &DefineBuffer) const = 0; /// getTargetBuiltins - Return information about target-specific builtins for /// the current primary target, and info about which builtins are non-portable /// across the current set of primary and secondary targets. virtual void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const = 0; /// getVAListDeclaration - Return the declaration to use for /// __builtin_va_list, which is target-specific. virtual const char *getVAListDeclaration() const = 0; /// isValidGCCRegisterName - Returns whether the passed in string /// is a valid register name according to GCC. This is used by Sema for /// inline asm statements. bool isValidGCCRegisterName(const char *Name) const; // getNormalizedGCCRegisterName - Returns the "normalized" GCC register name. // For example, on x86 it will return "ax" when "eax" is passed in. const char *getNormalizedGCCRegisterName(const char *Name) const; enum ConstraintInfo { CI_None = 0x00, CI_AllowsMemory = 0x01, CI_AllowsRegister = 0x02, CI_ReadWrite = 0x04 }; // validateOutputConstraint, validateInputConstraint - Checks that // a constraint is valid and provides information about it. // FIXME: These should return a real error instead of just true/false. bool validateOutputConstraint(const char *Name, ConstraintInfo &Info) const; bool validateInputConstraint(const char *Name, const std::string *OutputNamesBegin, const std::string *OutputNamesEnd, ConstraintInfo* OutputConstraints, ConstraintInfo &info) const; bool resolveSymbolicName(const char *&Name, const std::string *OutputNamesBegin, const std::string *OutputNamesEnd, unsigned &Index) const; virtual std::string convertConstraint(const char Constraint) const { return std::string(1, Constraint); } // Returns a string of target-specific clobbers, in LLVM format. virtual const char *getClobbers() const = 0; /// getTargetPrefix - Return the target prefix used for identifying /// llvm intrinsics. virtual const char *getTargetPrefix() const = 0; /// getTargetTriple - Return the target triple of the primary target. const char *getTargetTriple() const { return Triple.c_str(); } const char *getTargetDescription() const { return DescriptionString; } struct GCCRegAlias { const char * const Aliases[5]; const char * const Register; }; virtual bool useGlobalsForAutomaticVariables() const { return false; } /// getStringSymbolPrefix - Get the default symbol prefix to /// use for string literals. virtual const char *getStringSymbolPrefix(bool IsConstant) const { return ".str"; } /// getCFStringSymbolPrefix - Get the default symbol prefix /// to use for CFString literals. virtual const char *getCFStringSymbolPrefix() const { return ""; } /// getUnicodeStringSymbolPrefix - Get the default symbol prefix to /// use for string literals. virtual const char *getUnicodeStringSymbolPrefix() const { return ".str"; } /// getUnicodeStringSection - Return the section to use for unicode /// string literals, or 0 if no special section is used. virtual const char *getUnicodeStringSection() const { return 0; } /// getCFStringSection - Return the section to use for CFString /// literals, or 0 if no special section is used. virtual const char *getCFStringSection() const { return "__DATA,__cfstring"; } /// getCFStringDataSection - Return the section to use for the /// constant string data associated with a CFString literal, or 0 if /// no special section is used. virtual const char *getCFStringDataSection() const { return "__TEXT,__cstring,cstring_literals"; } /// getDefaultLangOptions - Allow the target to specify default settings for /// various language options. These may be overridden by command line /// options. virtual void getDefaultLangOptions(LangOptions &Opts) {} /// HandleTargetFeatures - Handle target-specific options like -mattr=+sse2 /// and friends. An array of arguments is passed in: if they are all valid, /// this should handle them and return -1. If there is an error, the index of /// the invalid argument should be returned along with an optional error /// string. /// /// Note that the driver should have already consolidated all the /// target-feature settings and passed them to us in the -mattr list. The /// -mattr list is treated by the code generator as a diff against the -mcpu /// setting, but the driver should pass all enabled options as "+" settings. /// This means that the target should only look at + settings. virtual int HandleTargetFeatures(std::string *StrArray, unsigned NumStrs, std::string &ErrorReason) { if (NumStrs == 0) return -1; return 0; } // getRegParmMax - Returns maximal number of args passed in registers. unsigned getRegParmMax() const { return RegParmMax; } protected: virtual uint64_t getPointerWidthV(unsigned AddrSpace) const { return PointerWidth; } virtual uint64_t getPointerAlignV(unsigned AddrSpace) const { return PointerAlign; } virtual enum IntType getPtrDiffTypeV(unsigned AddrSpace) const { return PtrDiffType; } virtual void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const = 0; virtual void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const = 0; virtual bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const= 0; }; } // end namespace clang #endif <file_sep>/include/clang/AST/StmtVisitor.h //===--- StmtVisitor.h - Visitor for Stmt subclasses ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the StmtVisitor interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMTVISITOR_H #define LLVM_CLANG_AST_STMTVISITOR_H #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" namespace clang { #define DISPATCH(NAME, CLASS) \ return static_cast<ImplClass*>(this)->Visit ## NAME(static_cast<CLASS*>(S)) /// StmtVisitor - This class implements a simple visitor for Stmt subclasses. /// Since Expr derives from Stmt, this also includes support for visiting Exprs. template<typename ImplClass, typename RetTy=void> class StmtVisitor { public: RetTy Visit(Stmt *S) { // If we have a binary expr, dispatch to the subcode of the binop. A smart // optimizer (e.g. LLVM) will fold this comparison into the switch stmt // below. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) { switch (BinOp->getOpcode()) { default: assert(0 && "Unknown binary operator!"); case BinaryOperator::PtrMemD: DISPATCH(BinPtrMemD, BinaryOperator); case BinaryOperator::PtrMemI: DISPATCH(BinPtrMemI, BinaryOperator); case BinaryOperator::Mul: DISPATCH(BinMul, BinaryOperator); case BinaryOperator::Div: DISPATCH(BinDiv, BinaryOperator); case BinaryOperator::Rem: DISPATCH(BinRem, BinaryOperator); case BinaryOperator::Add: DISPATCH(BinAdd, BinaryOperator); case BinaryOperator::Sub: DISPATCH(BinSub, BinaryOperator); case BinaryOperator::Shl: DISPATCH(BinShl, BinaryOperator); case BinaryOperator::Shr: DISPATCH(BinShr, BinaryOperator); case BinaryOperator::LT: DISPATCH(BinLT, BinaryOperator); case BinaryOperator::GT: DISPATCH(BinGT, BinaryOperator); case BinaryOperator::LE: DISPATCH(BinLE, BinaryOperator); case BinaryOperator::GE: DISPATCH(BinGE, BinaryOperator); case BinaryOperator::EQ: DISPATCH(BinEQ, BinaryOperator); case BinaryOperator::NE: DISPATCH(BinNE, BinaryOperator); case BinaryOperator::And: DISPATCH(BinAnd, BinaryOperator); case BinaryOperator::Xor: DISPATCH(BinXor, BinaryOperator); case BinaryOperator::Or : DISPATCH(BinOr, BinaryOperator); case BinaryOperator::LAnd: DISPATCH(BinLAnd, BinaryOperator); case BinaryOperator::LOr : DISPATCH(BinLOr, BinaryOperator); case BinaryOperator::Assign: DISPATCH(BinAssign, BinaryOperator); case BinaryOperator::MulAssign: DISPATCH(BinMulAssign, CompoundAssignOperator); case BinaryOperator::DivAssign: DISPATCH(BinDivAssign, CompoundAssignOperator); case BinaryOperator::RemAssign: DISPATCH(BinRemAssign, CompoundAssignOperator); case BinaryOperator::AddAssign: DISPATCH(BinAddAssign, CompoundAssignOperator); case BinaryOperator::SubAssign: DISPATCH(BinSubAssign, CompoundAssignOperator); case BinaryOperator::ShlAssign: DISPATCH(BinShlAssign, CompoundAssignOperator); case BinaryOperator::ShrAssign: DISPATCH(BinShrAssign, CompoundAssignOperator); case BinaryOperator::AndAssign: DISPATCH(BinAndAssign, CompoundAssignOperator); case BinaryOperator::OrAssign: DISPATCH(BinOrAssign, CompoundAssignOperator); case BinaryOperator::XorAssign: DISPATCH(BinXorAssign, CompoundAssignOperator); case BinaryOperator::Comma: DISPATCH(BinComma, BinaryOperator); } } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) { switch (UnOp->getOpcode()) { default: assert(0 && "Unknown unary operator!"); case UnaryOperator::PostInc: DISPATCH(UnaryPostInc, UnaryOperator); case UnaryOperator::PostDec: DISPATCH(UnaryPostDec, UnaryOperator); case UnaryOperator::PreInc: DISPATCH(UnaryPreInc, UnaryOperator); case UnaryOperator::PreDec: DISPATCH(UnaryPreDec, UnaryOperator); case UnaryOperator::AddrOf: DISPATCH(UnaryAddrOf, UnaryOperator); case UnaryOperator::Deref: DISPATCH(UnaryDeref, UnaryOperator); case UnaryOperator::Plus: DISPATCH(UnaryPlus, UnaryOperator); case UnaryOperator::Minus: DISPATCH(UnaryMinus, UnaryOperator); case UnaryOperator::Not: DISPATCH(UnaryNot, UnaryOperator); case UnaryOperator::LNot: DISPATCH(UnaryLNot, UnaryOperator); case UnaryOperator::Real: DISPATCH(UnaryReal, UnaryOperator); case UnaryOperator::Imag: DISPATCH(UnaryImag, UnaryOperator); case UnaryOperator::Extension: DISPATCH(UnaryExtension, UnaryOperator); case UnaryOperator::OffsetOf: DISPATCH(UnaryOffsetOf, UnaryOperator); } } // Top switch stmt: dispatch to VisitFooStmt for each FooStmt. switch (S->getStmtClass()) { default: assert(0 && "Unknown stmt kind!"); #define STMT(CLASS, PARENT) \ case Stmt::CLASS ## Class: DISPATCH(CLASS, CLASS); #include "clang/AST/StmtNodes.def" } } // If the implementation chooses not to implement a certain visit method, fall // back on VisitExpr or whatever else is the superclass. #define STMT(CLASS, PARENT) \ RetTy Visit ## CLASS(CLASS *S) { DISPATCH(PARENT, PARENT); } #include "clang/AST/StmtNodes.def" // If the implementation doesn't implement binary operator methods, fall back // on VisitBinaryOperator. #define BINOP_FALLBACK(NAME) \ RetTy VisitBin ## NAME(BinaryOperator *S) { \ DISPATCH(BinaryOperator, BinaryOperator); \ } BINOP_FALLBACK(PtrMemD) BINOP_FALLBACK(PtrMemI) BINOP_FALLBACK(Mul) BINOP_FALLBACK(Div) BINOP_FALLBACK(Rem) BINOP_FALLBACK(Add) BINOP_FALLBACK(Sub) BINOP_FALLBACK(Shl) BINOP_FALLBACK(Shr) BINOP_FALLBACK(LT) BINOP_FALLBACK(GT) BINOP_FALLBACK(LE) BINOP_FALLBACK(GE) BINOP_FALLBACK(EQ) BINOP_FALLBACK(NE) BINOP_FALLBACK(And) BINOP_FALLBACK(Xor) BINOP_FALLBACK(Or) BINOP_FALLBACK(LAnd) BINOP_FALLBACK(LOr) BINOP_FALLBACK(Assign) BINOP_FALLBACK(Comma) #undef BINOP_FALLBACK // If the implementation doesn't implement compound assignment operator // methods, fall back on VisitCompoundAssignOperator. #define CAO_FALLBACK(NAME) \ RetTy VisitBin ## NAME(CompoundAssignOperator *S) { \ DISPATCH(CompoundAssignOperator, CompoundAssignOperator); \ } CAO_FALLBACK(MulAssign) CAO_FALLBACK(DivAssign) CAO_FALLBACK(RemAssign) CAO_FALLBACK(AddAssign) CAO_FALLBACK(SubAssign) CAO_FALLBACK(ShlAssign) CAO_FALLBACK(ShrAssign) CAO_FALLBACK(AndAssign) CAO_FALLBACK(OrAssign) CAO_FALLBACK(XorAssign) #undef CAO_FALLBACK // If the implementation doesn't implement unary operator methods, fall back // on VisitUnaryOperator. #define UNARYOP_FALLBACK(NAME) \ RetTy VisitUnary ## NAME(UnaryOperator *S) { \ DISPATCH(UnaryOperator, UnaryOperator); \ } UNARYOP_FALLBACK(PostInc) UNARYOP_FALLBACK(PostDec) UNARYOP_FALLBACK(PreInc) UNARYOP_FALLBACK(PreDec) UNARYOP_FALLBACK(AddrOf) UNARYOP_FALLBACK(Deref) UNARYOP_FALLBACK(Plus) UNARYOP_FALLBACK(Minus) UNARYOP_FALLBACK(Not) UNARYOP_FALLBACK(LNot) UNARYOP_FALLBACK(Real) UNARYOP_FALLBACK(Imag) UNARYOP_FALLBACK(Extension) UNARYOP_FALLBACK(OffsetOf) #undef UNARYOP_FALLBACK // Base case, ignore it. :) RetTy VisitStmt(Stmt *Node) { return RetTy(); } }; #undef DISPATCH } // end namespace clang #endif <file_sep>/test/CodeGen/global-init.c // RUN: clang-cc -emit-llvm -o - %s | not grep "common" // This checks that the global won't be marked as common. // (It shouldn't because it's being initialized). int a; int a = 242; <file_sep>/tools/ccc/test/ccc/Xarch.c // RUN: xcc -ccc-no-clang -### -fsyntax-only -Xarch_i386 -Wall -Xarch_ppc -Wunused -arch i386 -arch ppc %s &> %t && // RUN: grep '"-Xarch"' %t | count 0 && // RUN: grep '"-Wall"' %t | count 1 && // RUN: grep 'i686-apple' %t | grep -v '"-m64"' | count 1 && // RUN: grep '"-Wall"' %t | grep 'i686-apple' | grep -v '"-m64"' | count 1 && // RUN: grep '"-Wunused"' %t | count 1 && // RUN: grep '"-arch" "ppc"' %t | count 1 && // RUN: grep '"-Wunused"' %t | grep '"-arch" "ppc"' | count 1 <file_sep>/include/clang/Analysis/PathSensitive/GRAuditor.h //==- GRAuditor.h - Observers of the creation of ExplodedNodes------*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines GRAuditor and its primary subclasses, an interface // to audit the creation of ExplodedNodes. This interface can be used // to implement simple checkers that do not mutate analysis state but // instead operate by perfoming simple logical checks at key monitoring // locations (e.g., function calls). // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_GRAUDITOR #define LLVM_CLANG_ANALYSIS_GRAUDITOR #include "clang/AST/Expr.h" #include "clang/Analysis/PathSensitive/ExplodedGraph.h" namespace clang { template <typename STATE> class GRAuditor { public: typedef ExplodedNode<STATE> NodeTy; typedef typename STATE::ManagerTy ManagerTy; virtual ~GRAuditor() {} virtual bool Audit(NodeTy* N, ManagerTy& M) = 0; }; } // end clang namespace #endif <file_sep>/test/Analysis/ptr-arith.c // RUN: clang-cc -analyze -checker-simple -analyzer-store=region -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify -triple x86_64-apple-darwin9 %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify -triple i686-apple-darwin9 %s void f1() { int a[10]; int *p = a; ++p; } char* foo(); void f2() { char *p = foo(); ++p; } // This test case checks if we get the right rvalue type of a TypedViewRegion. // The ElementRegion's type depends on the array region's rvalue type. If it was // a pointer type, we would get a loc::SymbolVal for '*p'. char* memchr(); static int domain_port (const char *domain_b, const char *domain_e, const char **domain_e_ptr) { int port = 0; const char *p; const char *colon = memchr (domain_b, ':', domain_e - domain_b); for (p = colon + 1; p < domain_e ; p++) port = 10 * port + (*p - '0'); return port; } <file_sep>/test/CodeGen/blocks-2.c // RUN: clang-cc -g %s -emit-llvm -o %t -fblocks // RUN: grep "func.start" %t | count 4 // 1 declaration, 1 bar, 1 test_block_dbg and 1 for the block. static __inline__ __attribute__((always_inline)) int bar(int va, int vb) { return (va == vb); } int test_block_dbg() { extern int g; static int i = 1; ^(int j){ i = bar(3,4); }(0); return i + g; } <file_sep>/test/Sema/carbon.c // RUN: clang-cc %s -print-stats && // RUN: clang-cc %s -disable-free #ifdef __APPLE__ #include <Carbon/Carbon.h> #endif <file_sep>/lib/CodeGen/CMakeLists.txt set(LLVM_NO_RTTI 1) add_clang_library(clangCodeGen CGBuiltin.cpp CGBlocks.cpp CGCall.cpp CGCXX.cpp CGDebugInfo.cpp CGDecl.cpp CGExprAgg.cpp CGExprComplex.cpp CGExprConstant.cpp CGExpr.cpp CGExprScalar.cpp CGObjC.cpp CGObjCGNU.cpp CGObjCMac.cpp CGStmt.cpp CodeGenFunction.cpp CodeGenModule.cpp CodeGenTypes.cpp Mangle.cpp ModuleBuilder.cpp ) <file_sep>/lib/CodeGen/CodeGenFunction.h //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the internal per-function state used for llvm translation. // //===----------------------------------------------------------------------===// #ifndef CLANG_CODEGEN_CODEGENFUNCTION_H #define CLANG_CODEGEN_CODEGENFUNCTION_H #include "clang/AST/Type.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/ValueHandle.h" #include <map> #include "CGBlocks.h" #include "CGBuilder.h" #include "CGCall.h" #include "CGValue.h" namespace llvm { class BasicBlock; class Module; class SwitchInst; class Value; } namespace clang { class ASTContext; class Decl; class EnumConstantDecl; class FunctionDecl; class FunctionProtoType; class LabelStmt; class ObjCContainerDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; class ObjCMethodDecl; class ObjCImplementationDecl; class ObjCPropertyImplDecl; class TargetInfo; class VarDecl; namespace CodeGen { class CodeGenModule; class CodeGenTypes; class CGDebugInfo; class CGFunctionInfo; class CGRecordLayout; /// CodeGenFunction - This class organizes the per-function state that is used /// while generating LLVM code. class CodeGenFunction : public BlockFunction { CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT public: CodeGenModule &CGM; // Per-module state. TargetInfo &Target; typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; CGBuilderTy Builder; /// CurFuncDecl - Holds the Decl for the current function or method. This /// excludes BlockDecls. const Decl *CurFuncDecl; const CGFunctionInfo *CurFnInfo; QualType FnRetTy; llvm::Function *CurFn; /// ReturnBlock - Unified return block. llvm::BasicBlock *ReturnBlock; /// ReturnValue - The temporary alloca to hold the return value. This is null /// iff the function has no return value. llvm::Instruction *ReturnValue; /// AllocaInsertPoint - This is an instruction in the entry block before which /// we prefer to insert allocas. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; const llvm::Type *LLVMIntTy; uint32_t LLVMPointerWidth; public: /// ObjCEHValueStack - Stack of Objective-C exception values, used for /// rethrows. llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack; /// PushCleanupBlock - Push a new cleanup entry on the stack and set the /// passed in block as the cleanup block. void PushCleanupBlock(llvm::BasicBlock *CleanupBlock); /// CleanupBlockInfo - A struct representing a popped cleanup block. struct CleanupBlockInfo { /// CleanupBlock - the cleanup block llvm::BasicBlock *CleanupBlock; /// SwitchBlock - the block (if any) containing the switch instruction used /// for jumping to the final destination. llvm::BasicBlock *SwitchBlock; /// EndBlock - the default destination for the switch instruction. llvm::BasicBlock *EndBlock; CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb, llvm::BasicBlock *eb) : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb) {} }; /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all /// branch fixups and return a block info struct with the switch block and end /// block. CleanupBlockInfo PopCleanupBlock(); /// CleanupScope - RAII object that will create a cleanup block and set the /// insert point to that block. When destructed, it sets the insert point to /// the previous block and pushes a new cleanup entry on the stack. class CleanupScope { CodeGenFunction& CGF; llvm::BasicBlock *CurBB; llvm::BasicBlock *CleanupBB; public: CleanupScope(CodeGenFunction &cgf) : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()) { CleanupBB = CGF.createBasicBlock("cleanup"); CGF.Builder.SetInsertPoint(CleanupBB); } ~CleanupScope() { CGF.PushCleanupBlock(CleanupBB); CGF.Builder.SetInsertPoint(CurBB); } }; /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup /// blocks that have been added. void EmitCleanupBlocks(size_t OldCleanupStackSize); /// EmitBranchThroughCleanup - Emit a branch from the current insert block /// through the cleanup handling code (if any) and then on to \arg Dest. /// /// FIXME: Maybe this should really be in EmitBranch? Don't we always want /// this behavior for branches? void EmitBranchThroughCleanup(llvm::BasicBlock *Dest); private: CGDebugInfo* DebugInfo; /// LabelIDs - Track arbitrary ids assigned to labels for use in implementing /// the GCC address-of-label extension and indirect goto. IDs are assigned to /// labels inside getIDForAddrOfLabel(). std::map<const LabelStmt*, unsigned> LabelIDs; /// IndirectSwitches - Record the list of switches for indirect /// gotos. Emission of the actual switching code needs to be delayed until all /// AddrLabelExprs have been seen. std::vector<llvm::SwitchInst*> IndirectSwitches; /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C /// decls. llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap; /// LabelMap - This keeps track of the LLVM basic block for each C label. llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap; // BreakContinueStack - This keeps track of where break and continue // statements should jump to. struct BreakContinue { BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb) : BreakBlock(bb), ContinueBlock(cb) {} llvm::BasicBlock *BreakBlock; llvm::BasicBlock *ContinueBlock; }; llvm::SmallVector<BreakContinue, 8> BreakContinueStack; /// SwitchInsn - This is nearest current switch instruction. It is null if if /// current context is not in a switch. llvm::SwitchInst *SwitchInsn; /// CaseRangeBlock - This block holds if condition check for last case /// statement range in current switch instruction. llvm::BasicBlock *CaseRangeBlock; /// InvokeDest - This is the nearest exception target for calls /// which can unwind, when exceptions are being used. llvm::BasicBlock *InvokeDest; // VLASizeMap - This keeps track of the associated size for each VLA type. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we // enter/leave scopes. llvm::DenseMap<const VariableArrayType*, llvm::Value*> VLASizeMap; /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid /// calling llvm.stacksave for multiple VLAs in the same scope. bool DidCallStackSave; struct CleanupEntry { /// CleanupBlock - The block of code that does the actual cleanup. llvm::BasicBlock *CleanupBlock; /// Blocks - Basic blocks that were emitted in the current cleanup scope. std::vector<llvm::BasicBlock *> Blocks; /// BranchFixups - Branch instructions to basic blocks that haven't been /// inserted into the current function yet. std::vector<llvm::BranchInst *> BranchFixups; explicit CleanupEntry(llvm::BasicBlock *cb) : CleanupBlock(cb) {} }; /// CleanupEntries - Stack of cleanup entries. llvm::SmallVector<CleanupEntry, 8> CleanupEntries; typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap; /// BlockScopes - Map of which "cleanup scope" scope basic blocks have. BlockScopeMap BlockScopes; /// CXXThisDecl - When parsing an C++ function, this will hold the implicit /// 'this' declaration. ImplicitParamDecl *CXXThisDecl; public: CodeGenFunction(CodeGenModule &cgm); ASTContext &getContext() const; CGDebugInfo *getDebugInfo() { return DebugInfo; } llvm::BasicBlock *getInvokeDest() { return InvokeDest; } void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; } //===--------------------------------------------------------------------===// // Objective-C //===--------------------------------------------------------------------===// void GenerateObjCMethod(const ObjCMethodDecl *OMD); void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD); /// GenerateObjCGetter - Synthesize an Objective-C property getter function. void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID); /// GenerateObjCSetter - Synthesize an Objective-C property setter function /// for the given property. void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID); //===--------------------------------------------------------------------===// // Block Bits //===--------------------------------------------------------------------===// llvm::Value *BuildBlockLiteralTmp(const BlockExpr *); llvm::Constant *BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size, const llvm::StructType *, std::vector<HelperInfo> *); llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr, const BlockInfo& Info, const Decl *OuterFuncDecl, llvm::DenseMap<const Decl*, llvm::Value*> ldm, uint64_t &Size, uint64_t &Align, llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls, bool &subBlockHasCopyDispose); void BlockForwardSelf(); llvm::Value *LoadBlockStruct(); llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E); const llvm::Type *BuildByRefType(QualType Ty, uint64_t Align); void GenerateCode(const FunctionDecl *FD, llvm::Function *Fn); void StartFunction(const Decl *D, QualType RetTy, llvm::Function *Fn, const FunctionArgList &Args, SourceLocation StartLoc); /// EmitReturnBlock - Emit the unified return block, trying to avoid its /// emission when possible. void EmitReturnBlock(); /// FinishFunction - Complete IR generation of the current function. It is /// legal to call this function even if there is no current insertion point. void FinishFunction(SourceLocation EndLoc=SourceLocation()); /// EmitFunctionProlog - Emit the target specific LLVM code to load the /// arguments for the given function. This is also responsible for naming the /// LLVM function arguments. void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args); /// EmitFunctionEpilog - Emit the target specific LLVM code to return the /// given temporary. void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue); const llvm::Type *ConvertTypeForMem(QualType T); const llvm::Type *ConvertType(QualType T); /// LoadObjCSelf - Load the value of self. This function is only valid while /// generating code for an Objective-C method. llvm::Value *LoadObjCSelf(); /// TypeOfSelfObject - Return type of object that this self represents. QualType TypeOfSelfObject(); /// hasAggregateLLVMType - Return true if the specified AST type will map into /// an aggregate LLVM type or is void. static bool hasAggregateLLVMType(QualType T); /// createBasicBlock - Create an LLVM basic block. llvm::BasicBlock *createBasicBlock(const char *Name="", llvm::Function *Parent=0, llvm::BasicBlock *InsertBefore=0) { #ifdef NDEBUG return llvm::BasicBlock::Create("", Parent, InsertBefore); #else return llvm::BasicBlock::Create(Name, Parent, InsertBefore); #endif } /// getBasicBlockForLabel - Return the LLVM basicblock that the specified /// label maps to. llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S); /// SimplifyForwardingBlocks - If the given basic block is only a /// branch to another basic block, simplify it. This assumes that no /// other code could potentially reference the basic block. void SimplifyForwardingBlocks(llvm::BasicBlock *BB); /// EmitBlock - Emit the given block \arg BB and set it as the insert point, /// adding a fall-through branch from the current insert block if /// necessary. It is legal to call this function even if there is no current /// insertion point. /// /// IsFinished - If true, indicates that the caller has finished emitting /// branches to the given block and does not expect to emit code into it. This /// means the block can be ignored if it is unreachable. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); /// EmitBranch - Emit a branch to the specified basic block from the current /// insert block, taking care to avoid creation of branches from dummy /// blocks. It is legal to call this function even if there is no current /// insertion point. /// /// This function clears the current insertion point. The caller should follow /// calls to this function with calls to Emit*Block prior to generation new /// code. void EmitBranch(llvm::BasicBlock *Block); /// HaveInsertPoint - True if an insertion point is defined. If not, this /// indicates that the current code being emitted is unreachable. bool HaveInsertPoint() const { return Builder.GetInsertBlock() != 0; } /// EnsureInsertPoint - Ensure that an insertion point is defined so that /// emitted IR has a place to go. Note that by definition, if this function /// creates a block then that block is unreachable; callers may do better to /// detect when no insertion point is defined and simply skip IR generation. void EnsureInsertPoint() { if (!HaveInsertPoint()) EmitBlock(createBasicBlock()); } /// ErrorUnsupported - Print out an error that codegen doesn't support the /// specified stmt yet. void ErrorUnsupported(const Stmt *S, const char *Type, bool OmitOnError=false); //===--------------------------------------------------------------------===// // Helpers //===--------------------------------------------------------------------===// /// CreateTempAlloca - This creates a alloca and inserts it into the entry /// block. llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty, const char *Name = "tmp"); /// EvaluateExprAsBool - Perform the usual unary conversions on the specified /// expression and compare the result against zero, returning an Int1Ty value. llvm::Value *EvaluateExprAsBool(const Expr *E); /// EmitAnyExpr - Emit code to compute the specified expression which can have /// any type. The result is returned as an RValue struct. If this is an /// aggregate expression, the aggloc/agglocvolatile arguments indicate where /// the result should be returned. RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0, bool isAggLocVolatile = false); // EmitVAListRef - Emit a "reference" to a va_list; this is either the address // or the value of the expression, depending on how va_list is defined. llvm::Value *EmitVAListRef(const Expr *E); /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will /// always be accessible even if no aggregate location is provided. RValue EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc = 0, bool isAggLocVolatile = false); void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, QualType EltTy); void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); /// StartBlock - Start new block named N. If insert block is a dummy block /// then reuse it. void StartBlock(const char *N); /// getCGRecordLayout - Return record layout info. const CGRecordLayout *getCGRecordLayout(CodeGenTypes &CGT, QualType RTy); /// GetAddrOfStaticLocalVar - Return the address of a static local variable. llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD); /// GetAddrOfLocalVar - Return the address of a local variable. llvm::Value *GetAddrOfLocalVar(const VarDecl *VD); /// getAccessedFieldNo - Given an encoded value and a result number, return /// the input field number being accessed. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); unsigned GetIDForAddrOfLabel(const LabelStmt *L); /// EmitMemSetToZero - Generate code to memset a value of the given type to 0. void EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty); // EmitVAArg - Generate code to get an argument from the passed in pointer // and update it accordingly. The return value is a pointer to the argument. // FIXME: We should be able to get rid of this method and use the va_arg // instruction in LLVM instead once it works well enough. llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); // EmitVLASize - Generate code for any VLA size expressions that might occur // in a variably modified type. If Ty is a VLA, will return the value that // corresponds to the size in bytes of the VLA type. Will return 0 otherwise. llvm::Value *EmitVLASize(QualType Ty); // GetVLASize - Returns an LLVM value that corresponds to the size in bytes // of a variable length array type. llvm::Value *GetVLASize(const VariableArrayType *); /// LoadCXXThis - Load the value of 'this'. This function is only valid while /// generating code for an C++ member function. llvm::Value *LoadCXXThis(); //===--------------------------------------------------------------------===// // Declaration Emission //===--------------------------------------------------------------------===// void EmitDecl(const Decl &D); void EmitBlockVarDecl(const VarDecl &D); void EmitLocalBlockVarDecl(const VarDecl &D); void EmitStaticBlockVarDecl(const VarDecl &D); /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. void EmitParmDecl(const VarDecl &D, llvm::Value *Arg); //===--------------------------------------------------------------------===// // Statement Emission //===--------------------------------------------------------------------===// /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. void EmitStopPoint(const Stmt *S); /// EmitStmt - Emit the code for the statement \arg S. It is legal to call /// this function even if there is no current insertion point. /// /// This function may clear the current insertion point; callers should use /// EnsureInsertPoint if they wish to subsequently generate code without first /// calling EmitBlock, EmitBranch, or EmitStmt. void EmitStmt(const Stmt *S); /// EmitSimpleStmt - Try to emit a "simple" statement which does not /// necessarily require an insertion point or debug information; typically /// because the statement amounts to a jump or a container of other /// statements. /// /// \return True if the statement was handled. bool EmitSimpleStmt(const Stmt *S); RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, llvm::Value *AggLoc = 0, bool isAggVol = false); /// EmitLabel - Emit the block for the given label. It is legal to call this /// function even if there is no current insertion point. void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt. void EmitLabelStmt(const LabelStmt &S); void EmitGotoStmt(const GotoStmt &S); void EmitIndirectGotoStmt(const IndirectGotoStmt &S); void EmitIfStmt(const IfStmt &S); void EmitWhileStmt(const WhileStmt &S); void EmitDoStmt(const DoStmt &S); void EmitForStmt(const ForStmt &S); void EmitReturnStmt(const ReturnStmt &S); void EmitDeclStmt(const DeclStmt &S); void EmitBreakStmt(const BreakStmt &S); void EmitContinueStmt(const ContinueStmt &S); void EmitSwitchStmt(const SwitchStmt &S); void EmitDefaultStmt(const DefaultStmt &S); void EmitCaseStmt(const CaseStmt &S); void EmitCaseStmtRange(const CaseStmt &S); void EmitAsmStmt(const AsmStmt &S); void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); //===--------------------------------------------------------------------===// // LValue Expression Emission //===--------------------------------------------------------------------===// /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. RValue GetUndefRValue(QualType Ty); /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E /// and issue an ErrorUnsupported style diagnostic (using the /// provided Name). RValue EmitUnsupportedRValue(const Expr *E, const char *Name); /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue /// an ErrorUnsupported style diagnostic (using the provided Name). LValue EmitUnsupportedLValue(const Expr *E, const char *Name); /// EmitLValue - Emit code to compute a designator that specifies the location /// of the expression. /// /// This can return one of two things: a simple address or a bitfield /// reference. In either case, the LLVM Value* in the LValue structure is /// guaranteed to be an LLVM pointer type. /// /// If this returns a bitfield reference, nothing about the pointee type of /// the LLVM value is known: For example, it may not be a pointer to an /// integer. /// /// If this returns a normal address, and if the lvalue's C type is fixed /// size, this method guarantees that the returned pointer type will point to /// an LLVM type of the same size of the lvalue's type. If the lvalue has a /// variable length type, this is not possible. /// LValue EmitLValue(const Expr *E); /// EmitLoadOfScalar - Load a scalar value from an address, taking /// care to appropriately convert from the memory representation to /// the LLVM value representation. llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, QualType Ty); /// EmitStoreOfScalar - Store a scalar value to an address, taking /// care to appropriately convert from the memory representation to /// the LLVM value representation. void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, bool Volatile); /// EmitLoadOfLValue - Given an expression that represents a value lvalue, /// this method emits the address of the lvalue, then loads the result as an /// rvalue, returning the rvalue. RValue EmitLoadOfLValue(LValue V, QualType LVType); RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType); RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType); RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType); RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType); /// EmitStoreThroughLValue - Store the specified rvalue into the specified /// lvalue, where both are guaranteed to the have the same type, and that type /// is 'Ty'. void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty); void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst, QualType Ty); void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty); void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty); /// EmitStoreThroughLValue - Store Src into Dst with same constraints as /// EmitStoreThroughLValue. /// /// \param Result [out] - If non-null, this will be set to a Value* for the /// bit-field contents after the store, appropriate for use as the result of /// an assignment to the bit-field. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty, llvm::Value **Result=0); // Note: only availabe for agg return types LValue EmitBinaryOperatorLValue(const BinaryOperator *E); // Note: only available for agg return types LValue EmitCallExprLValue(const CallExpr *E); // Note: only available for agg return types LValue EmitVAArgExprLValue(const VAArgExpr *E); LValue EmitDeclRefLValue(const DeclRefExpr *E); LValue EmitStringLiteralLValue(const StringLiteral *E); LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); LValue EmitPredefinedFunctionName(unsigned Type); LValue EmitPredefinedLValue(const PredefinedExpr *E); LValue EmitUnaryOpLValue(const UnaryOperator *E); LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E); LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); LValue EmitMemberExpr(const MemberExpr *E); LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); LValue EmitConditionalOperator(const ConditionalOperator *E); LValue EmitCastLValue(const CastExpr *E); llvm::Value *EmitIvarOffset(ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar); LValue EmitLValueForField(llvm::Value* Base, FieldDecl* Field, bool isUnion, unsigned CVRQualifiers); LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value* Base, const ObjCIvarDecl *Ivar, const FieldDecl *Field, unsigned CVRQualifiers); LValue EmitLValueForBitfield(llvm::Value* Base, FieldDecl* Field, unsigned CVRQualifiers); LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E); LValue EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E); LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E); LValue EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E); LValue EmitObjCSuperExpr(const ObjCSuperExpr *E); //===--------------------------------------------------------------------===// // Scalar Expression Emission //===--------------------------------------------------------------------===// /// EmitCall - Generate a call of the given function, expecting the given /// result type, and using the given argument list which specifies both the /// LLVM arguments and the types they were derived from. /// /// \param TargetDecl - If given, the decl of the function in a /// direct call; used to set attributes on the call (noreturn, /// etc.). RValue EmitCall(const CGFunctionInfo &FnInfo, llvm::Value *Callee, const CallArgList &Args, const Decl *TargetDecl = 0); RValue EmitCallExpr(const CallExpr *E); RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E); RValue EmitCallExpr(llvm::Value *Callee, QualType FnType, CallExpr::const_arg_iterator ArgBeg, CallExpr::const_arg_iterator ArgEnd, const Decl *TargetDecl = 0); RValue EmitBuiltinExpr(const FunctionDecl *FD, unsigned BuiltinID, const CallExpr *E); RValue EmitBlockCallExpr(const CallExpr *E); /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call /// is unhandled by the current target. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); llvm::Value *EmitShuffleVector(llvm::Value* V1, llvm::Value *V2, ...); llvm::Value *EmitVector(llvm::Value * const *Vals, unsigned NumVals, bool isSplat = false); llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); RValue EmitObjCMessageExpr(const ObjCMessageExpr *E); RValue EmitObjCPropertyGet(const Expr *E); RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S); void EmitObjCPropertySet(const Expr *E, RValue Src); void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src); //===--------------------------------------------------------------------===// // Expression Emission //===--------------------------------------------------------------------===// // Expressions are broken into three classes: scalar, complex, aggregate. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM /// scalar type, returning the result. llvm::Value *EmitScalarExpr(const Expr *E); /// EmitScalarConversion - Emit a conversion from the specified type to the /// specified destination type, both of which are LLVM scalar types. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy); /// EmitComplexToScalarConversion - Emit a conversion from the specified /// complex type to the specified destination type, where the destination type /// is an LLVM scalar type. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy); /// EmitAggExpr - Emit the computation of the specified expression of /// aggregate type. The result is computed into DestPtr. Note that if /// DestPtr is null, the value of the aggregate expression is not needed. void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest); /// EmitComplexExpr - Emit the computation of the specified expression of /// complex type, returning the result. ComplexPairTy EmitComplexExpr(const Expr *E); /// EmitComplexExprIntoAddr - Emit the computation of the specified expression /// of complex type, storing into the specified Value*. void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr, bool DestIsVolatile); /// StoreComplexToAddr - Store a complex number into the specified address. void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr, bool DestIsVolatile); /// LoadComplexFromAddr - Load a complex number from the specified address. ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile); /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global /// for a static block var decl. llvm::GlobalVariable * CreateStaticBlockVarDecl(const VarDecl &D, const char *Separator, llvm::GlobalValue::LinkageTypes Linkage); /// GenerateStaticCXXBlockVarDecl - Create the initializer for a C++ /// runtime initialized static block var decl. void GenerateStaticCXXBlockVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV); //===--------------------------------------------------------------------===// // Internal Helpers //===--------------------------------------------------------------------===// /// ContainsLabel - Return true if the statement contains a label in it. If /// this statement is not executed normally, it not containing a label means /// that we can just remove the code. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); /// ConstantFoldsToSimpleInteger - If the specified expression does not fold /// to a constant, or if it does but contains a label, return 0. If it /// constant folds to 'true' and does not contain a label, return 1, if it /// constant folds to 'false' and does not contain a label, return -1. int ConstantFoldsToSimpleInteger(const Expr *Cond); /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an /// if statement) to the specified blocks. Based on the condition, this might /// try to simplify the codegen of the conditional based on the branch. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock); private: /// EmitIndirectSwitches - Emit code for all of the switch /// instructions in IndirectSwitches. void EmitIndirectSwitches(); void EmitReturnOfRValue(RValue RV, QualType Ty); /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty /// from function arguments into \arg Dst. See ABIArgInfo::Expand. /// /// \param AI - The first function argument of the expansion. /// \return The argument following the last expanded function /// argument. llvm::Function::arg_iterator ExpandTypeFromArgs(QualType Ty, LValue Dst, llvm::Function::arg_iterator AI); /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg /// Ty, into individual arguments on the provided vector \arg Args. See /// ABIArgInfo::Expand. void ExpandTypeToArgs(QualType Ty, RValue Src, llvm::SmallVector<llvm::Value*, 16> &Args); llvm::Value* EmitAsmInput(const AsmStmt &S, TargetInfo::ConstraintInfo Info, const Expr *InputExpr, std::string &ConstraintStr); /// EmitCleanupBlock - emits a single cleanup block. void EmitCleanupBlock(); /// AddBranchFixup - adds a branch instruction to the list of fixups for the /// current cleanup scope. void AddBranchFixup(llvm::BranchInst *BI); /// EmitCallArg - Emit a single call argument. RValue EmitCallArg(const Expr *E, QualType ArgType); /// EmitCallArgs - Emit call arguments for a function. /// FIXME: It should be possible to generalize this and pass a generic /// "argument type container" type instead of the FunctionProtoType. This way /// it can work on Objective-C methods as well. void EmitCallArgs(CallArgList& args, const FunctionProtoType *FPT, CallExpr::const_arg_iterator ArgBeg, CallExpr::const_arg_iterator ArgEnd); }; } // end namespace CodeGen } // end namespace clang #endif <file_sep>/lib/Sema/SemaExprCXX.cpp //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for C++ expressions. // //===----------------------------------------------------------------------===// #include "SemaInherit.h" #include "Sema.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ASTContext.h" #include "clang/Parse/DeclSpec.h" #include "clang/Lex/Preprocessor.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/STLExtras.h" using namespace clang; /// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function /// name (e.g., operator void const *) as an expression. This is /// very similar to ActOnIdentifierExpr, except that instead of /// providing an identifier the parser provides the type of the /// conversion function. Sema::OwningExprResult Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc, TypeTy *Ty, bool HasTrailingLParen, const CXXScopeSpec &SS, bool isAddressOfOperand) { QualType ConvType = QualType::getFromOpaquePtr(Ty); QualType ConvTypeCanon = Context.getCanonicalType(ConvType); DeclarationName ConvName = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon); return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen, &SS, isAddressOfOperand); } /// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator /// name (e.g., @c operator+ ) as an expression. This is very /// similar to ActOnIdentifierExpr, except that instead of providing /// an identifier the parser provides the kind of overloaded /// operator that was parsed. Sema::OwningExprResult Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc, OverloadedOperatorKind Op, bool HasTrailingLParen, const CXXScopeSpec &SS, bool isAddressOfOperand) { DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op); return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS, isAddressOfOperand); } /// ActOnCXXTypeidOfType - Parse typeid( type-id ). Action::OwningExprResult Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc) { NamespaceDecl *StdNs = GetStdNamespace(); if (!StdNs) return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName); RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl); if (!TypeInfoRecordDecl) return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(), SourceRange(OpLoc, RParenLoc))); } /// ActOnCXXBoolLiteral - Parse {true,false} literals. Action::OwningExprResult Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { assert((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"); return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc)); } /// ActOnCXXThrow - Parse throw expressions. Action::OwningExprResult Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) { return Owned(new (Context) CXXThrowExpr((Expr*)E.release(), Context.VoidTy, OpLoc)); } Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { /// C++ 9.3.2: In the body of a non-static member function, the keyword this /// is a non-lvalue expression whose value is the address of the object for /// which the function is called. if (!isa<FunctionDecl>(CurContext)) return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) if (MD->isInstance()) return Owned(new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context))); return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); } /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). Action::OwningExprResult Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, SourceLocation LParenLoc, MultiExprArg exprs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { assert(TypeRep && "Missing type!"); QualType Ty = QualType::getFromOpaquePtr(TypeRep); unsigned NumExprs = exprs.size(); Expr **Exprs = (Expr**)exprs.get(); SourceLocation TyBeginLoc = TypeRange.getBegin(); SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { exprs.release(); return Owned(new (Context) CXXTemporaryObjectExpr(0, Ty, TyBeginLoc, Exprs, NumExprs, RParenLoc)); } // C++ [expr.type.conv]p1: // If the expression list is a single expression, the type conversion // expression is equivalent (in definedness, and if defined in meaning) to the // corresponding cast expression. // if (NumExprs == 1) { if (CheckCastTypes(TypeRange, Ty, Exprs[0])) return ExprError(); exprs.release(); return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc, Exprs[0], RParenLoc)); } if (const RecordType *RT = Ty->getAsRecordType()) { CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) { CXXConstructorDecl *Constructor = PerformInitializationByConstructor(Ty, Exprs, NumExprs, TypeRange.getBegin(), SourceRange(TypeRange.getBegin(), RParenLoc), DeclarationName(), IK_Direct); if (!Constructor) return ExprError(); exprs.release(); return Owned(new (Context) CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc, Exprs, NumExprs, RParenLoc)); } // Fall through to value-initialize an object of class type that // doesn't have a user-declared default constructor. } // C++ [expr.type.conv]p1: // If the expression list specifies more than a single value, the type shall // be a class with a suitably declared constructor. // if (NumExprs > 1) return ExprError(Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg) << FullRange); assert(NumExprs == 0 && "Expected 0 expressions"); // C++ [expr.type.conv]p2: // The expression T(), where T is a simple-type-specifier for a non-array // complete object type or the (possibly cv-qualified) void type, creates an // rvalue of the specified type, which is value-initialized. // if (Ty->isArrayType()) return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange); if (!Ty->isDependentType() && !Ty->isVoidType() && RequireCompleteType(TyBeginLoc, Ty, diag::err_invalid_incomplete_type_use, FullRange)) return ExprError(); if (RequireNonAbstractType(TyBeginLoc, Ty, diag::err_allocation_of_abstract_type)) return ExprError(); exprs.release(); return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc)); } /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: /// @code new (memory) int[size][4] @endcode /// or /// @code ::new Foo(23, "hello") @endcode /// For the interpretation of this heap of arguments, consult the base version. Action::OwningExprResult Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, bool ParenTypeId, Declarator &D, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { Expr *ArraySize = 0; unsigned Skip = 0; // If the specified type is an array, unwrap it and save the expression. if (D.getNumTypeObjects() > 0 && D.getTypeObject(0).Kind == DeclaratorChunk::Array) { DeclaratorChunk &Chunk = D.getTypeObject(0); if (Chunk.Arr.hasStatic) return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) << D.getSourceRange()); if (!Chunk.Arr.NumElts) return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) << D.getSourceRange()); ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); Skip = 1; } QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip); if (D.getInvalidType()) return ExprError(); if (CheckAllocatedType(AllocType, D)) return ExprError(); QualType ResultType = AllocType->isDependentType() ? Context.DependentTy : Context.getPointerType(AllocType); // That every array dimension except the first is constant was already // checked by the type check above. // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral // or enumeration type with a non-negative value." if (ArraySize && !ArraySize->isTypeDependent()) { QualType SizeType = ArraySize->getType(); if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) return ExprError(Diag(ArraySize->getSourceRange().getBegin(), diag::err_array_size_not_integral) << SizeType << ArraySize->getSourceRange()); // Let's see if this is a constant < 0. If so, we reject it out of hand. // We don't care about special rules, so we tell the machinery it's not // evaluated - it gives us a result in more cases. if (!ArraySize->isValueDependent()) { llvm::APSInt Value; if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { if (Value < llvm::APSInt( llvm::APInt::getNullValue(Value.getBitWidth()), false)) return ExprError(Diag(ArraySize->getSourceRange().getBegin(), diag::err_typecheck_negative_array_size) << ArraySize->getSourceRange()); } } } FunctionDecl *OperatorNew = 0; FunctionDecl *OperatorDelete = 0; Expr **PlaceArgs = (Expr**)PlacementArgs.get(); unsigned NumPlaceArgs = PlacementArgs.size(); if (!AllocType->isDependentType() && !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && FindAllocationFunctions(StartLoc, SourceRange(PlacementLParen, PlacementRParen), UseGlobal, AllocType, ArraySize, PlaceArgs, NumPlaceArgs, OperatorNew, OperatorDelete)) return ExprError(); bool Init = ConstructorLParen.isValid(); // --- Choosing a constructor --- // C++ 5.3.4p15 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid) // the object is not initialized. If the object, or any part of it, is // const-qualified, it's an error. // 2) If T is a POD and there's an empty initializer, the object is value- // initialized. // 3) If T is a POD and there's one initializer argument, the object is copy- // constructed. // 4) If T is a POD and there's more initializer arguments, it's an error. // 5) If T is not a POD, the initializer arguments are used as constructor // arguments. // // Or by the C++0x formulation: // 1) If there's no initializer, the object is default-initialized according // to C++0x rules. // 2) Otherwise, the object is direct-initialized. CXXConstructorDecl *Constructor = 0; Expr **ConsArgs = (Expr**)ConstructorArgs.get(); unsigned NumConsArgs = ConstructorArgs.size(); if (AllocType->isDependentType()) { // Skip all the checks. } // FIXME: Should check for primitive/aggregate here, not record. else if (const RecordType *RT = AllocType->getAsRecordType()) { // FIXME: This is incorrect for when there is an empty initializer and // no user-defined constructor. Must zero-initialize, not default-construct. Constructor = PerformInitializationByConstructor( AllocType, ConsArgs, NumConsArgs, D.getSourceRange().getBegin(), SourceRange(D.getSourceRange().getBegin(), ConstructorRParen), RT->getDecl()->getDeclName(), NumConsArgs != 0 ? IK_Direct : IK_Default); if (!Constructor) return ExprError(); } else { if (!Init) { // FIXME: Check that no subpart is const. if (AllocType.isConstQualified()) return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const) << D.getSourceRange()); } else if (NumConsArgs == 0) { // Object is value-initialized. Do nothing. } else if (NumConsArgs == 1) { // Object is direct-initialized. // FIXME: WHAT DeclarationName do we pass in here? if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc, DeclarationName() /*AllocType.getAsString()*/, /*DirectInit=*/true)) return ExprError(); } else { return ExprError(Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg) << SourceRange(ConstructorLParen, ConstructorRParen)); } } // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) PlacementArgs.release(); ConstructorArgs.release(); return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init, ConsArgs, NumConsArgs, OperatorDelete, ResultType, StartLoc, Init ? ConstructorRParen : SourceLocation())); } /// CheckAllocatedType - Checks that a type is suitable as the allocated type /// in a new-expression. /// dimension off and stores the size expression in ArraySize. bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D) { // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an // abstract class type or array thereof. if (AllocType->isFunctionType()) return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type) << AllocType << 0 << D.getSourceRange(); else if (AllocType->isReferenceType()) return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type) << AllocType << 1 << D.getSourceRange(); else if (!AllocType->isDependentType() && RequireCompleteType(D.getSourceRange().getBegin(), AllocType, diag::err_new_incomplete_type, D.getSourceRange())) return true; else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType, diag::err_allocation_of_abstract_type)) return true; // Every dimension shall be of constant size. unsigned i = 1; while (const ArrayType *Array = Context.getAsArrayType(AllocType)) { if (!Array->isConstantArrayType()) { Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst) << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange(); return true; } AllocType = Array->getElementType(); ++i; } return false; } /// FindAllocationFunctions - Finds the overloads of operator new and delete /// that are appropriate for the allocation. bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, bool UseGlobal, QualType AllocType, bool IsArray, Expr **PlaceArgs, unsigned NumPlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete) { // --- Choosing an allocation function --- // C++ 5.3.4p8 - 14 & 18 // 1) If UseGlobal is true, only look in the global scope. Else, also look // in the scope of the allocated class. // 2) If an array size is given, look for operator new[], else look for // operator new. // 3) The first argument is always size_t. Append the arguments from the // placement form. // FIXME: Also find the appropriate delete operator. llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); // We don't care about the actual value of this argument. // FIXME: Should the Sema create the expression and embed it in the syntax // tree? Or should the consumer just recalculate the value? AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue( Context.Target.getPointerWidth(0)), Context.getSizeType(), SourceLocation()); std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( IsArray ? OO_Array_New : OO_New); if (AllocType->isRecordType() && !UseGlobal) { CXXRecordDecl *Record = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl()); // FIXME: We fail to find inherited overloads. if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], AllocArgs.size(), Record, /*AllowMissing=*/true, OperatorNew)) return true; } if (!OperatorNew) { // Didn't find a member overload. Look for a global one. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], AllocArgs.size(), TUDecl, /*AllowMissing=*/false, OperatorNew)) return true; } // FIXME: This is leaked on error. But so much is currently in Sema that it's // easier to clean it in one go. AllocArgs[0]->Destroy(Context); return false; } /// FindAllocationOverload - Find an fitting overload for the allocation /// function in the specified scope. bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, DeclarationName Name, Expr** Args, unsigned NumArgs, DeclContext *Ctx, bool AllowMissing, FunctionDecl *&Operator) { DeclContext::lookup_iterator Alloc, AllocEnd; llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name); if (Alloc == AllocEnd) { if (AllowMissing) return false; return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) << Name << Range; } OverloadCandidateSet Candidates; for (; Alloc != AllocEnd; ++Alloc) { // Even member operator new/delete are implicitly treated as // static, so don't use AddMemberCandidate. if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) AddOverloadCandidate(Fn, Args, NumArgs, Candidates, /*SuppressUserConversions=*/false); } // Do the resolution. OverloadCandidateSet::iterator Best; switch(BestViableFunction(Candidates, Best)) { case OR_Success: { // Got one! FunctionDecl *FnDecl = Best->Function; // The first argument is size_t, and the first parameter must be size_t, // too. This is checked on declaration and can be assumed. (It can't be // asserted on, though, since invalid decls are left in there.) for (unsigned i = 1; i < NumArgs; ++i) { // FIXME: Passing word to diagnostic. if (PerformCopyInitialization(Args[i-1], FnDecl->getParamDecl(i)->getType(), "passing")) return true; } Operator = FnDecl; return false; } case OR_No_Viable_Function: if (AllowMissing) return false; Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) << Name << Range; PrintOverloadCandidates(Candidates, /*OnlyViable=*/false); return true; case OR_Ambiguous: Diag(StartLoc, diag::err_ovl_ambiguous_call) << Name << Range; PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); return true; case OR_Deleted: Diag(StartLoc, diag::err_ovl_deleted_call) << Best->Function->isDeleted() << Name << Range; PrintOverloadCandidates(Candidates, /*OnlyViable=*/true); return true; } assert(false && "Unreachable, bad result from BestViableFunction"); return true; } /// DeclareGlobalNewDelete - Declare the global forms of operator new and /// delete. These are: /// @code /// void* operator new(std::size_t) throw(std::bad_alloc); /// void* operator new[](std::size_t) throw(std::bad_alloc); /// void operator delete(void *) throw(); /// void operator delete[](void *) throw(); /// @endcode /// Note that the placement and nothrow forms of new are *not* implicitly /// declared. Their use requires including \<new\>. void Sema::DeclareGlobalNewDelete() { if (GlobalNewDeleteDeclared) return; GlobalNewDeleteDeclared = true; QualType VoidPtr = Context.getPointerType(Context.VoidTy); QualType SizeT = Context.getSizeType(); // FIXME: Exception specifications are not added. DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_New), VoidPtr, SizeT); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Array_New), VoidPtr, SizeT); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Delete), Context.VoidTy, VoidPtr); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), Context.VoidTy, VoidPtr); } /// DeclareGlobalAllocationFunction - Declares a single implicit global /// allocation function if it doesn't already exist. void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, QualType Argument) { DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); // Check if this function is already declared. { DeclContext::lookup_iterator Alloc, AllocEnd; for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name); Alloc != AllocEnd; ++Alloc) { // FIXME: Do we need to check for default arguments here? FunctionDecl *Func = cast<FunctionDecl>(*Alloc); if (Func->getNumParams() == 1 && Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument) return; } } QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0); FunctionDecl *Alloc = FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, FnType, FunctionDecl::None, false, true, SourceLocation()); Alloc->setImplicit(); ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 0, Argument, VarDecl::None, 0); Alloc->setParams(Context, &Param, 1); // FIXME: Also add this declaration to the IdentifierResolver, but // make sure it is at the end of the chain to coincide with the // global scope. ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc); } /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: /// @code ::delete ptr; @endcode /// or /// @code delete [] ptr; @endcode Action::OwningExprResult Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, ExprArg Operand) { // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type // having a single conversion function to a pointer type. The result has // type void." // DR599 amends "pointer type" to "pointer to object type" in both cases. Expr *Ex = (Expr *)Operand.get(); if (!Ex->isTypeDependent()) { QualType Type = Ex->getType(); if (Type->isRecordType()) { // FIXME: Find that one conversion function and amend the type. } if (!Type->isPointerType()) return ExprError(Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange()); QualType Pointee = Type->getAsPointerType()->getPointeeType(); if (Pointee->isFunctionType() || Pointee->isVoidType()) return ExprError(Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange()); else if (!Pointee->isDependentType() && RequireCompleteType(StartLoc, Pointee, diag::warn_delete_incomplete, Ex->getSourceRange())) return ExprError(); // FIXME: Look up the correct operator delete overload and pass a pointer // along. // FIXME: Check access and ambiguity of operator delete and destructor. } Operand.release(); return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex, StartLoc)); } /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a /// C++ if/switch/while/for statement. /// e.g: "if (int x = f()) {...}" Action::OwningExprResult Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, Declarator &D, SourceLocation EqualLoc, ExprArg AssignExprVal) { assert(AssignExprVal.get() && "Null assignment expression"); // C++ 6.4p2: // The declarator shall not specify a function or an array. // The type-specifier-seq shall not contain typedef and shall not declare a // new class or enumeration. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."); QualType Ty = GetTypeForDeclarator(D, S); if (Ty->isFunctionType()) { // The declarator shall not specify a function... // We exit without creating a CXXConditionDeclExpr because a FunctionDecl // would be created and CXXConditionDeclExpr wants a VarDecl. return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type) << SourceRange(StartLoc, EqualLoc)); } else if (Ty->isArrayType()) { // ...or an array. Diag(StartLoc, diag::err_invalid_use_of_array_type) << SourceRange(StartLoc, EqualLoc); } else if (const RecordType *RT = Ty->getAsRecordType()) { RecordDecl *RD = RT->getDecl(); // The type-specifier-seq shall not declare a new class... if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD)))) Diag(RD->getLocation(), diag::err_type_defined_in_condition); } else if (const EnumType *ET = Ty->getAsEnumType()) { EnumDecl *ED = ET->getDecl(); // ...or enumeration. if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED)))) Diag(ED->getLocation(), diag::err_type_defined_in_condition); } DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy()); if (!Dcl) return ExprError(); AddInitializerToDecl(Dcl, move(AssignExprVal)); // Mark this variable as one that is declared within a conditional. // We know that the decl had to be a VarDecl because that is the only type of // decl that can be assigned and the grammar requires an '='. VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); VD->setDeclaredInCondition(true); return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD)); } /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { // C++ 6.4p4: // The value of a condition that is an initialized declaration in a statement // other than a switch statement is the value of the declared variable // implicitly converted to type bool. If that conversion is ill-formed, the // program is ill-formed. // The value of a condition that is an expression is the value of the // expression, implicitly converted to bool. // return PerformContextuallyConvertToBool(CondExpr); } /// Helper function to determine whether this is the (deprecated) C++ /// conversion from a string literal to a pointer to non-const char or /// non-const wchar_t (for narrow and wide string literals, /// respectively). bool Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { // Look inside the implicit cast, if it exists. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) From = Cast->getSubExpr(); // A string literal (2.13.4) that is not a wide string literal can // be converted to an rvalue of type "pointer to char"; a wide // string literal can be converted to an rvalue of type "pointer // to wchar_t" (C++ 4.2p2). if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) if (const PointerType *ToPtrType = ToType->getAsPointerType()) if (const BuiltinType *ToPointeeType = ToPtrType->getPointeeType()->getAsBuiltinType()) { // This conversion is considered only when there is an // explicit appropriate pointer target type (C++ 4.2p2). if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 && ((StrLit->isWide() && ToPointeeType->isWideCharType()) || (!StrLit->isWide() && (ToPointeeType->getKind() == BuiltinType::Char_U || ToPointeeType->getKind() == BuiltinType::Char_S)))) return true; } return false; } /// PerformImplicitConversion - Perform an implicit conversion of the /// expression From to the type ToType. Returns true if there was an /// error, false otherwise. The expression From is replaced with the /// converted expression. Flavor is the kind of conversion we're /// performing, used in the error message. If @p AllowExplicit, /// explicit user-defined conversions are permitted. @p Elidable should be true /// when called for copies which may be elided (C++ 12.8p15). C++0x overload /// resolution works differently in that case. bool Sema::PerformImplicitConversion(Expr *&From, QualType ToType, const char *Flavor, bool AllowExplicit, bool Elidable) { ImplicitConversionSequence ICS; ICS.ConversionKind = ImplicitConversionSequence::BadConversion; if (Elidable && getLangOptions().CPlusPlus0x) { ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false, AllowExplicit, /*ForceRValue*/true); } if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { ICS = TryImplicitConversion(From, ToType, false, AllowExplicit); } return PerformImplicitConversion(From, ToType, ICS, Flavor); } /// PerformImplicitConversion - Perform an implicit conversion of the /// expression From to the type ToType using the pre-computed implicit /// conversion sequence ICS. Returns true if there was an error, false /// otherwise. The expression From is replaced with the converted /// expression. Flavor is the kind of conversion we're performing, /// used in the error message. bool Sema::PerformImplicitConversion(Expr *&From, QualType ToType, const ImplicitConversionSequence &ICS, const char* Flavor) { switch (ICS.ConversionKind) { case ImplicitConversionSequence::StandardConversion: if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor)) return true; break; case ImplicitConversionSequence::UserDefinedConversion: // FIXME: This is, of course, wrong. We'll need to actually call // the constructor or conversion operator, and then cope with the // standard conversions. ImpCastExprToType(From, ToType.getNonReferenceType(), ToType->isLValueReferenceType()); return false; case ImplicitConversionSequence::EllipsisConversion: assert(false && "Cannot perform an ellipsis conversion"); return false; case ImplicitConversionSequence::BadConversion: return true; } // Everything went well. return false; } /// PerformImplicitConversion - Perform an implicit conversion of the /// expression From to the type ToType by following the standard /// conversion sequence SCS. Returns true if there was an error, false /// otherwise. The expression From is replaced with the converted /// expression. Flavor is the context in which we're performing this /// conversion, for use in error messages. bool Sema::PerformImplicitConversion(Expr *&From, QualType ToType, const StandardConversionSequence& SCS, const char *Flavor) { // Overall FIXME: we are recomputing too many types here and doing // far too much extra work. What this means is that we need to keep // track of more information that is computed when we try the // implicit conversion initially, so that we don't need to recompute // anything here. QualType FromType = From->getType(); if (SCS.CopyConstructor) { // FIXME: Create a temporary object by calling the copy // constructor. ImpCastExprToType(From, ToType.getNonReferenceType(), ToType->isLValueReferenceType()); return false; } // Perform the first implicit conversion. switch (SCS.First) { case ICK_Identity: case ICK_Lvalue_To_Rvalue: // Nothing to do. break; case ICK_Array_To_Pointer: FromType = Context.getArrayDecayedType(FromType); ImpCastExprToType(From, FromType); break; case ICK_Function_To_Pointer: if (Context.getCanonicalType(FromType) == Context.OverloadTy) { FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); if (!Fn) return true; if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) return true; FixOverloadedFunctionReference(From, Fn); FromType = From->getType(); } FromType = Context.getPointerType(FromType); ImpCastExprToType(From, FromType); break; default: assert(false && "Improper first standard conversion"); break; } // Perform the second implicit conversion switch (SCS.Second) { case ICK_Identity: // Nothing to do. break; case ICK_Integral_Promotion: case ICK_Floating_Promotion: case ICK_Complex_Promotion: case ICK_Integral_Conversion: case ICK_Floating_Conversion: case ICK_Complex_Conversion: case ICK_Floating_Integral: case ICK_Complex_Real: case ICK_Compatible_Conversion: // FIXME: Go deeper to get the unqualified type! FromType = ToType.getUnqualifiedType(); ImpCastExprToType(From, FromType); break; case ICK_Pointer_Conversion: if (SCS.IncompatibleObjC) { // Diagnose incompatible Objective-C conversions Diag(From->getSourceRange().getBegin(), diag::ext_typecheck_convert_incompatible_pointer) << From->getType() << ToType << Flavor << From->getSourceRange(); } if (CheckPointerConversion(From, ToType)) return true; ImpCastExprToType(From, ToType); break; case ICK_Pointer_Member: if (CheckMemberPointerConversion(From, ToType)) return true; ImpCastExprToType(From, ToType); break; case ICK_Boolean_Conversion: FromType = Context.BoolTy; ImpCastExprToType(From, FromType); break; default: assert(false && "Improper second standard conversion"); break; } switch (SCS.Third) { case ICK_Identity: // Nothing to do. break; case ICK_Qualification: // FIXME: Not sure about lvalue vs rvalue here in the presence of // rvalue references. ImpCastExprToType(From, ToType.getNonReferenceType(), ToType->isLValueReferenceType()); break; default: assert(false && "Improper second standard conversion"); break; } return false; } Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, SourceLocation KWLoc, SourceLocation LParen, TypeTy *Ty, SourceLocation RParen) { // FIXME: Some of the type traits have requirements. Interestingly, only the // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, // G++ accepts __is_pod(Incomplete) without complaints, and claims that the // type is indeed a POD. // There is no point in eagerly computing the value. The traits are designed // to be used from type trait templates, so Ty will be a template parameter // 99% of the time. return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, QualType::getFromOpaquePtr(Ty), RParen, Context.BoolTy)); } QualType Sema::CheckPointerToMemberOperands( Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { const char *OpSpelling = isIndirect ? "->*" : ".*"; // C++ 5.5p2 // The binary operator .* [p3: ->*] binds its second operand, which shall // be of type "pointer to member of T" (where T is a completely-defined // class type) [...] QualType RType = rex->getType(); const MemberPointerType *MemPtr = RType->getAsMemberPointerType(); if (!MemPtr) { Diag(Loc, diag::err_bad_memptr_rhs) << OpSpelling << RType << rex->getSourceRange(); return QualType(); } else if (RequireCompleteType(Loc, QualType(MemPtr->getClass(), 0), diag::err_memptr_rhs_incomplete, rex->getSourceRange())) return QualType(); QualType Class(MemPtr->getClass(), 0); // C++ 5.5p2 // [...] to its first operand, which shall be of class T or of a class of // which T is an unambiguous and accessible base class. [p3: a pointer to // such a class] QualType LType = lex->getType(); if (isIndirect) { if (const PointerType *Ptr = LType->getAsPointerType()) LType = Ptr->getPointeeType().getNonReferenceType(); else { Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling << 1 << LType << lex->getSourceRange(); return QualType(); } } if (Context.getCanonicalType(Class).getUnqualifiedType() != Context.getCanonicalType(LType).getUnqualifiedType()) { BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, /*DetectVirtual=*/false); // FIXME: Would it be useful to print full ambiguity paths, // or is that overkill? if (!IsDerivedFrom(LType, Class, Paths) || Paths.isAmbiguous(Context.getCanonicalType(Class))) { Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling << (int)isIndirect << lex->getType() << lex->getSourceRange(); return QualType(); } } // C++ 5.5p2 // The result is an object or a function of the type specified by the // second operand. // The cv qualifiers are the union of those in the pointer and the left side, // in accordance with 5.5p5 and 5.2.5. // FIXME: This returns a dereferenced member function pointer as a normal // function type. However, the only operation valid on such functions is // calling them. There's also a GCC extension to get a function pointer to // the thing, which is another complication, because this type - unlike the // type that is the result of this expression - takes the class as the first // argument. // We probably need a "MemberFunctionClosureType" or something like that. QualType Result = MemPtr->getPointeeType(); if (LType.isConstQualified()) Result.addConst(); if (LType.isVolatileQualified()) Result.addVolatile(); return Result; } <file_sep>/test/Sema/cast.c // RUN: clang-cc -fsyntax-only %s -verify typedef struct { unsigned long bits[(((1) + (64) - 1) / (64))]; } cpumask_t; cpumask_t x; void foo() { (void)x; } <file_sep>/test/CodeGen/PR2001-bitfield-reload.c // RUN: clang-cc -triple i386-unknown-unknown --emit-llvm-bc -o - %s | opt --std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32" %t | count 1 && // RUN: grep "ret i32 1" %t | count 1 // PR2001 /* Test that the result of the assignment properly uses the value *in the bitfield* as opposed to the RHS. */ static int foo(int i) { struct { int f0 : 2; } x; return (x.f0 = i); } int bar() { return foo(-5) == -1; } <file_sep>/test/Coverage/parse-callbacks.c // RUN: clang-cc --parse-noop %s && // RUN: clang-cc --parse-print-callbacks %s #include "c-language-features.inc" <file_sep>/test/Driver/hello.c // RUN: clang -ccc-echo -o %t %s 2> %t.log && // Make sure we used clang. // RUN: grep 'clang-cc" .*hello.c' %t.log && // RUN: %t > %t.out && // RUN: grep "I'm a little driver, short and stout." %t.out #include <stdio.h> int main() { printf("I'm a little driver, short and stout."); return 0; } <file_sep>/lib/CodeGen/CGExpr.cpp //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This contains code to emit Expr nodes as LLVM code. // //===----------------------------------------------------------------------===// #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "CGCall.h" #include "CGObjCRuntime.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "llvm/Target/TargetData.h" using namespace clang; using namespace CodeGen; //===--------------------------------------------------------------------===// // Miscellaneous Helper Methods //===--------------------------------------------------------------------===// /// CreateTempAlloca - This creates a alloca and inserts it into the entry /// block. llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty, const char *Name) { if (!Builder.isNamePreserving()) Name = ""; return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); } /// EvaluateExprAsBool - Perform the usual unary conversions on the specified /// expression and compare the result against zero, returning an Int1Ty value. llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { QualType BoolTy = getContext().BoolTy; if (!E->getType()->isAnyComplexType()) return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); } /// EmitAnyExpr - Emit code to compute the specified expression which can have /// any type. The result is returned as an RValue struct. If this is an /// aggregate expression, the aggloc/agglocvolatile arguments indicate where /// the result should be returned. RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc, bool isAggLocVolatile) { if (!hasAggregateLLVMType(E->getType())) return RValue::get(EmitScalarExpr(E)); else if (E->getType()->isAnyComplexType()) return RValue::getComplex(EmitComplexExpr(E)); EmitAggExpr(E, AggLoc, isAggLocVolatile); return RValue::getAggregate(AggLoc); } /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result /// will always be accessible even if no aggregate location is /// provided. RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc, bool isAggLocVolatile) { if (!AggLoc && hasAggregateLLVMType(E->getType()) && !E->getType()->isAnyComplexType()) AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp"); return EmitAnyExpr(E, AggLoc, isAggLocVolatile); } /// getAccessedFieldNo - Given an encoded value and a result number, return /// the input field number being accessed. unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts) { if (isa<llvm::ConstantAggregateZero>(Elts)) return 0; return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue(); } //===----------------------------------------------------------------------===// // LValue Expression Emission //===----------------------------------------------------------------------===// RValue CodeGenFunction::GetUndefRValue(QualType Ty) { if (Ty->isVoidType()) { return RValue::get(0); } else if (const ComplexType *CTy = Ty->getAsComplexType()) { const llvm::Type *EltTy = ConvertType(CTy->getElementType()); llvm::Value *U = llvm::UndefValue::get(EltTy); return RValue::getComplex(std::make_pair(U, U)); } else if (hasAggregateLLVMType(Ty)) { const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty)); return RValue::getAggregate(llvm::UndefValue::get(LTy)); } else { return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); } } RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, const char *Name) { ErrorUnsupported(E, Name); return GetUndefRValue(E->getType()); } LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, const char *Name) { ErrorUnsupported(E, Name); llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); return LValue::MakeAddr(llvm::UndefValue::get(Ty), E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } /// EmitLValue - Emit code to compute a designator that specifies the location /// of the expression. /// /// This can return one of two things: a simple address or a bitfield /// reference. In either case, the LLVM Value* in the LValue structure is /// guaranteed to be an LLVM pointer type. /// /// If this returns a bitfield reference, nothing about the pointee type of /// the LLVM value is known: For example, it may not be a pointer to an /// integer. /// /// If this returns a normal address, and if the lvalue's C type is fixed /// size, this method guarantees that the returned pointer type will point to /// an LLVM type of the same size of the lvalue's type. If the lvalue has a /// variable length type, this is not possible. /// LValue CodeGenFunction::EmitLValue(const Expr *E) { switch (E->getStmtClass()) { default: return EmitUnsupportedLValue(E, "l-value expression"); case Expr::BinaryOperatorClass: return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); case Expr::CallExprClass: case Expr::CXXOperatorCallExprClass: return EmitCallExprLValue(cast<CallExpr>(E)); case Expr::VAArgExprClass: return EmitVAArgExprLValue(cast<VAArgExpr>(E)); case Expr::DeclRefExprClass: case Expr::QualifiedDeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E)); case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); case Expr::PredefinedExprClass: return EmitPredefinedLValue(cast<PredefinedExpr>(E)); case Expr::StringLiteralClass: return EmitStringLiteralLValue(cast<StringLiteral>(E)); case Expr::ObjCEncodeExprClass: return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); case Expr::BlockDeclRefExprClass: return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E)); case Expr::CXXConditionDeclExprClass: return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E)); case Expr::ObjCMessageExprClass: return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); case Expr::ObjCIvarRefExprClass: return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); case Expr::ObjCPropertyRefExprClass: return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E)); case Expr::ObjCKVCRefExprClass: return EmitObjCKVCRefLValue(cast<ObjCKVCRefExpr>(E)); case Expr::ObjCSuperExprClass: return EmitObjCSuperExpr(cast<ObjCSuperExpr>(E)); case Expr::UnaryOperatorClass: return EmitUnaryOpLValue(cast<UnaryOperator>(E)); case Expr::ArraySubscriptExprClass: return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); case Expr::ExtVectorElementExprClass: return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E)); case Expr::CompoundLiteralExprClass: return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); case Expr::ConditionalOperatorClass: return EmitConditionalOperator(cast<ConditionalOperator>(E)); case Expr::ChooseExprClass: return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext())); case Expr::ImplicitCastExprClass: case Expr::CStyleCastExprClass: case Expr::CXXFunctionalCastExprClass: case Expr::CXXStaticCastExprClass: case Expr::CXXDynamicCastExprClass: case Expr::CXXReinterpretCastExprClass: case Expr::CXXConstCastExprClass: return EmitCastLValue(cast<CastExpr>(E)); } } llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, QualType Ty) { llvm::Value *V = Builder.CreateLoad(Addr, Volatile, "tmp"); // Bool can have different representation in memory than in // registers. if (Ty->isBooleanType()) if (V->getType() != llvm::Type::Int1Ty) V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool"); return V; } void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, bool Volatile) { // Handle stores of types which have different representations in // memory and as LLVM values. // FIXME: We shouldn't be this loose, we should only do this // conversion when we have a type we know has a different memory // representation (e.g., bool). const llvm::Type *SrcTy = Value->getType(); const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType()); if (DstPtr->getElementType() != SrcTy) { const llvm::Type *MemTy = llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace()); Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp"); } Builder.CreateStore(Value, Addr, Volatile); } /// EmitLoadOfLValue - Given an expression that represents a value lvalue, /// this method emits the address of the lvalue, then loads the result as an /// rvalue, returning the rvalue. RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) { if (LV.isObjCWeak()) { // load of a __weak object. llvm::Value *AddrWeakObj = LV.getAddress(); llvm::Value *read_weak = CGM.getObjCRuntime().EmitObjCWeakRead(*this, AddrWeakObj); return RValue::get(read_weak); } if (LV.isSimple()) { llvm::Value *Ptr = LV.getAddress(); const llvm::Type *EltTy = cast<llvm::PointerType>(Ptr->getType())->getElementType(); // Simple scalar l-value. if (EltTy->isSingleValueType()) return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(), ExprType)); assert(ExprType->isFunctionType() && "Unknown scalar value"); return RValue::get(Ptr); } if (LV.isVectorElt()) { llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), LV.isVolatileQualified(), "tmp"); return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(), "vecext")); } // If this is a reference to a subset of the elements of a vector, either // shuffle the input or extract/insert them as appropriate. if (LV.isExtVectorElt()) return EmitLoadOfExtVectorElementLValue(LV, ExprType); if (LV.isBitfield()) return EmitLoadOfBitfieldLValue(LV, ExprType); if (LV.isPropertyRef()) return EmitLoadOfPropertyRefLValue(LV, ExprType); assert(LV.isKVCRef() && "Unknown LValue type!"); return EmitLoadOfKVCRefLValue(LV, ExprType); } RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType) { unsigned StartBit = LV.getBitfieldStartBit(); unsigned BitfieldSize = LV.getBitfieldSize(); llvm::Value *Ptr = LV.getBitfieldAddr(); const llvm::Type *EltTy = cast<llvm::PointerType>(Ptr->getType())->getElementType(); unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy); // In some cases the bitfield may straddle two memory locations. // Currently we load the entire bitfield, then do the magic to // sign-extend it if necessary. This results in somewhat more code // than necessary for the common case (one load), since two shifts // accomplish both the masking and sign extension. unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit); llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp"); // Shift to proper location. if (StartBit) Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit), "bf.lo"); // Mask off unused bits. llvm::Constant *LowMask = llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, LowBits)); Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared"); // Fetch the high bits if necessary. if (LowBits < BitfieldSize) { unsigned HighBits = BitfieldSize - LowBits; llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get(llvm::Type::Int32Ty, 1), "bf.ptr.hi"); llvm::Value *HighVal = Builder.CreateLoad(HighPtr, LV.isVolatileQualified(), "tmp"); // Mask off unused bits. llvm::Constant *HighMask = llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, HighBits)); HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared"); // Shift to proper location and or in to bitfield value. HighVal = Builder.CreateShl(HighVal, llvm::ConstantInt::get(EltTy, LowBits)); Val = Builder.CreateOr(Val, HighVal, "bf.val"); } // Sign extend if necessary. if (LV.isBitfieldSigned()) { llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy, EltTySize - BitfieldSize); Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits), ExtraBits, "bf.val.sext"); } // The bitfield type and the normal type differ when the storage sizes // differ (currently just _Bool). Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp"); return RValue::get(Val); } RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType) { return EmitObjCPropertyGet(LV.getPropertyRefExpr()); } RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType) { return EmitObjCPropertyGet(LV.getKVCRefExpr()); } // If this is a reference to a subset of the elements of a vector, create an // appropriate shufflevector. RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV, QualType ExprType) { llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), LV.isVolatileQualified(), "tmp"); const llvm::Constant *Elts = LV.getExtVectorElts(); // If the result of the expression is a non-vector type, we must be // extracting a single element. Just codegen as an extractelement. const VectorType *ExprVT = ExprType->getAsVectorType(); if (!ExprVT) { unsigned InIdx = getAccessedFieldNo(0, Elts); llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx); return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp")); } // Always use shuffle vector to try to retain the original program structure unsigned NumResultElts = ExprVT->getNumElements(); llvm::SmallVector<llvm::Constant*, 4> Mask; for (unsigned i = 0; i != NumResultElts; ++i) { unsigned InIdx = getAccessedFieldNo(i, Elts); Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx)); } llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), MaskV, "tmp"); return RValue::get(Vec); } /// EmitStoreThroughLValue - Store the specified rvalue into the specified /// lvalue, where both are guaranteed to the have the same type, and that type /// is 'Ty'. void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty) { if (!Dst.isSimple()) { if (Dst.isVectorElt()) { // Read/modify/write the vector, inserting the new element. llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), Dst.isVolatileQualified(), "tmp"); Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), Dst.getVectorIdx(), "vecins"); Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified()); return; } // If this is an update of extended vector elements, insert them as // appropriate. if (Dst.isExtVectorElt()) return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty); if (Dst.isBitfield()) return EmitStoreThroughBitfieldLValue(Src, Dst, Ty); if (Dst.isPropertyRef()) return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty); if (Dst.isKVCRef()) return EmitStoreThroughKVCRefLValue(Src, Dst, Ty); assert(0 && "Unknown LValue type"); } if (Dst.isObjCWeak() && !Dst.isNonGC()) { // load of a __weak object. llvm::Value *LvalueDst = Dst.getAddress(); llvm::Value *src = Src.getScalarVal(); CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); return; } if (Dst.isObjCStrong() && !Dst.isNonGC()) { // load of a __strong object. llvm::Value *LvalueDst = Dst.getAddress(); llvm::Value *src = Src.getScalarVal(); #if 0 // FIXME. We cannot positively determine if we have an // 'ivar' assignment, object assignment or an unknown // assignment. For now, generate call to objc_assign_strongCast // assignment which is a safe, but consevative assumption. if (Dst.isObjCIvar()) CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, LvalueDst); else CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst); #endif CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); return; } assert(Src.isScalar() && "Can't emit an agg store with this method"); EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(), Dst.isVolatileQualified()); } void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty, llvm::Value **Result) { unsigned StartBit = Dst.getBitfieldStartBit(); unsigned BitfieldSize = Dst.getBitfieldSize(); llvm::Value *Ptr = Dst.getBitfieldAddr(); const llvm::Type *EltTy = cast<llvm::PointerType>(Ptr->getType())->getElementType(); unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy); // Get the new value, cast to the appropriate type and masked to // exactly the size of the bit-field. llvm::Value *SrcVal = Src.getScalarVal(); llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp"); llvm::Constant *Mask = llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize)); NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value"); // Return the new value of the bit-field, if requested. if (Result) { // Cast back to the proper type for result. const llvm::Type *SrcTy = SrcVal->getType(); llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false, "bf.reload.val"); // Sign extend if necessary. if (Dst.isBitfieldSigned()) { unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy); llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy, SrcTySize - BitfieldSize); SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits), ExtraBits, "bf.reload.sext"); } *Result = SrcTrunc; } // In some cases the bitfield may straddle two memory locations. // Emit the low part first and check to see if the high needs to be // done. unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit); llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.prev.low"); // Compute the mask for zero-ing the low part of this bitfield. llvm::Constant *InvMask = llvm::ConstantInt::get(~llvm::APInt::getBitsSet(EltTySize, StartBit, StartBit + LowBits)); // Compute the new low part as // LowVal = (LowVal & InvMask) | (NewVal << StartBit), // with the shift of NewVal implicitly stripping the high bits. llvm::Value *NewLowVal = Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit), "bf.value.lo"); LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared"); LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo"); // Write back. Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified()); // If the low part doesn't cover the bitfield emit a high part. if (LowBits < BitfieldSize) { unsigned HighBits = BitfieldSize - LowBits; llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get(llvm::Type::Int32Ty, 1), "bf.ptr.hi"); llvm::Value *HighVal = Builder.CreateLoad(HighPtr, Dst.isVolatileQualified(), "bf.prev.hi"); // Compute the mask for zero-ing the high part of this bitfield. llvm::Constant *InvMask = llvm::ConstantInt::get(~llvm::APInt::getLowBitsSet(EltTySize, HighBits)); // Compute the new high part as // HighVal = (HighVal & InvMask) | (NewVal lshr LowBits), // where the high bits of NewVal have already been cleared and the // shift stripping the low bits. llvm::Value *NewHighVal = Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits), "bf.value.high"); HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared"); HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi"); // Write back. Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified()); } } void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty) { EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src); } void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty) { EmitObjCPropertySet(Dst.getKVCRefExpr(), Src); } void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst, QualType Ty) { // This access turns into a read/modify/write of the vector. Load the input // value now. llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), Dst.isVolatileQualified(), "tmp"); const llvm::Constant *Elts = Dst.getExtVectorElts(); llvm::Value *SrcVal = Src.getScalarVal(); if (const VectorType *VTy = Ty->getAsVectorType()) { unsigned NumSrcElts = VTy->getNumElements(); unsigned NumDstElts = cast<llvm::VectorType>(Vec->getType())->getNumElements(); if (NumDstElts == NumSrcElts) { // Use shuffle vector is the src and destination are the same number // of elements llvm::SmallVector<llvm::Constant*, 4> Mask; for (unsigned i = 0; i != NumSrcElts; ++i) { unsigned InIdx = getAccessedFieldNo(i, Elts); Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx)); } llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); Vec = Builder.CreateShuffleVector(SrcVal, llvm::UndefValue::get(Vec->getType()), MaskV, "tmp"); } else if (NumDstElts > NumSrcElts) { // Extended the source vector to the same length and then shuffle it // into the destination. // FIXME: since we're shuffling with undef, can we just use the indices // into that? This could be simpler. llvm::SmallVector<llvm::Constant*, 4> ExtMask; unsigned i; for (i = 0; i != NumSrcElts; ++i) ExtMask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, i)); for (; i != NumDstElts; ++i) ExtMask.push_back(llvm::UndefValue::get(llvm::Type::Int32Ty)); llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0], ExtMask.size()); llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, llvm::UndefValue::get(SrcVal->getType()), ExtMaskV, "tmp"); // build identity llvm::SmallVector<llvm::Constant*, 4> Mask; for (unsigned i = 0; i != NumDstElts; ++i) { Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, i)); } // modify when what gets shuffled in for (unsigned i = 0; i != NumSrcElts; ++i) { unsigned Idx = getAccessedFieldNo(i, Elts); Mask[Idx] =llvm::ConstantInt::get(llvm::Type::Int32Ty, i+NumDstElts); } llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp"); } else { // We should never shorten the vector assert(0 && "unexpected shorten vector length"); } } else { // If the Src is a scalar (not a vector) it must be updating one element. unsigned InIdx = getAccessedFieldNo(0, Elts); llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx); Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp"); } Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified()); } LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) || isa<ImplicitParamDecl>(VD))) { LValue LV; bool GCable = VD->hasLocalStorage() && !VD->hasAttr<BlocksAttr>(); if (VD->hasExternalStorage()) { LV = LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD), E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } else { llvm::Value *V = LocalDeclMap[VD]; assert(V && "DeclRefExpr not entered in LocalDeclMap?"); // local variables do not get their gc attribute set. QualType::GCAttrTypes attr = QualType::GCNone; // local static? if (!GCable) attr = getContext().getObjCGCAttrKind(E->getType()); if (VD->hasAttr<BlocksAttr>()) { bool needsCopyDispose = BlockRequiresCopying(VD->getType()); const llvm::Type *PtrStructTy = V->getType(); const llvm::Type *Ty = PtrStructTy; Ty = llvm::PointerType::get(Ty, 0); V = Builder.CreateStructGEP(V, 1, "forwarding"); V = Builder.CreateBitCast(V, Ty); V = Builder.CreateLoad(V, false); V = Builder.CreateBitCast(V, PtrStructTy); V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x"); } LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), attr); } LValue::SetObjCNonGC(LV, GCable); return LV; } else if (VD && VD->isFileVarDecl()) { LValue LV = LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD), E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); return LV; } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) { return LValue::MakeAddr(CGM.GetAddrOfFunction(FD), E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } else if (const ImplicitParamDecl *IPD = dyn_cast<ImplicitParamDecl>(E->getDecl())) { llvm::Value *V = LocalDeclMap[IPD]; assert(V && "BlockVarDecl not entered in LocalDeclMap?"); return LValue::MakeAddr(V, E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } assert(0 && "Unimp declref"); //an invalid LValue, but the assert will //ensure that this point is never reached. return LValue(); } LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) { return LValue::MakeAddr(GetAddrOfBlockDecl(E), 0); } LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { // __extension__ doesn't affect lvalue-ness. if (E->getOpcode() == UnaryOperator::Extension) return EmitLValue(E->getSubExpr()); QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); switch (E->getOpcode()) { default: assert(0 && "Unknown unary operator lvalue!"); case UnaryOperator::Deref: { QualType T = E->getSubExpr()->getType()->getAsPointerType()->getPointeeType(); LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()), ExprTy->getAsPointerType()->getPointeeType() .getCVRQualifiers(), getContext().getObjCGCAttrKind(T)); // We should not generate __weak write barrier on indirect reference // of a pointer to object; as in void foo (__weak id *param); *param = 0; // But, we continue to generate __strong write barrier on indirect write // into a pointer to object. if (getContext().getLangOptions().ObjC1 && getContext().getLangOptions().getGCMode() != LangOptions::NonGC && LV.isObjCWeak()) LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate()); return LV; } case UnaryOperator::Real: case UnaryOperator::Imag: LValue LV = EmitLValue(E->getSubExpr()); unsigned Idx = E->getOpcode() == UnaryOperator::Imag; return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(), Idx, "idx"), ExprTy.getCVRQualifiers()); } } LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0); } LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E), 0); } LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) { std::string GlobalVarName; switch (Type) { default: assert(0 && "Invalid type"); case PredefinedExpr::Func: GlobalVarName = "__func__."; break; case PredefinedExpr::Function: GlobalVarName = "__FUNCTION__."; break; case PredefinedExpr::PrettyFunction: // FIXME:: Demangle C++ method names GlobalVarName = "__PRETTY_FUNCTION__."; break; } std::string FunctionName; if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) { FunctionName = CGM.getMangledName(FD); } else { // Just get the mangled name; skipping the asm prefix if it // exists. FunctionName = CurFn->getName(); if (FunctionName[0] == '\01') FunctionName = FunctionName.substr(1, std::string::npos); } GlobalVarName += FunctionName; llvm::Constant *C = CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str()); return LValue::MakeAddr(C, 0); } LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { switch (E->getIdentType()) { default: return EmitUnsupportedLValue(E, "predefined expression"); case PredefinedExpr::Func: case PredefinedExpr::Function: case PredefinedExpr::PrettyFunction: return EmitPredefinedFunctionName(E->getIdentType()); } } LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { // The index must always be an integer, which is not an aggregate. Emit it. llvm::Value *Idx = EmitScalarExpr(E->getIdx()); // If the base is a vector type, then we are forming a vector element lvalue // with this subscript. if (E->getBase()->getType()->isVectorType()) { // Emit the vector as an lvalue to get its address. LValue LHS = EmitLValue(E->getBase()); assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); // FIXME: This should properly sign/zero/extend or truncate Idx to i32. return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType().getCVRQualifiers()); } // The base must be a pointer, which is not an aggregate. Emit it. llvm::Value *Base = EmitScalarExpr(E->getBase()); // Extend or truncate the index type to 32 or 64-bits. QualType IdxTy = E->getIdx()->getType(); bool IdxSigned = IdxTy->isSignedIntegerType(); unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); // If Pointer width is less than 32 than extend to 32. unsigned IdxValidWidth = (LLVMPointerWidth < 32 ) ? 32 : LLVMPointerWidth; if (IdxBitwidth != IdxValidWidth) Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(IdxValidWidth), IdxSigned, "idxprom"); // We know that the pointer points to a type of the correct size, unless the // size is a VLA. if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(E->getType())) { llvm::Value *VLASize = VLASizeMap[VAT]; Idx = Builder.CreateMul(Idx, VLASize); QualType BaseType = getContext().getBaseElementType(VAT); uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8; Idx = Builder.CreateUDiv(Idx, llvm::ConstantInt::get(Idx->getType(), BaseTypeSize)); } QualType T = E->getBase()->getType(); QualType ExprTy = getContext().getCanonicalType(T); T = T->getAsPointerType()->getPointeeType(); LValue LV = LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"), ExprTy->getAsPointerType()->getPointeeType().getCVRQualifiers(), getContext().getObjCGCAttrKind(T)); if (getContext().getLangOptions().ObjC1 && getContext().getLangOptions().getGCMode() != LangOptions::NonGC) LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate()); return LV; } static llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) { llvm::SmallVector<llvm::Constant *, 4> CElts; for (unsigned i = 0, e = Elts.size(); i != e; ++i) CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i])); return llvm::ConstantVector::get(&CElts[0], CElts.size()); } LValue CodeGenFunction:: EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { // Emit the base vector as an l-value. LValue Base; // ExtVectorElementExpr's base can either be a vector or pointer to vector. if (!E->isArrow()) { assert(E->getBase()->getType()->isVectorType()); Base = EmitLValue(E->getBase()); } else { const PointerType *PT = E->getBase()->getType()->getAsPointerType(); llvm::Value *Ptr = EmitScalarExpr(E->getBase()); Base = LValue::MakeAddr(Ptr, PT->getPointeeType().getCVRQualifiers()); } // Encode the element access list into a vector of unsigned indices. llvm::SmallVector<unsigned, 4> Indices; E->getEncodedElementAccess(Indices); if (Base.isSimple()) { llvm::Constant *CV = GenerateConstantVector(Indices); return LValue::MakeExtVectorElt(Base.getAddress(), CV, Base.getQualifiers()); } assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); llvm::Constant *BaseElts = Base.getExtVectorElts(); llvm::SmallVector<llvm::Constant *, 4> CElts; for (unsigned i = 0, e = Indices.size(); i != e; ++i) { if (isa<llvm::ConstantAggregateZero>(BaseElts)) CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); else CElts.push_back(BaseElts->getOperand(Indices[i])); } llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size()); return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, Base.getQualifiers()); } LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { bool isUnion = false; bool isIvar = false; bool isNonGC = false; Expr *BaseExpr = E->getBase(); llvm::Value *BaseValue = NULL; unsigned CVRQualifiers=0; // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. if (E->isArrow()) { BaseValue = EmitScalarExpr(BaseExpr); const PointerType *PTy = cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType())); if (PTy->getPointeeType()->isUnionType()) isUnion = true; CVRQualifiers = PTy->getPointeeType().getCVRQualifiers(); } else if (isa<ObjCPropertyRefExpr>(BaseExpr) || isa<ObjCKVCRefExpr>(BaseExpr)) { RValue RV = EmitObjCPropertyGet(BaseExpr); BaseValue = RV.getAggregateAddr(); if (BaseExpr->getType()->isUnionType()) isUnion = true; CVRQualifiers = BaseExpr->getType().getCVRQualifiers(); } else { LValue BaseLV = EmitLValue(BaseExpr); if (BaseLV.isObjCIvar()) isIvar = true; if (BaseLV.isNonGC()) isNonGC = true; // FIXME: this isn't right for bitfields. BaseValue = BaseLV.getAddress(); if (BaseExpr->getType()->isUnionType()) isUnion = true; CVRQualifiers = BaseExpr->getType().getCVRQualifiers(); } FieldDecl *Field = dyn_cast<FieldDecl>(E->getMemberDecl()); // FIXME: Handle non-field member expressions assert(Field && "No code generation for non-field member references"); LValue MemExpLV = EmitLValueForField(BaseValue, Field, isUnion, CVRQualifiers); LValue::SetObjCIvar(MemExpLV, isIvar); LValue::SetObjCNonGC(MemExpLV, isNonGC); return MemExpLV; } LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue, FieldDecl* Field, unsigned CVRQualifiers) { unsigned idx = CGM.getTypes().getLLVMFieldNo(Field); // FIXME: CodeGenTypes should expose a method to get the appropriate // type for FieldTy (the appropriate type is ABI-dependent). const llvm::Type *FieldTy = CGM.getTypes().ConvertTypeForMem(Field->getType()); const llvm::PointerType *BaseTy = cast<llvm::PointerType>(BaseValue->getType()); unsigned AS = BaseTy->getAddressSpace(); BaseValue = Builder.CreateBitCast(BaseValue, llvm::PointerType::get(FieldTy, AS), "tmp"); llvm::Value *V = Builder.CreateGEP(BaseValue, llvm::ConstantInt::get(llvm::Type::Int32Ty, idx), "tmp"); CodeGenTypes::BitFieldInfo bitFieldInfo = CGM.getTypes().getBitFieldInfo(Field); return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size, Field->getType()->isSignedIntegerType(), Field->getType().getCVRQualifiers()|CVRQualifiers); } LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue, FieldDecl* Field, bool isUnion, unsigned CVRQualifiers) { if (Field->isBitField()) return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers); unsigned idx = CGM.getTypes().getLLVMFieldNo(Field); llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); // Match union field type. if (isUnion) { const llvm::Type *FieldTy = CGM.getTypes().ConvertTypeForMem(Field->getType()); const llvm::PointerType * BaseTy = cast<llvm::PointerType>(BaseValue->getType()); unsigned AS = BaseTy->getAddressSpace(); V = Builder.CreateBitCast(V, llvm::PointerType::get(FieldTy, AS), "tmp"); } QualType::GCAttrTypes attr = QualType::GCNone; if (CGM.getLangOptions().ObjC1 && CGM.getLangOptions().getGCMode() != LangOptions::NonGC) { QualType Ty = Field->getType(); attr = Ty.getObjCGCAttr(); if (attr != QualType::GCNone) { // __weak attribute on a field is ignored. if (attr == QualType::Weak) attr = QualType::GCNone; } else if (getContext().isObjCObjectPointerType(Ty)) attr = QualType::Strong; } LValue LV = LValue::MakeAddr(V, Field->getType().getCVRQualifiers()|CVRQualifiers, attr); return LV; } LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){ const llvm::Type *LTy = ConvertType(E->getType()); llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral"); const Expr* InitExpr = E->getInitializer(); LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers()); if (E->getType()->isComplexType()) { EmitComplexExprIntoAddr(InitExpr, DeclPtr, false); } else if (hasAggregateLLVMType(E->getType())) { EmitAnyExpr(InitExpr, DeclPtr, false); } else { EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType()); } return Result; } LValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator* E) { // We don't handle vectors yet. if (E->getType()->isVectorType()) return EmitUnsupportedLValue(E, "conditional operator"); // ?: here should be an aggregate. assert((hasAggregateLLVMType(E->getType()) && !E->getType()->isAnyComplexType()) && "Unexpected conditional operator!"); llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); EmitAggExpr(E, Temp, false); return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } /// EmitCastLValue - Casts are never lvalues. If a cast is needed by the code /// generator in an lvalue context, then it must mean that we need the address /// of an aggregate in order to access one of its fields. This can happen for /// all the reasons that casts are permitted with aggregate result, including /// noop aggregate casts, and cast from scalar to union. LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { // If this is an aggregate-to-aggregate cast, just use the input's address as // the lvalue. if (getContext().hasSameUnqualifiedType(E->getType(), E->getSubExpr()->getType())) return EmitLValue(E->getSubExpr()); // Otherwise, we must have a cast from scalar to union. assert(E->getType()->isUnionType() && "Expected scalar-to-union cast"); // Casts are only lvalues when the source and destination types are the same. llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); EmitAnyExpr(E->getSubExpr(), Temp, false); return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } //===--------------------------------------------------------------------===// // Expression Emission //===--------------------------------------------------------------------===// RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) { // Builtins never have block type. if (E->getCallee()->getType()->isBlockPointerType()) return EmitBlockCallExpr(E); if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E)) return EmitCXXMemberCallExpr(CE); const Decl *TargetDecl = 0; if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) { if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) { TargetDecl = DRE->getDecl(); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl)) if (unsigned builtinID = FD->getBuiltinID(getContext())) return EmitBuiltinExpr(FD, builtinID, E); } } llvm::Value *Callee = EmitScalarExpr(E->getCallee()); return EmitCallExpr(Callee, E->getCallee()->getType(), E->arg_begin(), E->arg_end(), TargetDecl); } LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { // Can only get l-value for binary operator expressions which are a // simple assignment of aggregate type. if (E->getOpcode() != BinaryOperator::Assign) return EmitUnsupportedLValue(E, "binary l-value expression"); llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); EmitAggExpr(E, Temp, false); // FIXME: Are these qualifiers correct? return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { // Can only get l-value for call expression returning aggregate type RValue RV = EmitCallExpr(E); return LValue::MakeAddr(RV.getAggregateAddr(), E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { // FIXME: This shouldn't require another copy. llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); EmitAggExpr(E, Temp, false); return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers()); } LValue CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) { EmitLocalBlockVarDecl(*E->getVarDecl()); return EmitDeclRefLValue(E); } LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { // Can only get l-value for message expression returning aggregate type RValue RV = EmitObjCMessageExpr(E); // FIXME: can this be volatile? return LValue::MakeAddr(RV.getAggregateAddr(), E->getType().getCVRQualifiers(), getContext().getObjCGCAttrKind(E->getType())); } llvm::Value *CodeGenFunction::EmitIvarOffset(ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar) { // Objective-C objects are traditionally C structures with their layout // defined at compile-time. In some implementations, their layout is not // defined until run time in order to allow instance variables to be added to // a class without recompiling all of the subclasses. If this is the case // then the CGObjCRuntime subclass must return true to LateBoundIvars and // implement the lookup itself. if (CGM.getObjCRuntime().LateBoundIVars()) assert(0 && "late-bound ivars are unsupported"); return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); } LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, const FieldDecl *Field, unsigned CVRQualifiers) { // See comment in EmitIvarOffset. if (CGM.getObjCRuntime().LateBoundIVars()) assert(0 && "late-bound ivars are unsupported"); LValue LV = CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, Ivar, Field, CVRQualifiers); return LV; } LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { // FIXME: A lot of the code below could be shared with EmitMemberExpr. llvm::Value *BaseValue = 0; const Expr *BaseExpr = E->getBase(); unsigned CVRQualifiers = 0; QualType ObjectTy; if (E->isArrow()) { BaseValue = EmitScalarExpr(BaseExpr); const PointerType *PTy = cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType())); ObjectTy = PTy->getPointeeType(); CVRQualifiers = ObjectTy.getCVRQualifiers(); } else { LValue BaseLV = EmitLValue(BaseExpr); // FIXME: this isn't right for bitfields. BaseValue = BaseLV.getAddress(); ObjectTy = BaseExpr->getType(); CVRQualifiers = ObjectTy.getCVRQualifiers(); } return EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), getContext().getFieldDecl(E), CVRQualifiers); } LValue CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) { // This is a special l-value that just issues sends when we load or // store through it. return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers()); } LValue CodeGenFunction::EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E) { // This is a special l-value that just issues sends when we load or // store through it. return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers()); } LValue CodeGenFunction::EmitObjCSuperExpr(const ObjCSuperExpr *E) { return EmitUnsupportedLValue(E, "use of super"); } RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType CalleeType, CallExpr::const_arg_iterator ArgBeg, CallExpr::const_arg_iterator ArgEnd, const Decl *TargetDecl) { // Get the actual function type. The callee type will always be a // pointer to function type or a block pointer type. assert(CalleeType->isFunctionPointerType() && "Call must have function pointer type!"); QualType FnType = CalleeType->getAsPointerType()->getPointeeType(); QualType ResultType = FnType->getAsFunctionType()->getResultType(); CallArgList Args; EmitCallArgs(Args, FnType->getAsFunctionProtoType(), ArgBeg, ArgEnd); return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, TargetDecl); } <file_sep>/test/Parser/cxx-typeof.cpp // RUN: clang-cc -fsyntax-only -verify %s static void test() { int *pi; int x; typeof pi[x] y; } <file_sep>/lib/Analysis/GRSimpleVals.cpp // GRSimpleVals.cpp - Transfer functions for tracking simple values -*- C++ -*-- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines GRSimpleVals, a sub-class of GRTransferFuncs that // provides transfer functions for performing simple value tracking with // limited support for symbolics. // //===----------------------------------------------------------------------===// #include "GRSimpleVals.h" #include "BasicObjCFoundationChecks.h" #include "clang/Basic/SourceManager.h" #include "clang/Analysis/PathDiagnostic.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Analysis/LocalCheckers.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" #include "llvm/Support/Compiler.h" #include <sstream> using namespace clang; //===----------------------------------------------------------------------===// // Transfer Function creation for External clients. //===----------------------------------------------------------------------===// GRTransferFuncs* clang::MakeGRSimpleValsTF() { return new GRSimpleVals(); } //===----------------------------------------------------------------------===// // Transfer function for Casts. //===----------------------------------------------------------------------===// SVal GRSimpleVals::EvalCast(GRExprEngine& Eng, NonLoc X, QualType T) { if (!isa<nonloc::ConcreteInt>(X)) return UnknownVal(); bool isLocType = Loc::IsLocType(T); // Only handle casts from integers to integers. if (!isLocType && !T->isIntegerType()) return UnknownVal(); BasicValueFactory& BasicVals = Eng.getBasicVals(); llvm::APSInt V = cast<nonloc::ConcreteInt>(X).getValue(); V.setIsUnsigned(T->isUnsignedIntegerType() || Loc::IsLocType(T)); V.extOrTrunc(Eng.getContext().getTypeSize(T)); if (isLocType) return loc::ConcreteInt(BasicVals.getValue(V)); else return nonloc::ConcreteInt(BasicVals.getValue(V)); } // Casts. SVal GRSimpleVals::EvalCast(GRExprEngine& Eng, Loc X, QualType T) { // Casts from pointers -> pointers, just return the lval. // // Casts from pointers -> references, just return the lval. These // can be introduced by the frontend for corner cases, e.g // casting from va_list* to __builtin_va_list&. // assert (!X.isUnknownOrUndef()); if (Loc::IsLocType(T) || T->isReferenceType()) return X; // FIXME: Handle transparent unions where a value can be "transparently" // lifted into a union type. if (T->isUnionType()) return UnknownVal(); assert (T->isIntegerType()); BasicValueFactory& BasicVals = Eng.getBasicVals(); unsigned BitWidth = Eng.getContext().getTypeSize(T); if (!isa<loc::ConcreteInt>(X)) return nonloc::LocAsInteger::Make(BasicVals, X, BitWidth); llvm::APSInt V = cast<loc::ConcreteInt>(X).getValue(); V.setIsUnsigned(T->isUnsignedIntegerType() || Loc::IsLocType(T)); V.extOrTrunc(BitWidth); return nonloc::ConcreteInt(BasicVals.getValue(V)); } // Unary operators. SVal GRSimpleVals::EvalMinus(GRExprEngine& Eng, UnaryOperator* U, NonLoc X){ switch (X.getSubKind()) { case nonloc::ConcreteIntKind: return cast<nonloc::ConcreteInt>(X).EvalMinus(Eng.getBasicVals(), U); default: return UnknownVal(); } } SVal GRSimpleVals::EvalComplement(GRExprEngine& Eng, NonLoc X) { switch (X.getSubKind()) { case nonloc::ConcreteIntKind: return cast<nonloc::ConcreteInt>(X).EvalComplement(Eng.getBasicVals()); default: return UnknownVal(); } } // Binary operators. static unsigned char LNotOpMap[] = { (unsigned char) BinaryOperator::GE, /* LT => GE */ (unsigned char) BinaryOperator::LE, /* GT => LE */ (unsigned char) BinaryOperator::GT, /* LE => GT */ (unsigned char) BinaryOperator::LT, /* GE => LT */ (unsigned char) BinaryOperator::NE, /* EQ => NE */ (unsigned char) BinaryOperator::EQ /* NE => EQ */ }; SVal GRSimpleVals::DetermEvalBinOpNN(GRExprEngine& Eng, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, QualType T) { BasicValueFactory& BasicVals = Eng.getBasicVals(); unsigned subkind = L.getSubKind(); while (1) { switch (subkind) { default: return UnknownVal(); case nonloc::LocAsIntegerKind: { Loc LL = cast<nonloc::LocAsInteger>(L).getLoc(); switch (R.getSubKind()) { case nonloc::LocAsIntegerKind: return EvalBinOp(Eng, Op, LL, cast<nonloc::LocAsInteger>(R).getLoc()); case nonloc::ConcreteIntKind: { // Transform the integer into a location and compare. ASTContext& Ctx = Eng.getContext(); llvm::APSInt V = cast<nonloc::ConcreteInt>(R).getValue(); V.setIsUnsigned(true); V.extOrTrunc(Ctx.getTypeSize(Ctx.VoidPtrTy)); return EvalBinOp(Eng, Op, LL, loc::ConcreteInt(BasicVals.getValue(V))); } default: switch (Op) { case BinaryOperator::EQ: return NonLoc::MakeIntTruthVal(BasicVals, false); case BinaryOperator::NE: return NonLoc::MakeIntTruthVal(BasicVals, true); default: // This case also handles pointer arithmetic. return UnknownVal(); } } } case nonloc::SymExprValKind: { // Logical not? if (!(Op == BinaryOperator::EQ && R.isZeroConstant())) return UnknownVal(); const SymExpr &SE=*cast<nonloc::SymExprVal>(L).getSymbolicExpression(); // Only handle ($sym op constant) for now. if (const SymIntExpr *E = dyn_cast<SymIntExpr>(&SE)) { BinaryOperator::Opcode Opc = E->getOpcode(); if (Opc < BinaryOperator::LT || Opc > BinaryOperator::NE) return UnknownVal(); // For comparison operators, translate the constraint by // changing the opcode. int idx = (unsigned) Opc - (unsigned) BinaryOperator::LT; assert (idx >= 0 && (unsigned) idx < sizeof(LNotOpMap)/sizeof(unsigned char)); Opc = (BinaryOperator::Opcode) LNotOpMap[idx]; assert(E->getType(Eng.getContext()) == T); E = Eng.getSymbolManager().getSymIntExpr(E->getLHS(), Opc, E->getRHS(), T); return nonloc::SymExprVal(E); } return UnknownVal(); } case nonloc::ConcreteIntKind: if (isa<nonloc::ConcreteInt>(R)) { const nonloc::ConcreteInt& L_CI = cast<nonloc::ConcreteInt>(L); const nonloc::ConcreteInt& R_CI = cast<nonloc::ConcreteInt>(R); return L_CI.EvalBinOp(BasicVals, Op, R_CI); } else { subkind = R.getSubKind(); NonLoc tmp = R; R = L; L = tmp; // Swap the operators. switch (Op) { case BinaryOperator::LT: Op = BinaryOperator::GT; break; case BinaryOperator::GT: Op = BinaryOperator::LT; break; case BinaryOperator::LE: Op = BinaryOperator::GE; break; case BinaryOperator::GE: Op = BinaryOperator::LE; break; default: break; } continue; } case nonloc::SymbolValKind: if (isa<nonloc::ConcreteInt>(R)) { ValueManager &ValMgr = Eng.getValueManager(); return ValMgr.makeNonLoc(cast<nonloc::SymbolVal>(L).getSymbol(), Op, cast<nonloc::ConcreteInt>(R).getValue(), T); } else return UnknownVal(); } } } // Binary Operators (except assignments and comma). SVal GRSimpleVals::EvalBinOp(GRExprEngine& Eng, BinaryOperator::Opcode Op, Loc L, Loc R) { switch (Op) { default: return UnknownVal(); case BinaryOperator::EQ: return EvalEQ(Eng, L, R); case BinaryOperator::NE: return EvalNE(Eng, L, R); } } SVal GRSimpleVals::EvalBinOp(GRExprEngine& Eng, BinaryOperator::Opcode Op, Loc L, NonLoc R) { // Delegate pointer arithmetic to store manager. return Eng.getStoreManager().EvalBinOp(Op, L, R); } // Equality operators for Locs. // FIXME: All this logic will be revamped when we have MemRegion::getLocation() // implemented. SVal GRSimpleVals::EvalEQ(GRExprEngine& Eng, Loc L, Loc R) { BasicValueFactory& BasicVals = Eng.getBasicVals(); switch (L.getSubKind()) { default: assert(false && "EQ not implemented for this Loc."); return UnknownVal(); case loc::ConcreteIntKind: if (isa<loc::ConcreteInt>(R)) { bool b = cast<loc::ConcreteInt>(L).getValue() == cast<loc::ConcreteInt>(R).getValue(); return NonLoc::MakeIntTruthVal(BasicVals, b); } break; case loc::MemRegionKind: { if (SymbolRef LSym = L.getAsLocSymbol()) { if (isa<loc::ConcreteInt>(R)) { const SymIntExpr *SE = Eng.getSymbolManager().getSymIntExpr(LSym, BinaryOperator::EQ, cast<loc::ConcreteInt>(R).getValue(), Eng.getContext().IntTy); return nonloc::SymExprVal(SE); } } } // Fall-through. case loc::FuncValKind: case loc::GotoLabelKind: return NonLoc::MakeIntTruthVal(BasicVals, L == R); } return NonLoc::MakeIntTruthVal(BasicVals, false); } SVal GRSimpleVals::EvalNE(GRExprEngine& Eng, Loc L, Loc R) { BasicValueFactory& BasicVals = Eng.getBasicVals(); switch (L.getSubKind()) { default: assert(false && "NE not implemented for this Loc."); return UnknownVal(); case loc::ConcreteIntKind: if (isa<loc::ConcreteInt>(R)) { bool b = cast<loc::ConcreteInt>(L).getValue() != cast<loc::ConcreteInt>(R).getValue(); return NonLoc::MakeIntTruthVal(BasicVals, b); } else if (SymbolRef Sym = R.getAsSymbol()) { const SymIntExpr * SE = Eng.getSymbolManager().getSymIntExpr(Sym, BinaryOperator::NE, cast<loc::ConcreteInt>(L).getValue(), Eng.getContext().IntTy); return nonloc::SymExprVal(SE); } break; case loc::MemRegionKind: { if (SymbolRef LSym = L.getAsLocSymbol()) { if (isa<loc::ConcreteInt>(R)) { const SymIntExpr* SE = Eng.getSymbolManager().getSymIntExpr(LSym, BinaryOperator::NE, cast<loc::ConcreteInt>(R).getValue(), Eng.getContext().IntTy); return nonloc::SymExprVal(SE); } } // Fall through: } case loc::FuncValKind: case loc::GotoLabelKind: return NonLoc::MakeIntTruthVal(BasicVals, L != R); } return NonLoc::MakeIntTruthVal(BasicVals, true); } //===----------------------------------------------------------------------===// // Transfer function for function calls. //===----------------------------------------------------------------------===// void GRSimpleVals::EvalCall(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, CallExpr* CE, SVal L, ExplodedNode<GRState>* Pred) { GRStateManager& StateMgr = Eng.getStateManager(); const GRState* St = Builder.GetState(Pred); // Invalidate all arguments passed in by reference (Locs). for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { SVal V = StateMgr.GetSVal(St, *I); if (isa<loc::MemRegionVal>(V)) St = StateMgr.BindLoc(St, cast<Loc>(V), UnknownVal()); else if (isa<nonloc::LocAsInteger>(V)) St = StateMgr.BindLoc(St, cast<nonloc::LocAsInteger>(V).getLoc(), UnknownVal()); } // Make up a symbol for the return value of this function. // FIXME: We eventually should handle structs and other compound types // that are returned by value. QualType T = CE->getType(); if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) { unsigned Count = Builder.getCurrentBlockCount(); SVal X = Eng.getValueManager().getConjuredSymbolVal(CE, Count); St = StateMgr.BindExpr(St, CE, X, Eng.getCFG().isBlkExpr(CE), false); } Builder.MakeNode(Dst, CE, Pred, St); } //===----------------------------------------------------------------------===// // Transfer function for Objective-C message expressions. //===----------------------------------------------------------------------===// void GRSimpleVals::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, ObjCMessageExpr* ME, ExplodedNode<GRState>* Pred) { // The basic transfer function logic for message expressions does nothing. // We just invalidate all arguments passed in by references. GRStateManager& StateMgr = Eng.getStateManager(); const GRState* St = Builder.GetState(Pred); for (ObjCMessageExpr::arg_iterator I = ME->arg_begin(), E = ME->arg_end(); I != E; ++I) { SVal V = StateMgr.GetSVal(St, *I); if (isa<Loc>(V)) St = StateMgr.BindLoc(St, cast<Loc>(V), UnknownVal()); } Builder.MakeNode(Dst, ME, Pred, St); } <file_sep>/test/CodeGen/c-strings.c // RUN: clang-cc -emit-llvm -o %t %s && // RUN: grep "hello" %t | count 3 && // RUN: grep 'c"hello\\00"' %t | count 2 && // RUN: grep 'c"hello\\00\\00\\00"' %t | count 1 && // RUN: grep 'c"ola"' %t | count 1 /* Should be 3 hello string, two global (of different sizes), the rest are shared. */ void f0() { bar("hello"); } void f1() { static char *x = "hello"; bar(x); } void f2() { static char x[] = "hello"; bar(x); } void f3() { static char x[8] = "hello"; bar(x); } void f4() { static struct s { char *name; } x = { "hello" }; gaz(&x); } char x[3] = "ola"; <file_sep>/include/clang/Frontend/FixItRewriter.h //===--- FixItRewriter.h - Fix-It Rewriter Diagnostic Client ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a diagnostic client adaptor that performs rewrites as // suggested by code modification hints attached to diagnostics. It // then forwards any diagnostics to the adapted diagnostic client. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_FIX_IT_REWRITER_H #define LLVM_CLANG_FRONTEND_FIX_IT_REWRITER_H #include "clang/Basic/Diagnostic.h" #include "clang/Rewrite/Rewriter.h" #include "llvm/ADT/SmallVector.h" namespace clang { class SourceManager; class FileEntry; /// \brief Stores a source location in the form that it shows up on /// the Clang command line, e.g., file:line:column. /// /// FIXME: Would prefer to use real SourceLocations, but I don't see a /// good way to resolve them during parsing. struct RequestedSourceLocation { const FileEntry *File; unsigned Line; unsigned Column; }; class FixItRewriter : public DiagnosticClient { /// \brief The diagnostics machinery. Diagnostic &Diags; /// \brief The rewriter used to perform the various code /// modifications. Rewriter Rewrite; /// \brief The diagnostic client that performs the actual formatting /// of error messages. DiagnosticClient *Client; /// \brief The number of rewriter failures. unsigned NumFailures; /// \brief Locations at which we should perform fix-its. /// /// When empty, perform fix-it modifications everywhere. llvm::SmallVector<RequestedSourceLocation, 4> FixItLocations; public: /// \brief Initialize a new fix-it rewriter. FixItRewriter(Diagnostic &Diags, SourceManager &SourceMgr, const LangOptions &LangOpts); /// \brief Destroy the fix-it rewriter. ~FixItRewriter(); /// \brief Add a location where fix-it modifications should be /// performed. void addFixItLocation(RequestedSourceLocation Loc) { FixItLocations.push_back(Loc); } /// \brief Write the modified source file. /// /// \returns true if there was an error, false otherwise. bool WriteFixedFile(const std::string &InFileName, const std::string &OutFileName = std::string()); /// IncludeInDiagnosticCounts - This method (whose default implementation /// returns true) indicates whether the diagnostics handled by this /// DiagnosticClient should be included in the number of diagnostics /// reported by Diagnostic. virtual bool IncludeInDiagnosticCounts() const; /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or /// capturing it to a log as needed. virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info); /// \brief Emit a diagnostic via the adapted diagnostic client. void Diag(FullSourceLoc Loc, unsigned DiagID); }; } #endif // LLVM_CLANG_FRONTEND_FIX_IT_REWRITER_H <file_sep>/lib/Basic/IdentifierTable.cpp //===--- IdentifierTable.cpp - Hash table for identifier lookup -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the IdentifierInfo, IdentifierVisitor, and // IdentifierTable interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Bitcode/Serialize.h" #include "llvm/Bitcode/Deserialize.h" #include <cstdio> using namespace clang; //===----------------------------------------------------------------------===// // IdentifierInfo Implementation //===----------------------------------------------------------------------===// IdentifierInfo::IdentifierInfo() { TokenID = tok::identifier; ObjCOrBuiltinID = 0; HasMacro = false; IsExtension = false; IsPoisoned = false; IsCPPOperatorKeyword = false; NeedsHandleIdentifier = false; FETokenInfo = 0; Entry = 0; } //===----------------------------------------------------------------------===// // IdentifierTable Implementation //===----------------------------------------------------------------------===// IdentifierInfoLookup::~IdentifierInfoLookup() {} IdentifierTable::IdentifierTable(const LangOptions &LangOpts, IdentifierInfoLookup* externalLookup) : HashTable(8192), // Start with space for 8K identifiers. ExternalLookup(externalLookup) { // Populate the identifier table with info about keywords for the current // language. AddKeywords(LangOpts); } // This cstor is intended to be used only for serialization. IdentifierTable::IdentifierTable() : HashTable(8192), ExternalLookup(0) { } //===----------------------------------------------------------------------===// // Language Keyword Implementation //===----------------------------------------------------------------------===// /// AddKeyword - This method is used to associate a token ID with specific /// identifiers because they are language keywords. This causes the lexer to /// automatically map matching identifiers to specialized token codes. /// /// The C90/C99/CPP/CPP0x flags are set to 0 if the token should be /// enabled in the specified langauge, set to 1 if it is an extension /// in the specified language, and set to 2 if disabled in the /// specified language. static void AddKeyword(const char *Keyword, unsigned KWLen, tok::TokenKind TokenCode, int C90, int C99, int CXX, int CXX0x, int BoolSupport, const LangOptions &LangOpts, IdentifierTable &Table) { int Flags = 0; if (BoolSupport != 0) { Flags = LangOpts.CPlusPlus? 0 : LangOpts.Boolean ? BoolSupport : 2; } else if (LangOpts.CPlusPlus) { Flags = LangOpts.CPlusPlus0x ? CXX0x : CXX; } else if (LangOpts.C99) { Flags = C99; } else { Flags = C90; } // Don't add this keyword if disabled in this language or if an extension // and extensions are disabled. if (Flags + LangOpts.NoExtensions >= 2) return; IdentifierInfo &Info = Table.get(Keyword, Keyword+KWLen); Info.setTokenID(TokenCode); Info.setIsExtensionToken(Flags == 1); } static void AddAlias(const char *Keyword, unsigned KWLen, tok::TokenKind AliaseeID, const char *AliaseeKeyword, unsigned AliaseeKWLen, const LangOptions &LangOpts, IdentifierTable &Table) { IdentifierInfo &AliasInfo = Table.get(Keyword, Keyword+KWLen); IdentifierInfo &AliaseeInfo = Table.get(AliaseeKeyword, AliaseeKeyword+AliaseeKWLen); AliasInfo.setTokenID(AliaseeID); AliasInfo.setIsExtensionToken(AliaseeInfo.isExtensionToken()); } /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative /// representations. static void AddCXXOperatorKeyword(const char *Keyword, unsigned KWLen, tok::TokenKind TokenCode, IdentifierTable &Table) { IdentifierInfo &Info = Table.get(Keyword, Keyword + KWLen); Info.setTokenID(TokenCode); Info.setIsCPlusPlusOperatorKeyword(); } /// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or /// "property". static void AddObjCKeyword(tok::ObjCKeywordKind ObjCID, const char *Name, unsigned NameLen, IdentifierTable &Table) { Table.get(Name, Name+NameLen).setObjCKeywordID(ObjCID); } /// AddKeywords - Add all keywords to the symbol table. /// void IdentifierTable::AddKeywords(const LangOptions &LangOpts) { enum { C90Shift = 0, EXTC90 = 1 << C90Shift, NOTC90 = 2 << C90Shift, C99Shift = 2, EXTC99 = 1 << C99Shift, NOTC99 = 2 << C99Shift, CPPShift = 4, EXTCPP = 1 << CPPShift, NOTCPP = 2 << CPPShift, CPP0xShift = 6, EXTCPP0x = 1 << CPP0xShift, NOTCPP0x = 2 << CPP0xShift, BoolShift = 8, BOOLSUPPORT = 1 << BoolShift, Mask = 3 }; // Add keywords and tokens for the current language. #define KEYWORD(NAME, FLAGS) \ AddKeyword(#NAME, strlen(#NAME), tok::kw_ ## NAME, \ ((FLAGS) >> C90Shift) & Mask, \ ((FLAGS) >> C99Shift) & Mask, \ ((FLAGS) >> CPPShift) & Mask, \ ((FLAGS) >> CPP0xShift) & Mask, \ ((FLAGS) >> BoolShift) & Mask, LangOpts, *this); #define ALIAS(NAME, TOK) \ AddAlias(NAME, strlen(NAME), tok::kw_ ## TOK, #TOK, strlen(#TOK), \ LangOpts, *this); #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \ if (LangOpts.CXXOperatorNames) \ AddCXXOperatorKeyword(#NAME, strlen(#NAME), tok::ALIAS, *this); #define OBJC1_AT_KEYWORD(NAME) \ if (LangOpts.ObjC1) \ AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this); #define OBJC2_AT_KEYWORD(NAME) \ if (LangOpts.ObjC2) \ AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this); #include "clang/Basic/TokenKinds.def" } tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { // We use a perfect hash function here involving the length of the keyword, // the first and third character. For preprocessor ID's there are no // collisions (if there were, the switch below would complain about duplicate // case values). Note that this depends on 'if' being null terminated. #define HASH(LEN, FIRST, THIRD) \ (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31) #define CASE(LEN, FIRST, THIRD, NAME) \ case HASH(LEN, FIRST, THIRD): \ return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME unsigned Len = getLength(); if (Len < 2) return tok::pp_not_keyword; const char *Name = getName(); switch (HASH(Len, Name[0], Name[2])) { default: return tok::pp_not_keyword; CASE( 2, 'i', '\0', if); CASE( 4, 'e', 'i', elif); CASE( 4, 'e', 's', else); CASE( 4, 'l', 'n', line); CASE( 4, 's', 'c', sccs); CASE( 5, 'e', 'd', endif); CASE( 5, 'e', 'r', error); CASE( 5, 'i', 'e', ident); CASE( 5, 'i', 'd', ifdef); CASE( 5, 'u', 'd', undef); CASE( 6, 'a', 's', assert); CASE( 6, 'd', 'f', define); CASE( 6, 'i', 'n', ifndef); CASE( 6, 'i', 'p', import); CASE( 6, 'p', 'a', pragma); CASE( 7, 'd', 'f', defined); CASE( 7, 'i', 'c', include); CASE( 7, 'w', 'r', warning); CASE( 8, 'u', 'a', unassert); CASE(12, 'i', 'c', include_next); CASE(16, '_', 'i', __include_macros); #undef CASE #undef HASH } } //===----------------------------------------------------------------------===// // Stats Implementation //===----------------------------------------------------------------------===// /// PrintStats - Print statistics about how well the identifier table is doing /// at hashing identifiers. void IdentifierTable::PrintStats() const { unsigned NumBuckets = HashTable.getNumBuckets(); unsigned NumIdentifiers = HashTable.getNumItems(); unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers; unsigned AverageIdentifierSize = 0; unsigned MaxIdentifierLength = 0; // TODO: Figure out maximum times an identifier had to probe for -stats. for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator I = HashTable.begin(), E = HashTable.end(); I != E; ++I) { unsigned IdLen = I->getKeyLength(); AverageIdentifierSize += IdLen; if (MaxIdentifierLength < IdLen) MaxIdentifierLength = IdLen; } fprintf(stderr, "\n*** Identifier Table Stats:\n"); fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers); fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets); fprintf(stderr, "Hash density (#identifiers per bucket): %f\n", NumIdentifiers/(double)NumBuckets); fprintf(stderr, "Ave identifier length: %f\n", (AverageIdentifierSize/(double)NumIdentifiers)); fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength); // Compute statistics about the memory allocated for identifiers. HashTable.getAllocator().PrintStats(); } //===----------------------------------------------------------------------===// // SelectorTable Implementation //===----------------------------------------------------------------------===// unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) { return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr()); } namespace clang { /// MultiKeywordSelector - One of these variable length records is kept for each /// selector containing more than one keyword. We use a folding set /// to unique aggregate names (keyword selectors in ObjC parlance). Access to /// this class is provided strictly through Selector. class MultiKeywordSelector : public DeclarationNameExtra, public llvm::FoldingSetNode { friend SelectorTable* SelectorTable::CreateAndRegister(llvm::Deserializer&); MultiKeywordSelector(unsigned nKeys) { ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; } public: // Constructor for keyword selectors. MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) { assert((nKeys > 1) && "not a multi-keyword selector"); ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; // Fill in the trailing keyword array. IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1); for (unsigned i = 0; i != nKeys; ++i) KeyInfo[i] = IIV[i]; } // getName - Derive the full selector name and return it. std::string getName() const; unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; } typedef IdentifierInfo *const *keyword_iterator; keyword_iterator keyword_begin() const { return reinterpret_cast<keyword_iterator>(this+1); } keyword_iterator keyword_end() const { return keyword_begin()+getNumArgs(); } IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const { assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index"); return keyword_begin()[i]; } static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys, unsigned NumArgs) { ID.AddInteger(NumArgs); for (unsigned i = 0; i != NumArgs; ++i) ID.AddPointer(ArgTys[i]); } void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, keyword_begin(), getNumArgs()); } }; } // end namespace clang. unsigned Selector::getNumArgs() const { unsigned IIF = getIdentifierInfoFlag(); if (IIF == ZeroArg) return 0; if (IIF == OneArg) return 1; // We point to a MultiKeywordSelector (pointer doesn't contain any flags). MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr); return SI->getNumArgs(); } IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const { if (IdentifierInfo *II = getAsIdentifierInfo()) { assert(argIndex == 0 && "illegal keyword index"); return II; } // We point to a MultiKeywordSelector (pointer doesn't contain any flags). MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr); return SI->getIdentifierInfoForSlot(argIndex); } std::string MultiKeywordSelector::getName() const { std::string Result; unsigned Length = 0; for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) { if (*I) Length += (*I)->getLength(); ++Length; // : } Result.reserve(Length); for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) { if (*I) Result.insert(Result.end(), (*I)->getName(), (*I)->getName()+(*I)->getLength()); Result.push_back(':'); } return Result; } std::string Selector::getAsString() const { if (InfoPtr & ArgFlags) { IdentifierInfo *II = getAsIdentifierInfo(); // If the number of arguments is 0 then II is guaranteed to not be null. if (getNumArgs() == 0) return II->getName(); std::string Res = II ? II->getName() : ""; Res += ":"; return Res; } // We have a multiple keyword selector (no embedded flags). return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName(); } namespace { struct SelectorTableImpl { llvm::FoldingSet<MultiKeywordSelector> Table; llvm::BumpPtrAllocator Allocator; }; } // end anonymous namespace. static SelectorTableImpl &getSelectorTableImpl(void *P) { return *static_cast<SelectorTableImpl*>(P); } Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) { if (nKeys < 2) return Selector(IIV[0], nKeys); SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); // Unique selector, to guarantee there is one per name. llvm::FoldingSetNodeID ID; MultiKeywordSelector::Profile(ID, IIV, nKeys); void *InsertPos = 0; if (MultiKeywordSelector *SI = SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos)) return Selector(SI); // MultiKeywordSelector objects are not allocated with new because they have a // variable size array (for parameter types) at the end of them. unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *); MultiKeywordSelector *SI = (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size, llvm::alignof<MultiKeywordSelector>()); new (SI) MultiKeywordSelector(nKeys, IIV); SelTabImpl.Table.InsertNode(SI, InsertPos); return Selector(SI); } SelectorTable::SelectorTable() { Impl = new SelectorTableImpl(); } SelectorTable::~SelectorTable() { delete &getSelectorTableImpl(Impl); } //===----------------------------------------------------------------------===// // Serialization for IdentifierInfo and IdentifierTable. //===----------------------------------------------------------------------===// void IdentifierInfo::Emit(llvm::Serializer& S) const { S.EmitInt(getTokenID()); S.EmitInt(getBuiltinID()); S.EmitInt(getObjCKeywordID()); S.EmitBool(hasMacroDefinition()); S.EmitBool(isExtensionToken()); S.EmitBool(isPoisoned()); S.EmitBool(isCPlusPlusOperatorKeyword()); // FIXME: FETokenInfo } void IdentifierInfo::Read(llvm::Deserializer& D) { setTokenID((tok::TokenKind) D.ReadInt()); setBuiltinID(D.ReadInt()); setObjCKeywordID((tok::ObjCKeywordKind) D.ReadInt()); setHasMacroDefinition(D.ReadBool()); setIsExtensionToken(D.ReadBool()); setIsPoisoned(D.ReadBool()); setIsCPlusPlusOperatorKeyword(D.ReadBool()); // FIXME: FETokenInfo } void IdentifierTable::Emit(llvm::Serializer& S) const { S.EnterBlock(); S.EmitPtr(this); for (iterator I=begin(), E=end(); I != E; ++I) { const char* Key = I->getKeyData(); const IdentifierInfo* Info = I->getValue(); bool KeyRegistered = S.isRegistered(Key); bool InfoRegistered = S.isRegistered(Info); if (KeyRegistered || InfoRegistered) { // These acrobatics are so that we don't incur the cost of registering // a pointer with the backpatcher during deserialization if nobody // references the object. S.EmitPtr(InfoRegistered ? Info : NULL); S.EmitPtr(KeyRegistered ? Key : NULL); S.EmitCStr(Key); S.Emit(*Info); } } S.ExitBlock(); } IdentifierTable* IdentifierTable::CreateAndRegister(llvm::Deserializer& D) { llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation(); std::vector<char> buff; buff.reserve(200); IdentifierTable* t = new IdentifierTable(); D.RegisterPtr(t); while (!D.FinishedBlock(BLoc)) { llvm::SerializedPtrID InfoPtrID = D.ReadPtrID(); llvm::SerializedPtrID KeyPtrID = D.ReadPtrID(); D.ReadCStr(buff); IdentifierInfo *II = &t->get(&buff[0], &buff[0] + buff.size()); II->Read(D); if (InfoPtrID) D.RegisterPtr(InfoPtrID, II); if (KeyPtrID) D.RegisterPtr(KeyPtrID, II->getName()); } return t; } //===----------------------------------------------------------------------===// // Serialization for Selector and SelectorTable. //===----------------------------------------------------------------------===// void Selector::Emit(llvm::Serializer& S) const { S.EmitInt(getIdentifierInfoFlag()); S.EmitPtr(reinterpret_cast<void*>(InfoPtr & ~ArgFlags)); } Selector Selector::ReadVal(llvm::Deserializer& D) { unsigned flag = D.ReadInt(); uintptr_t ptr; D.ReadUIntPtr(ptr,false); // No backpatching. return Selector(ptr | flag); } void SelectorTable::Emit(llvm::Serializer& S) const { typedef llvm::FoldingSet<MultiKeywordSelector>::iterator iterator; llvm::FoldingSet<MultiKeywordSelector> *SelTab; SelTab = static_cast<llvm::FoldingSet<MultiKeywordSelector> *>(Impl); S.EnterBlock(); S.EmitPtr(this); for (iterator I=SelTab->begin(), E=SelTab->end(); I != E; ++I) { if (!S.isRegistered(&*I)) continue; S.FlushRecord(); // Start a new record. S.EmitPtr(&*I); S.EmitInt(I->getNumArgs()); for (MultiKeywordSelector::keyword_iterator KI = I->keyword_begin(), KE = I->keyword_end(); KI != KE; ++KI) S.EmitPtr(*KI); } S.ExitBlock(); } SelectorTable* SelectorTable::CreateAndRegister(llvm::Deserializer& D) { llvm::Deserializer::Location BLoc = D.getCurrentBlockLocation(); SelectorTable* t = new SelectorTable(); D.RegisterPtr(t); llvm::FoldingSet<MultiKeywordSelector>& SelTab = *static_cast<llvm::FoldingSet<MultiKeywordSelector>*>(t->Impl); while (!D.FinishedBlock(BLoc)) { llvm::SerializedPtrID PtrID = D.ReadPtrID(); unsigned nKeys = D.ReadInt(); MultiKeywordSelector *SI = (MultiKeywordSelector*)malloc(sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *)); new (SI) MultiKeywordSelector(nKeys); D.RegisterPtr(PtrID,SI); IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(SI+1); for (unsigned i = 0; i != nKeys; ++i) D.ReadPtr(KeyInfo[i],false); SelTab.GetOrInsertNode(SI); } return t; } <file_sep>/test/SemaCXX/do-while-scope.cpp // RUN: clang-cc -fsyntax-only -verify %s void test() { int x; do int x; while (1); } <file_sep>/test/Analysis/cfref_PR2519.c // RUN: clang-cc -analyze -checker-cfref --analyzer-store=basic -analyzer-constraints=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref --analyzer-store=basic -analyzer-constraints=range -verify %s && // RUN: clang-cc -analyze -checker-cfref --analyzer-store=region -analyzer-constraints=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref --analyzer-store=region -analyzer-constraints=range -verify %s typedef unsigned char Boolean; typedef signed long CFIndex; typedef const void * CFTypeRef; typedef const struct __CFString * CFStringRef; typedef const struct __CFAllocator * CFAllocatorRef; extern const CFAllocatorRef kCFAllocatorDefault; typedef struct {} CFAllocatorContext; extern void CFRelease(CFTypeRef cf); typedef struct {} CFDictionaryKeyCallBacks; extern const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks; typedef struct {} CFDictionaryValueCallBacks; extern const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks; typedef const struct __CFDictionary * CFDictionaryRef; extern CFDictionaryRef CFDictionaryCreate(CFAllocatorRef allocator, const void **keys, const void **values, CFIndex numValues, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks); enum { kCFNumberSInt8Type = 1, kCFNumberSInt16Type = 2, kCFNumberSInt32Type = 3, kCFNumberSInt64Type = 4, kCFNumberFloat32Type = 5, kCFNumberFloat64Type = 6, kCFNumberCharType = 7, kCFNumberShortType = 8, kCFNumberIntType = 9, kCFNumberLongType = 10, kCFNumberLongLongType = 11, kCFNumberFloatType = 12, kCFNumberDoubleType = 13, kCFNumberCFIndexType = 14, kCFNumberNSIntegerType = 15, kCFNumberCGFloatType = 16, kCFNumberMaxType = 16 }; typedef CFIndex CFNumberType; typedef const struct __CFNumber * CFNumberRef; extern CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr); typedef struct __CFNotificationCenter * CFNotificationCenterRef; extern CFNotificationCenterRef CFNotificationCenterGetDistributedCenter(void); extern void CFNotificationCenterPostNotification(CFNotificationCenterRef center, CFStringRef name, const void *object, CFDictionaryRef userInfo, Boolean deliverImmediately); // This test case was reported in PR2519 as a false positive (_value was // reported as being leaked). int main(int argc, char **argv) { CFStringRef _key = ((CFStringRef) __builtin___CFStringMakeConstantString ("" "Process identifier" "")); int pid = 42; CFNumberRef _value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &pid); CFDictionaryRef userInfo = CFDictionaryCreate(kCFAllocatorDefault, (const void **)&_key, (const void **)&_value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(_value); // no-warning CFNotificationCenterPostNotification(CFNotificationCenterGetDistributedCenter(), ((CFStringRef) __builtin___CFStringMakeConstantString ("" "GrowlPreferencesChanged" "")), ((CFStringRef) __builtin___CFStringMakeConstantString ("" "GrowlUserDefaults" "")), userInfo, 0); CFRelease(userInfo); // no-warning return 0; } <file_sep>/tools/ccc/test/ccc/hello.c // RUN: xcc -ccc-no-clang %s -o %t && // RUN: %t | grep "Hello, World" && // RUN: xcc -ccc-no-clang %s -o %t -pipe && // RUN: %t | grep "Hello, World" && // RUN: xcc %s -o %t && // RUN: %t | grep "Hello, World" int main() { printf("Hello, World!\n"); return 0; } <file_sep>/test/TestRunner.sh #!/bin/sh # # TestRunner.sh - This script is used to run arbitrary unit tests. Unit # tests must contain the command used to run them in the input file, starting # immediately after a "RUN:" string. # # This runner recognizes and replaces the following strings in the command: # # %s - Replaced with the input name of the program, or the program to # execute, as appropriate. # %S - Replaced with the directory where the input file resides # %prcontext - prcontext.tcl script # %t - temporary file name (derived from testcase name) # FILENAME=$1 TESTNAME=$1 SUBST=$1 FILEDIR=`dirname $TESTNAME` OUTPUT=Output/$1.out # create the output directory if it does not already exist mkdir -p `dirname $OUTPUT` > /dev/null 2>&1 if test $# != 1; then # If more than one parameter is passed in, there must be three parameters: # The filename to read from (already processed), the command used to execute, # and the file to output to. SUBST=$2 OUTPUT=$3 TESTNAME=$3 fi ulimit -t 40 # Verify the script contains a run line. grep -q 'RUN:' $FILENAME || ( echo "******************** TEST '$TESTNAME' HAS NO RUN LINE! ********************" exit 1 ) # Run under valgrind if the VG environment variable has been set. CLANG=$CLANG if [ ! -n "$CLANG" ]; then CLANG="clang" fi # Resolve the path, and Make sure $CLANG actually exists; otherwise # ensuing failures are non-obvious. CLANG=$(which "$CLANG") if [ -z $CLANG ]; then echo "Couldn't find 'clang' program, try setting CLANG in your environment" exit 1 fi if [ -n "$VG" ]; then rm -f $OUTPUT.vg CLANG="valgrind --leak-check=full --quiet --log-file=$OUTPUT.vg $CLANG" fi # Assuming $CLANG is correct, use it to derive clang-cc. We expect to # be looking in a build directory, so just add '-cc'. CLANGCC=$CLANGCC if [ ! -n "$CLANGCC" ]; then CLANGCC="$CLANG-cc" fi # Try to sanity check $CLANGCC too CLANGCC=$(which "$CLANGCC") if [ -z "$CLANGCC" ]; then echo "Couldn't find 'clang-cc' program, make sure clang is found in your build directory" exit 1 fi SCRIPT=$OUTPUT.script TEMPOUTPUT=$OUTPUT.tmp grep 'RUN:' $FILENAME | \ sed -e "s|^.*RUN:\(.*\)$|\1|g" \ -e "s| clang | $CLANG |g" \ -e "s| clang-cc | $CLANGCC |g" \ -e "s|%s|$SUBST|g" \ -e "s|%S|$FILEDIR|g" \ -e "s|%prcontext|prcontext.tcl|g" \ -e "s|%t|$TEMPOUTPUT|g" > $SCRIPT IS_XFAIL=0 if (grep -q XFAIL $FILENAME); then IS_XFAIL=1 printf "XFAILED '$TESTNAME': " grep XFAIL $FILENAME fi /bin/sh $SCRIPT > $OUTPUT 2>&1 SCRIPT_STATUS=$? if [ -n "$VG" ]; then [ ! -s $OUTPUT.vg ] VG_STATUS=$? else VG_STATUS=0 fi if [ $IS_XFAIL -ne 0 ]; then if [ $SCRIPT_STATUS -ne 0 ]; then SCRIPT_STATUS=0 else SCRIPT_STATUS=1 fi fi if [ $SCRIPT_STATUS -ne 0 -o $VG_STATUS -ne 0 ]; then echo "******************** TEST '$TESTNAME' FAILED! ********************" echo "Command: " cat $SCRIPT if [ $SCRIPT_STATUS -eq 0 ]; then echo "Output:" elif [ $IS_XFAIL -ne 0 ]; then echo "Incorrect Output (Expected Failure):" else echo "Incorrect Output:" fi cat $OUTPUT if [ $VG_STATUS -ne 0 ]; then echo "Valgrind Output:" cat $OUTPUT.vg fi echo "******************** TEST '$TESTNAME' FAILED! ********************" exit 1 fi <file_sep>/test/Driver/clang_cpp.c // Verify that -include isn't included twice with -save-temps. // RUN: clang -S -o - %s -include %t.h -save-temps -### 2> %t.log && // RUN: grep '"-include' %t.log | count 1 <file_sep>/test/CodeGen/visibility.c // RUN: clang-cc -triple i386-unknown-unknown -fvisibility=default -emit-llvm -o %t %s && // RUN: grep '@g_com = common global i32 0' %t && // RUN: grep '@g_def = global i32 0' %t && // RUN: grep '@g_ext = external global i32' %t && // RUN: grep '@g_deferred = internal global' %t && // RUN: grep 'declare void @f_ext()' %t && // RUN: grep 'define internal void @f_deferred()' %t && // RUN: grep 'define i32 @f_def()' %t && // RUN: clang-cc -triple i386-unknown-unknown -fvisibility=protected -emit-llvm -o %t %s && // RUN: grep '@g_com = common protected global i32 0' %t && // RUN: grep '@g_def = protected global i32 0' %t && // RUN: grep '@g_ext = external global i32' %t && // RUN: grep '@g_deferred = internal global' %t && // RUN: grep 'declare void @f_ext()' %t && // RUN: grep 'define internal void @f_deferred()' %t && // RUN: grep 'define protected i32 @f_def()' %t && // RUN: clang-cc -triple i386-unknown-unknown -fvisibility=hidden -emit-llvm -o %t %s && // RUN: grep '@g_com = common hidden global i32 0' %t &&a // RUN: grep '@g_def = hidden global i32 0' %t && // RUN: grep '@g_ext = external global i32' %t && // RUN: grep '@g_deferred = internal global' %t && // RUN: grep 'declare void @f_ext()' %t && // RUN: grep 'define internal void @f_deferred()' %t && // RUN: grep 'define hidden i32 @f_def()' %t && // RUN: true int g_com; int g_def = 0; extern int g_ext; static char g_deferred[] = "hello"; extern void f_ext(void); static void f_deferred(void) { } int f_def(void) { f_ext(); f_deferred(); return g_com + g_def + g_ext + g_deferred[0]; } <file_sep>/include/clang/Parse/AccessSpecifier.h //===--- AccessSpecifier.h - C++ Access Specifiers -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines interfaces used for C++ access specifiers. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_ACCESS_SPECIFIER_H #define LLVM_CLANG_PARSE_ACCESS_SPECIFIER_H namespace clang { /// AccessSpecifier - A C++ access specifier (none, public, private, /// protected). enum AccessSpecifier { AS_none, AS_public, AS_protected, AS_private }; } // end namespace clang #endif <file_sep>/lib/Frontend/FixItRewriter.cpp //===--- FixItRewriter.cpp - Fix-It Rewriter Diagnostic Client --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a diagnostic client adaptor that performs rewrites as // suggested by code modification hints attached to diagnostics. It // then forwards any diagnostics to the adapted diagnostic client. // //===----------------------------------------------------------------------===// #include "clang/Frontend/FixItRewriter.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Support/Streams.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" using namespace clang; FixItRewriter::FixItRewriter(Diagnostic &Diags, SourceManager &SourceMgr, const LangOptions &LangOpts) : Diags(Diags), Rewrite(SourceMgr, LangOpts), NumFailures(0) { Client = Diags.getClient(); Diags.setClient(this); } FixItRewriter::~FixItRewriter() { Diags.setClient(Client); } bool FixItRewriter::WriteFixedFile(const std::string &InFileName, const std::string &OutFileName) { if (NumFailures > 0) { Diag(FullSourceLoc(), diag::warn_fixit_no_changes); return true; } llvm::OwningPtr<llvm::raw_ostream> OwnedStream; llvm::raw_ostream *OutFile; if (!OutFileName.empty()) { std::string Err; OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), // set binary mode (critical for Windoze) true, Err); OwnedStream.reset(OutFile); } else if (InFileName == "-") { OutFile = &llvm::outs(); } else { llvm::sys::Path Path(InFileName); std::string Suffix = Path.getSuffix(); Path.eraseSuffix(); Path.appendSuffix("fixit." + Suffix); std::string Err; OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), // set binary mode (critical for Windoze) true, Err); OwnedStream.reset(OutFile); } FileID MainFileID = Rewrite.getSourceMgr().getMainFileID(); if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(MainFileID)) { *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end()); } else { std::fprintf(stderr, "Main file is unchanged\n"); } OutFile->flush(); return false; } bool FixItRewriter::IncludeInDiagnosticCounts() const { return Client? Client->IncludeInDiagnosticCounts() : true; } void FixItRewriter::HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info) { Client->HandleDiagnostic(DiagLevel, Info); // Skip over any diagnostics that are ignored. if (DiagLevel == Diagnostic::Ignored) return; if (!FixItLocations.empty()) { // The user has specified the locations where we should perform // the various fix-it modifications. // If this diagnostic does not have any code modifications, // completely ignore it, even if it's an error: fix-it locations // are meant to perform specific fix-ups even in the presence of // other errors. if (Info.getNumCodeModificationHints() == 0) return; // See if the location of the error is one that matches what the // user requested. bool AcceptableLocation = false; const FileEntry *File = Rewrite.getSourceMgr().getFileEntryForID( Info.getLocation().getFileID()); unsigned Line = Info.getLocation().getSpellingLineNumber(); unsigned Column = Info.getLocation().getSpellingColumnNumber(); for (llvm::SmallVector<RequestedSourceLocation, 4>::iterator Loc = FixItLocations.begin(), LocEnd = FixItLocations.end(); Loc != LocEnd; ++Loc) { if (Loc->File == File && Loc->Line == Line && Loc->Column == Column) { AcceptableLocation = true; break; } } if (!AcceptableLocation) return; } // Make sure that we can perform all of the modifications we // in this diagnostic. bool CanRewrite = Info.getNumCodeModificationHints() > 0; for (unsigned Idx = 0, Last = Info.getNumCodeModificationHints(); Idx < Last; ++Idx) { const CodeModificationHint &Hint = Info.getCodeModificationHint(Idx); if (Hint.RemoveRange.isValid() && Rewrite.getRangeSize(Hint.RemoveRange) == -1) { CanRewrite = false; break; } if (Hint.InsertionLoc.isValid() && !Rewrite.isRewritable(Hint.InsertionLoc)) { CanRewrite = false; break; } } if (!CanRewrite) { if (Info.getNumCodeModificationHints() > 0) Diag(Info.getLocation(), diag::note_fixit_in_macro); // If this was an error, refuse to perform any rewriting. if (DiagLevel == Diagnostic::Error || DiagLevel == Diagnostic::Fatal) { if (++NumFailures == 1) Diag(Info.getLocation(), diag::note_fixit_unfixed_error); } return; } bool Failed = false; for (unsigned Idx = 0, Last = Info.getNumCodeModificationHints(); Idx < Last; ++Idx) { const CodeModificationHint &Hint = Info.getCodeModificationHint(Idx); if (!Hint.RemoveRange.isValid()) { // We're adding code. if (Rewrite.InsertStrBefore(Hint.InsertionLoc, Hint.CodeToInsert)) Failed = true; continue; } if (Hint.CodeToInsert.empty()) { // We're removing code. if (Rewrite.RemoveText(Hint.RemoveRange.getBegin(), Rewrite.getRangeSize(Hint.RemoveRange))) Failed = true; continue; } // We're replacing code. if (Rewrite.ReplaceText(Hint.RemoveRange.getBegin(), Rewrite.getRangeSize(Hint.RemoveRange), Hint.CodeToInsert.c_str(), Hint.CodeToInsert.size())) Failed = true; } if (Failed) { ++NumFailures; Diag(Info.getLocation(), diag::note_fixit_failed); return; } Diag(Info.getLocation(), diag::note_fixit_applied); } /// \brief Emit a diagnostic via the adapted diagnostic client. void FixItRewriter::Diag(FullSourceLoc Loc, unsigned DiagID) { // When producing this diagnostic, we temporarily bypass ourselves, // clear out any current diagnostic, and let the downstream client // format the diagnostic. Diags.setClient(Client); Diags.Clear(); Diags.Report(Loc, DiagID); Diags.setClient(this); } <file_sep>/test/CodeGen/rdr-6098585-unsigned-caserange.c // RUN: clang-cc -triple i386-unknown-unknown --emit-llvm-bc -o - %s | opt -std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32" %t | count 1 && // RUN: grep "ret i32 3" %t | count 1 int f2(unsigned x) { switch(x) { default: return 3; case 0xFFFFFFFF ... 1: // This range should be empty because x is unsigned. return 0; } } <file_sep>/test/CodeGen/var-align.c // RUN: clang-cc -emit-llvm %s -o - | grep "align 16" | count 2 __attribute((aligned(16))) float a[128]; union {int a[4]; __attribute((aligned(16))) float b[4];} u; <file_sep>/test/SemaCXX/constructor-initializer.cpp // RUN: clang-cc -fsyntax-only -verify %s class A { int m; }; class B : public A { public: B() : A(), m(1), n(3.14) { } private: int m; float n; }; class C : public virtual B { public: C() : B() { } }; class D : public C { public: D() : B(), C() { } }; class E : public D, public B { public: E() : B(), D() { } // expected-error{{base class initializer 'B' names both a direct base class and an inherited virtual base class}} }; typedef int INT; class F : public B { public: int B; F() : B(17), m(17), // expected-error{{member initializer 'm' does not name a non-static data member or base class}} INT(17) // expected-error{{constructor initializer 'INT' (aka 'int') does not name a class}} { } }; class G : A { G() : A(10); // expected-error{{expected '{'}} }; void f() : a(242) { } // expected-error{{only constructors take base initializers}} class H : A { H(); }; H::H() : A(10) { } <file_sep>/tools/clang-cc/AnalysisConsumer.cpp //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // "Meta" ASTConsumer for running different source analyses. // //===----------------------------------------------------------------------===// #include "ASTConsumers.h" #include "clang/Frontend/PathDiagnosticClients.h" #include "clang/Frontend/ManagerRegistry.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/OwningPtr.h" #include "clang/AST/CFG.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "clang/Analysis/PathDiagnostic.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/FileManager.h" #include "clang/AST/ParentMap.h" #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "clang/Analysis/LocalCheckers.h" #include "clang/Analysis/PathSensitive/GRTransferFuncs.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Streams.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" using namespace clang; static ExplodedNodeImpl::Auditor* CreateUbiViz(); //===----------------------------------------------------------------------===// // Analyzer Options: available analyses. //===----------------------------------------------------------------------===// /// Analysis - Set of available source code analyses. enum Analyses { #define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE) NAME, #include "Analyses.def" NumAnalyses }; static llvm::cl::list<Analyses> AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"), llvm::cl::values( #define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\ clEnumValN(NAME, CMDFLAG, DESC), #include "Analyses.def" clEnumValEnd)); //===----------------------------------------------------------------------===// // Analyzer Options: store model. //===----------------------------------------------------------------------===// /// AnalysisStores - Set of available analysis store models. enum AnalysisStores { #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) NAME##Model, #include "Analyses.def" NumStores }; static llvm::cl::opt<AnalysisStores> AnalysisStoreOpt("analyzer-store", llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"), llvm::cl::init(BasicStoreModel), llvm::cl::values( #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\ clEnumValN(NAME##Model, CMDFLAG, DESC), #include "Analyses.def" clEnumValEnd)); //===----------------------------------------------------------------------===// // Analyzer Options: constraint engines. //===----------------------------------------------------------------------===// /// AnalysisConstraints - Set of available constraint models. enum AnalysisConstraints { #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) NAME##Model, #include "Analyses.def" NumConstraints }; static llvm::cl::opt<AnalysisConstraints> AnalysisConstraintsOpt("analyzer-constraints", llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"), llvm::cl::init(RangeConstraintsModel), llvm::cl::values( #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\ clEnumValN(NAME##Model, CMDFLAG, DESC), #include "Analyses.def" clEnumValEnd)); //===----------------------------------------------------------------------===// // Analyzer Options: diagnostic clients. //===----------------------------------------------------------------------===// /// AnalysisDiagClients - Set of available diagnostic clients for rendering /// analysis results. enum AnalysisDiagClients { #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREAT) PD_##NAME, #include "Analyses.def" NUM_ANALYSIS_DIAG_CLIENTS }; static llvm::cl::opt<AnalysisDiagClients> AnalysisDiagOpt("analyzer-output", llvm::cl::desc("Source Code Analysis - Output Options"), llvm::cl::init(PD_HTML), llvm::cl::values( #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\ clEnumValN(PD_##NAME, CMDFLAG, DESC), #include "Analyses.def" clEnumValEnd)); //===----------------------------------------------------------------------===// // Misc. fun options. //===----------------------------------------------------------------------===// static llvm::cl::opt<bool> VisualizeEGDot("analyzer-viz-egraph-graphviz", llvm::cl::desc("Display exploded graph using GraphViz")); static llvm::cl::opt<bool> VisualizeEGUbi("analyzer-viz-egraph-ubigraph", llvm::cl::desc("Display exploded graph using Ubigraph")); static llvm::cl::opt<bool> AnalyzeAll("analyzer-opt-analyze-headers", llvm::cl::desc("Force the static analyzer to analyze " "functions defined in header files")); static llvm::cl::opt<bool> AnalyzerDisplayProgress("analyzer-display-progress", llvm::cl::desc("Emit verbose output about the analyzer's progress.")); static llvm::cl::opt<bool> PurgeDead("analyzer-purge-dead", llvm::cl::init(true), llvm::cl::desc("Remove dead symbols, bindings, and constraints before" " processing a statement.")); static llvm::cl::opt<bool> EagerlyAssume("analyzer-eagerly-assume", llvm::cl::init(false), llvm::cl::desc("Eagerly assume the truth/falseness of some " "symbolic constraints.")); static llvm::cl::opt<std::string> AnalyzeSpecificFunction("analyze-function", llvm::cl::desc("Run analysis on specific function")); static llvm::cl::opt<bool> TrimGraph("trim-egraph", llvm::cl::desc("Only show error-related paths in the analysis graph")); //===----------------------------------------------------------------------===// // Basic type definitions. //===----------------------------------------------------------------------===// namespace { class AnalysisManager; typedef void (*CodeAction)(AnalysisManager& Mgr); } // end anonymous namespace //===----------------------------------------------------------------------===// // AnalysisConsumer declaration. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN AnalysisConsumer : public ASTConsumer { typedef std::vector<CodeAction> Actions; Actions FunctionActions; Actions ObjCMethodActions; Actions ObjCImplementationActions; Actions TranslationUnitActions; public: const LangOptions& LOpts; Diagnostic &Diags; ASTContext* Ctx; Preprocessor* PP; PreprocessorFactory* PPF; const std::string OutDir; llvm::OwningPtr<PathDiagnosticClient> PD; AnalysisConsumer(Diagnostic &diags, Preprocessor* pp, PreprocessorFactory* ppf, const LangOptions& lopts, const std::string& outdir) : LOpts(lopts), Diags(diags), Ctx(0), PP(pp), PPF(ppf), OutDir(outdir) {} void addCodeAction(CodeAction action) { FunctionActions.push_back(action); ObjCMethodActions.push_back(action); } void addObjCImplementationAction(CodeAction action) { ObjCImplementationActions.push_back(action); } void addTranslationUnitAction(CodeAction action) { TranslationUnitActions.push_back(action); } virtual void Initialize(ASTContext &Context) { Ctx = &Context; } virtual void HandleTopLevelDecl(DeclGroupRef D) { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) HandleTopLevelSingleDecl(*I); } void HandleTopLevelSingleDecl(Decl *D); virtual void HandleTranslationUnit(ASTContext &C); void HandleCode(Decl* D, Stmt* Body, Actions& actions); }; class VISIBILITY_HIDDEN AnalysisManager : public BugReporterData { Decl* D; Stmt* Body; enum AnalysisScope { ScopeTU, ScopeDecl } AScope; AnalysisConsumer& C; bool DisplayedFunction; llvm::OwningPtr<CFG> cfg; llvm::OwningPtr<LiveVariables> liveness; llvm::OwningPtr<ParentMap> PM; // Configurable components creators. StoreManagerCreator CreateStoreMgr; ConstraintManagerCreator CreateConstraintMgr; public: AnalysisManager(AnalysisConsumer& c, Decl* d, Stmt* b, bool displayProgress) : D(d), Body(b), AScope(ScopeDecl), C(c), DisplayedFunction(!displayProgress) { setManagerCreators(); } AnalysisManager(AnalysisConsumer& c, bool displayProgress) : D(0), Body(0), AScope(ScopeTU), C(c), DisplayedFunction(!displayProgress) { setManagerCreators(); } Decl* getCodeDecl() const { assert (AScope == ScopeDecl); return D; } Stmt* getBody() const { assert (AScope == ScopeDecl); return Body; } StoreManagerCreator getStoreManagerCreator() { return CreateStoreMgr; }; ConstraintManagerCreator getConstraintManagerCreator() { return CreateConstraintMgr; } virtual CFG* getCFG() { if (!cfg) cfg.reset(CFG::buildCFG(getBody())); return cfg.get(); } virtual ParentMap& getParentMap() { if (!PM) PM.reset(new ParentMap(getBody())); return *PM.get(); } virtual ASTContext& getContext() { return *C.Ctx; } virtual SourceManager& getSourceManager() { return getContext().getSourceManager(); } virtual Diagnostic& getDiagnostic() { return C.Diags; } const LangOptions& getLangOptions() const { return C.LOpts; } virtual PathDiagnosticClient* getPathDiagnosticClient() { if (C.PD.get() == 0 && !C.OutDir.empty()) { switch (AnalysisDiagOpt) { default: #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE)\ case PD_##NAME: C.PD.reset(CREATEFN(C.OutDir, C.PP, C.PPF)); break; #include "Analyses.def" } } return C.PD.get(); } virtual LiveVariables* getLiveVariables() { if (!liveness) { CFG* c = getCFG(); if (!c) return 0; liveness.reset(new LiveVariables(getContext(), *c)); liveness->runOnCFG(*c); liveness->runOnAllBlocks(*c, 0, true); } return liveness.get(); } bool shouldVisualizeGraphviz() const { return VisualizeEGDot; } bool shouldVisualizeUbigraph() const { return VisualizeEGUbi; } bool shouldVisualize() const { return VisualizeEGDot || VisualizeEGUbi; } bool shouldTrimGraph() const { return TrimGraph; } void DisplayFunction() { if (DisplayedFunction) return; DisplayedFunction = true; // FIXME: Is getCodeDecl() always a named decl? if (isa<FunctionDecl>(getCodeDecl()) || isa<ObjCMethodDecl>(getCodeDecl())) { NamedDecl *ND = cast<NamedDecl>(getCodeDecl()); SourceManager &SM = getContext().getSourceManager(); llvm::cerr << "ANALYZE: " << SM.getPresumedLoc(ND->getLocation()).getFilename() << ' ' << ND->getNameAsString() << '\n'; } } private: /// Set configurable analyzer components creators. First check if there are /// components registered at runtime. Otherwise fall back to builtin /// components. void setManagerCreators() { if (ManagerRegistry::StoreMgrCreator != 0) { CreateStoreMgr = ManagerRegistry::StoreMgrCreator; } else { switch (AnalysisStoreOpt) { default: assert(0 && "Unknown store manager."); #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ case NAME##Model: CreateStoreMgr = CREATEFN; break; #include "Analyses.def" } } if (ManagerRegistry::ConstraintMgrCreator != 0) CreateConstraintMgr = ManagerRegistry::ConstraintMgrCreator; else { switch (AnalysisConstraintsOpt) { default: assert(0 && "Unknown store manager."); #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ case NAME##Model: CreateConstraintMgr = CREATEFN; break; #include "Analyses.def" } } // Some DiagnosticClients should be created all the time instead of // lazily. Create those now. switch (AnalysisDiagOpt) { default: break; #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE)\ case PD_##NAME: if (AUTOCREATE) getPathDiagnosticClient(); break; #include "Analyses.def" } } }; } // end anonymous namespace namespace llvm { template <> struct FoldingSetTrait<CodeAction> { static inline void Profile(CodeAction X, FoldingSetNodeID& ID) { ID.AddPointer(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(X))); } }; } //===----------------------------------------------------------------------===// // AnalysisConsumer implementation. //===----------------------------------------------------------------------===// void AnalysisConsumer::HandleTopLevelSingleDecl(Decl *D) { switch (D->getKind()) { case Decl::Function: { FunctionDecl* FD = cast<FunctionDecl>(D); if (AnalyzeSpecificFunction.size() > 0 && AnalyzeSpecificFunction != FD->getIdentifier()->getName()) break; Stmt* Body = FD->getBody(); if (Body) HandleCode(FD, Body, FunctionActions); break; } case Decl::ObjCMethod: { ObjCMethodDecl* MD = cast<ObjCMethodDecl>(D); if (AnalyzeSpecificFunction.size() > 0 && AnalyzeSpecificFunction != MD->getSelector().getAsString()) return; Stmt* Body = MD->getBody(); if (Body) HandleCode(MD, Body, ObjCMethodActions); break; } default: break; } } void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { if(!TranslationUnitActions.empty()) { AnalysisManager mgr(*this, AnalyzerDisplayProgress); for (Actions::iterator I = TranslationUnitActions.begin(), E = TranslationUnitActions.end(); I != E; ++I) (*I)(mgr); } if (!ObjCImplementationActions.empty()) { TranslationUnitDecl *TUD = C.getTranslationUnitDecl(); for (DeclContext::decl_iterator I = TUD->decls_begin(C), E = TUD->decls_end(C); I != E; ++I) if (ObjCImplementationDecl* ID = dyn_cast<ObjCImplementationDecl>(*I)) HandleCode(ID, 0, ObjCImplementationActions); } // Delete the PathDiagnosticClient here just in case the AnalysisConsumer // object doesn't get released. This will cause any side-effects in the // destructor of the PathDiagnosticClient to get executed. PD.reset(); } void AnalysisConsumer::HandleCode(Decl* D, Stmt* Body, Actions& actions) { // Don't run the actions if an error has occured with parsing the file. if (Diags.hasErrorOccurred()) return; // Don't run the actions on declarations in header files unless // otherwise specified. if (!AnalyzeAll && !Ctx->getSourceManager().isFromMainFile(D->getLocation())) return; // Create an AnalysisManager that will manage the state for analyzing // this method/function. AnalysisManager mgr(*this, D, Body, AnalyzerDisplayProgress); // Dispatch on the actions. for (Actions::iterator I = actions.begin(), E = actions.end(); I != E; ++I) (*I)(mgr); } //===----------------------------------------------------------------------===// // Analyses //===----------------------------------------------------------------------===// static void ActionWarnDeadStores(AnalysisManager& mgr) { if (LiveVariables* L = mgr.getLiveVariables()) { BugReporter BR(mgr); CheckDeadStores(*L, BR); } } static void ActionWarnUninitVals(AnalysisManager& mgr) { if (CFG* c = mgr.getCFG()) CheckUninitializedValues(*c, mgr.getContext(), mgr.getDiagnostic()); } static void ActionGRExprEngine(AnalysisManager& mgr, GRTransferFuncs* tf, bool StandardWarnings = true) { llvm::OwningPtr<GRTransferFuncs> TF(tf); // Display progress. mgr.DisplayFunction(); // Construct the analysis engine. LiveVariables* L = mgr.getLiveVariables(); if (!L) return; GRExprEngine Eng(*mgr.getCFG(), *mgr.getCodeDecl(), mgr.getContext(), *L, mgr, PurgeDead, EagerlyAssume, mgr.getStoreManagerCreator(), mgr.getConstraintManagerCreator()); Eng.setTransferFunctions(tf); if (StandardWarnings) { Eng.RegisterInternalChecks(); RegisterAppleChecks(Eng); } // Set the graph auditor. llvm::OwningPtr<ExplodedNodeImpl::Auditor> Auditor; if (mgr.shouldVisualizeUbigraph()) { Auditor.reset(CreateUbiViz()); ExplodedNodeImpl::SetAuditor(Auditor.get()); } // Execute the worklist algorithm. Eng.ExecuteWorkList(); // Release the auditor (if any) so that it doesn't monitor the graph // created BugReporter. ExplodedNodeImpl::SetAuditor(0); // Visualize the exploded graph. if (mgr.shouldVisualizeGraphviz()) Eng.ViewGraph(mgr.shouldTrimGraph()); // Display warnings. Eng.getBugReporter().FlushReports(); } static void ActionCheckerCFRefAux(AnalysisManager& mgr, bool GCEnabled, bool StandardWarnings) { GRTransferFuncs* TF = MakeCFRefCountTF(mgr.getContext(), GCEnabled, mgr.getLangOptions()); ActionGRExprEngine(mgr, TF, StandardWarnings); } static void ActionCheckerCFRef(AnalysisManager& mgr) { switch (mgr.getLangOptions().getGCMode()) { default: assert (false && "Invalid GC mode."); case LangOptions::NonGC: ActionCheckerCFRefAux(mgr, false, true); break; case LangOptions::GCOnly: ActionCheckerCFRefAux(mgr, true, true); break; case LangOptions::HybridGC: ActionCheckerCFRefAux(mgr, false, true); ActionCheckerCFRefAux(mgr, true, false); break; } } static void ActionCheckerSimple(AnalysisManager& mgr) { ActionGRExprEngine(mgr, MakeGRSimpleValsTF()); } static void ActionDisplayLiveVariables(AnalysisManager& mgr) { if (LiveVariables* L = mgr.getLiveVariables()) { mgr.DisplayFunction(); L->dumpBlockLiveness(mgr.getSourceManager()); } } static void ActionCFGDump(AnalysisManager& mgr) { if (CFG* c = mgr.getCFG()) { mgr.DisplayFunction(); c->dump(); } } static void ActionCFGView(AnalysisManager& mgr) { if (CFG* c = mgr.getCFG()) { mgr.DisplayFunction(); c->viewCFG(); } } static void ActionWarnObjCDealloc(AnalysisManager& mgr) { if (mgr.getLangOptions().getGCMode() == LangOptions::GCOnly) return; BugReporter BR(mgr); CheckObjCDealloc(cast<ObjCImplementationDecl>(mgr.getCodeDecl()), mgr.getLangOptions(), BR); } static void ActionWarnObjCUnusedIvars(AnalysisManager& mgr) { BugReporter BR(mgr); CheckObjCUnusedIvar(cast<ObjCImplementationDecl>(mgr.getCodeDecl()), BR); } static void ActionWarnObjCMethSigs(AnalysisManager& mgr) { BugReporter BR(mgr); CheckObjCInstMethSignature(cast<ObjCImplementationDecl>(mgr.getCodeDecl()), BR); } //===----------------------------------------------------------------------===// // AnalysisConsumer creation. //===----------------------------------------------------------------------===// ASTConsumer* clang::CreateAnalysisConsumer(Diagnostic &diags, Preprocessor* pp, PreprocessorFactory* ppf, const LangOptions& lopts, const std::string& OutDir) { llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(diags, pp, ppf, lopts, OutDir)); for (unsigned i = 0; i < AnalysisList.size(); ++i) switch (AnalysisList[i]) { #define ANALYSIS(NAME, CMD, DESC, SCOPE)\ case NAME:\ C->add ## SCOPE ## Action(&Action ## NAME);\ break; #include "Analyses.def" default: break; } return C.take(); } //===----------------------------------------------------------------------===// // Ubigraph Visualization. FIXME: Move to separate file. //===----------------------------------------------------------------------===// namespace { class UbigraphViz : public ExplodedNodeImpl::Auditor { llvm::OwningPtr<llvm::raw_ostream> Out; llvm::sys::Path Dir, Filename; unsigned Cntr; typedef llvm::DenseMap<void*,unsigned> VMap; VMap M; public: UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir, llvm::sys::Path& filename); ~UbigraphViz(); virtual void AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst); }; } // end anonymous namespace static ExplodedNodeImpl::Auditor* CreateUbiViz() { std::string ErrMsg; llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); if (!ErrMsg.empty()) return 0; llvm::sys::Path Filename = Dir; Filename.appendComponent("llvm_ubi"); Filename.makeUnique(true,&ErrMsg); if (!ErrMsg.empty()) return 0; llvm::cerr << "Writing '" << Filename << "'.\n"; llvm::OwningPtr<llvm::raw_fd_ostream> Stream; std::string filename = Filename.toString(); Stream.reset(new llvm::raw_fd_ostream(filename.c_str(), false, ErrMsg)); if (!ErrMsg.empty()) return 0; return new UbigraphViz(Stream.take(), Dir, Filename); } void UbigraphViz::AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst) { assert (Src != Dst && "Self-edges are not allowed."); // Lookup the Src. If it is a new node, it's a root. VMap::iterator SrcI= M.find(Src); unsigned SrcID; if (SrcI == M.end()) { M[Src] = SrcID = Cntr++; *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; } else SrcID = SrcI->second; // Lookup the Dst. VMap::iterator DstI= M.find(Dst); unsigned DstID; if (DstI == M.end()) { M[Dst] = DstID = Cntr++; *Out << "('vertex', " << DstID << ")\n"; } else { // We have hit DstID before. Change its style to reflect a cache hit. DstID = DstI->second; *Out << "('change_vertex_style', " << DstID << ", 1)\n"; } // Add the edge. *Out << "('edge', " << SrcID << ", " << DstID << ", ('arrow','true'), ('oriented', 'true'))\n"; } UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir, llvm::sys::Path& filename) : Out(out), Dir(dir), Filename(filename), Cntr(0) { *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," " ('size', '1.5'))\n"; } UbigraphViz::~UbigraphViz() { Out.reset(0); llvm::cerr << "Running 'ubiviz' program... "; std::string ErrMsg; llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); std::vector<const char*> args; args.push_back(Ubiviz.c_str()); args.push_back(Filename.c_str()); args.push_back(0); if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { llvm::cerr << "Error viewing graph: " << ErrMsg << "\n"; } // Delete the directory. Dir.eraseFromDisk(true); } <file_sep>/tools/ccc/test/ccc/darwin-pic.c // RUN: xcc -ccc-host-system darwin -ccc-host-machine i386 -m32 -S %s -o - | grep 'L_g0$non_lazy_ptr-' && // RUN: xcc -ccc-host-system darwin -ccc-host-machine i386 -m32 -S %s -o - -fPIC | grep 'L_g0$non_lazy_ptr-' && // RUN: xcc -ccc-host-system darwin -ccc-host-machine i386 -m32 -S %s -o - -mdynamic-no-pic | grep 'L_g0$non_lazy_ptr,' && // RUN: xcc -ccc-host-system darwin -ccc-host-machine i386 -m32 -S %s -o - -static | grep 'non_lazy_ptr' | count 0 && // RUN: xcc -ccc-host-system darwin -ccc-host-machine i386 -m64 -S %s -o - | grep '_g0@GOTPCREL' && // RUN: xcc -ccc-host-system darwin -ccc-host-machine i386 -m64 -S %s -o - -fPIC | grep '_g0@GOTPCREL' && // RUN: xcc -ccc-host-system darwin -ccc-host-machine i386 -m64 -S %s -o - -mdynamic-no-pic | grep '_g0@GOTPCREL' && // RUN: xcc -ccc-host-system darwin -ccc-host-machine i386 -m64 -S %s -o - -static | grep '_g0@GOTPCREL' int g0; int f0() { return g0; } <file_sep>/test/CodeGen/address-space.c // RUN: clang-cc -emit-llvm < %s | grep '@foo.*global.*addrspace(1)' && // RUN: clang-cc -emit-llvm < %s | grep '@ban.*global.*addrspace(1)' && // RUN: clang-cc -emit-llvm < %s | grep 'load.*addrspace(1)' | count 2 && // RUN: clang-cc -emit-llvm < %s | grep 'load.*addrspace(2).. @A' && // RUN: clang-cc -emit-llvm < %s | grep 'load.*addrspace(2).. @B' int foo __attribute__((address_space(1))); int ban[10] __attribute__((address_space(1))); int bar() { return foo; } int baz(int i) { return ban[i]; } // Both A and B point into addrspace(2). __attribute__((address_space(2))) int *A, *B; void test3() { *A = *B; } <file_sep>/test/Driver/pth.c // Test transparent PTH support. // RUN: clang -x c-header %s -o %t.h.pch -### 2> %t.log && // RUN: grep '".*/clang-cc" .* "-o" ".*\.h\.pch" "-x" "c-header" ".*pth\.c"' %t.log && // RUN: touch %t.h.pth && // RUN: clang -E -include %t.h %s -### 2> %t.log && // RUN: grep '".*/clang-cc" .*"-include-pth" ".*\.h\.pth" .*"-x" "c" ".*pth\.c"' %t.log <file_sep>/TODO.txt //===---------------------------------------------------------------------===// // Minor random things that can be improved //===---------------------------------------------------------------------===// Warn about "X && 0x1000" saying that the user may mean "X & 0x1000". We should do this for any immediate except zero, so long as it doesn't come from a macro expansion. Likewise for ||. //===---------------------------------------------------------------------===// Lexer-related diagnostics should point to the problematic character, not the start of the token. For example: int y = 0000\ 00080; diag.c:4:9: error: invalid digit '8' in octal constant int y = 0000\ ^ should be: diag.c:4:9: error: invalid digit '8' in octal constant 00080; ^ This specific diagnostic is implemented, but others should be updated. //===---------------------------------------------------------------------===// C++ (checker): For iterators, warn of the use of "iterator++" instead of "++iterator" when when the value returned by operator++(int) is ignored. //===---------------------------------------------------------------------===// We want to keep more source range information in Declarator to help produce better diagnostics. Declarator::getSourceRange() should be implemented to give a range for the whole declarator with all of its specifiers, and DeclaratorChunk::ParamInfo should also have a source range covering the whole parameter, so that an error message like this: overloaded-operator-decl.cpp:37:23: error: parameter of overloaded post-increment operator must have type 'int' (not 'float') X operator++(X&, const float& f); ^ can be turned into something like this: overloaded-operator-decl.cpp:37:23: error: parameter of overloaded post-increment operator must have type 'int' (not 'float') X operator++(X&, const float& f); ^ ~~~~~~~~~~~~~~ //===---------------------------------------------------------------------===// For terminal output, we should consider limiting the amount of diagnostic text we print once the first error has been encountered. For example, once we have produced an error diagnostic, we should only continue producing diagnostics until we have produced a page full of results (say, 50 lines of text). Beyond that, (1) the remaining errors are likely to be less interesting, and (2) the poor user has to scroll his terminal to find out where things went wrong. //===---------------------------------------------------------------------===// More ideas for code modification hints: - If no member of a given name is found in a class/struct, search through the names of entities that do exist in the class and suggest the closest candidate. e.g., if I write "DS.setTypeSpecType", it would suggest "DS.SetTypeSpecType" (edit distance = 1). - If a class member is defined out-of-line but isn't in the class declaration (and there are no close matches!), provide the option to add an in-class declaration. - Fix-it hints for the inclusion of headers when needed for particular features (e.g., <typeinfo> for typeid) - Change "foo.bar" to "foo->bar" when "foo" is a pointer. <file_sep>/lib/Analysis/SymbolManager.cpp //== SymbolManager.h - Management of Symbolic Values ------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines SymbolManager, a class that manages symbolic values // created for use by GRExprEngine and related classes. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/SymbolManager.h" #include "clang/Analysis/PathSensitive/MemRegion.h" #include "llvm/Support/raw_ostream.h" using namespace clang; static void print(llvm::raw_ostream& os, const SymExpr *SE); static void print(llvm::raw_ostream& os, BinaryOperator::Opcode Op) { switch (Op) { default: assert(false && "operator printing not implemented"); break; case BinaryOperator::Mul: os << '*' ; break; case BinaryOperator::Div: os << '/' ; break; case BinaryOperator::Rem: os << '%' ; break; case BinaryOperator::Add: os << '+' ; break; case BinaryOperator::Sub: os << '-' ; break; case BinaryOperator::Shl: os << "<<" ; break; case BinaryOperator::Shr: os << ">>" ; break; case BinaryOperator::LT: os << "<" ; break; case BinaryOperator::GT: os << '>' ; break; case BinaryOperator::LE: os << "<=" ; break; case BinaryOperator::GE: os << ">=" ; break; case BinaryOperator::EQ: os << "==" ; break; case BinaryOperator::NE: os << "!=" ; break; case BinaryOperator::And: os << '&' ; break; case BinaryOperator::Xor: os << '^' ; break; case BinaryOperator::Or: os << '|' ; break; } } static void print(llvm::raw_ostream& os, const SymIntExpr *SE) { os << '('; print(os, SE->getLHS()); os << ") "; print(os, SE->getOpcode()); os << ' ' << SE->getRHS().getZExtValue(); if (SE->getRHS().isUnsigned()) os << 'U'; } static void print(llvm::raw_ostream& os, const SymSymExpr *SE) { os << '('; print(os, SE->getLHS()); os << ") "; os << '('; print(os, SE->getRHS()); os << ')'; } static void print(llvm::raw_ostream& os, const SymExpr *SE) { switch (SE->getKind()) { case SymExpr::BEGIN_SYMBOLS: case SymExpr::RegionRValue: case SymExpr::ConjuredKind: case SymExpr::END_SYMBOLS: os << '$' << cast<SymbolData>(SE)->getSymbolID(); return; case SymExpr::SymIntKind: print(os, cast<SymIntExpr>(SE)); return; case SymExpr::SymSymKind: print(os, cast<SymSymExpr>(SE)); return; } } llvm::raw_ostream& llvm::operator<<(llvm::raw_ostream& os, const SymExpr *SE) { print(os, SE); return os; } std::ostream& std::operator<<(std::ostream& os, const SymExpr *SE) { llvm::raw_os_ostream O(os); print(O, SE); return os; } const SymbolRegionRValue* SymbolManager::getRegionRValueSymbol(const MemRegion* R) { llvm::FoldingSetNodeID profile; SymbolRegionRValue::Profile(profile, R); void* InsertPos; SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos); if (!SD) { SD = (SymExpr*) BPAlloc.Allocate<SymbolRegionRValue>(); new (SD) SymbolRegionRValue(SymbolCounter, R); DataSet.InsertNode(SD, InsertPos); ++SymbolCounter; } return cast<SymbolRegionRValue>(SD); } const SymbolConjured* SymbolManager::getConjuredSymbol(const Stmt* E, QualType T, unsigned Count, const void* SymbolTag) { llvm::FoldingSetNodeID profile; SymbolConjured::Profile(profile, E, T, Count, SymbolTag); void* InsertPos; SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos); if (!SD) { SD = (SymExpr*) BPAlloc.Allocate<SymbolConjured>(); new (SD) SymbolConjured(SymbolCounter, E, T, Count, SymbolTag); DataSet.InsertNode(SD, InsertPos); ++SymbolCounter; } return cast<SymbolConjured>(SD); } const SymIntExpr *SymbolManager::getSymIntExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& v, QualType t) { llvm::FoldingSetNodeID ID; SymIntExpr::Profile(ID, lhs, op, v, t); void *InsertPos; SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos); if (!data) { data = (SymIntExpr*) BPAlloc.Allocate<SymIntExpr>(); new (data) SymIntExpr(lhs, op, v, t); DataSet.InsertNode(data, InsertPos); } return cast<SymIntExpr>(data); } const SymSymExpr *SymbolManager::getSymSymExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t) { llvm::FoldingSetNodeID ID; SymSymExpr::Profile(ID, lhs, op, rhs, t); void *InsertPos; SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos); if (!data) { data = (SymSymExpr*) BPAlloc.Allocate<SymSymExpr>(); new (data) SymSymExpr(lhs, op, rhs, t); DataSet.InsertNode(data, InsertPos); } return cast<SymSymExpr>(data); } QualType SymbolConjured::getType(ASTContext&) const { return T; } QualType SymbolRegionRValue::getType(ASTContext& C) const { if (const TypedRegion* TR = dyn_cast<TypedRegion>(R)) return TR->getRValueType(C); return QualType(); } SymbolManager::~SymbolManager() {} bool SymbolManager::canSymbolicate(QualType T) { return Loc::IsLocType(T) || T->isIntegerType(); } void SymbolReaper::markLive(SymbolRef sym) { TheLiving = F.Add(TheLiving, sym); TheDead = F.Remove(TheDead, sym); } bool SymbolReaper::maybeDead(SymbolRef sym) { if (isLive(sym)) return false; TheDead = F.Add(TheDead, sym); return true; } bool SymbolReaper::isLive(SymbolRef sym) { if (TheLiving.contains(sym)) return true; // Interogate the symbol. It may derive from an input value to // the analyzed function/method. return isa<SymbolRegionRValue>(sym); } SymbolVisitor::~SymbolVisitor() {} <file_sep>/lib/CodeGen/Mangle.cpp //===--- Mangle.cpp - Mangle C++ Names --------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements C++ name mangling according to the Itanium C++ ABI, // which is used in GCC 3.2 and newer (and many compilers that are // ABI-compatible with GCC): // // http://www.codesourcery.com/public/cxx-abi/abi.html // //===----------------------------------------------------------------------===// #include "Mangle.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" using namespace clang; namespace { class VISIBILITY_HIDDEN CXXNameMangler { ASTContext &Context; llvm::raw_ostream &Out; const CXXConstructorDecl *Ctor; CXXCtorType CtorType; public: CXXNameMangler(ASTContext &C, llvm::raw_ostream &os) : Context(C), Out(os), Ctor(0), CtorType(Ctor_Complete) { } bool mangle(const NamedDecl *D); void mangleGuardVariable(const VarDecl *D); void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type); private: bool mangleFunctionDecl(const FunctionDecl *FD); void mangleFunctionEncoding(const FunctionDecl *FD); void mangleName(const NamedDecl *ND); void mangleUnqualifiedName(const NamedDecl *ND); void mangleSourceName(const IdentifierInfo *II); void mangleLocalName(const NamedDecl *ND); void mangleNestedName(const NamedDecl *ND); void manglePrefix(const DeclContext *DC); void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity); void mangleCVQualifiers(unsigned Quals); void mangleType(QualType T); void mangleType(const BuiltinType *T); void mangleType(const FunctionType *T); void mangleBareFunctionType(const FunctionType *T, bool MangleReturnType); void mangleType(const TagType *T); void mangleType(const ArrayType *T); void mangleType(const MemberPointerType *T); void mangleType(const TemplateTypeParmType *T); void mangleType(const ObjCInterfaceType *T); void mangleExpression(Expr *E); void mangleCXXCtorType(CXXCtorType T); }; } static bool isInCLinkageSpecification(const Decl *D) { for (const DeclContext *DC = D->getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) return Linkage->getLanguage() == LinkageSpecDecl::lang_c; } return false; } bool CXXNameMangler::mangleFunctionDecl(const FunctionDecl *FD) { // Clang's "overloadable" attribute extension to C/C++ implies // name mangling (always). if (FD->hasAttr<OverloadableAttr>()) { ; // fall into mangling code unconditionally. } else if (// C functions are not mangled !Context.getLangOptions().CPlusPlus || // "main" is not mangled in C++ FD->isMain() || // No mangling in an "implicit extern C" header. Context.getSourceManager().getFileCharacteristic(FD->getLocation()) == SrcMgr::C_ExternCSystem || // No name mangling in a C linkage specification. isInCLinkageSpecification(FD)) return false; // If we get here, mangle the decl name! Out << "_Z"; mangleFunctionEncoding(FD); return true; } bool CXXNameMangler::mangle(const NamedDecl *D) { // Any decl can be declared with __asm("foo") on it, and this takes // precedence over all other naming in the .o file. if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) { // If we have an asm name, then we use it as the mangling. Out << '\01'; // LLVM IR Marker for __asm("foo") Out << ALA->getLabel(); return true; } // <mangled-name> ::= _Z <encoding> // ::= <data name> // ::= <special-name> // FIXME: Actually use a visitor to decode these? if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) return mangleFunctionDecl(FD); if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { if (!Context.getLangOptions().CPlusPlus || isInCLinkageSpecification(D) || D->getDeclContext()->isTranslationUnit()) return false; Out << "_Z"; mangleName(VD); return true; } return false; } void CXXNameMangler::mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type) { assert(!Ctor && "Ctor already set!"); Ctor = D; CtorType = Type; mangle(D); } void CXXNameMangler::mangleGuardVariable(const VarDecl *D) { // <special-name> ::= GV <object name> # Guard variable for one-time // # initialization Out << "_ZGV"; mangleName(D); } void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) { // <encoding> ::= <function name> <bare-function-type> mangleName(FD); mangleBareFunctionType(FD->getType()->getAsFunctionType(), false); } static bool isStdNamespace(const DeclContext *DC) { if (!DC->isNamespace() || !DC->getParent()->isTranslationUnit()) return false; const NamespaceDecl *NS = cast<NamespaceDecl>(DC); return NS->getOriginalNamespace()->getIdentifier()->isStr("std"); } void CXXNameMangler::mangleName(const NamedDecl *ND) { // <name> ::= <nested-name> // ::= <unscoped-name> // ::= <unscoped-template-name> <template-args> // ::= <local-name> # See Scope Encoding below // // <unscoped-name> ::= <unqualified-name> // ::= St <unqualified-name> # ::std:: if (ND->getDeclContext()->isTranslationUnit()) mangleUnqualifiedName(ND); else if (isStdNamespace(ND->getDeclContext())) { Out << "St"; mangleUnqualifiedName(ND); } else if (isa<FunctionDecl>(ND->getDeclContext())) mangleLocalName(ND); else mangleNestedName(ND); } void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND) { // <unqualified-name> ::= <operator-name> // ::= <ctor-dtor-name> // ::= <source-name> DeclarationName Name = ND->getDeclName(); switch (Name.getNameKind()) { case DeclarationName::Identifier: mangleSourceName(Name.getAsIdentifierInfo()); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: assert(false && "Can't mangle Objective-C selector names here!"); break; case DeclarationName::CXXConstructorName: if (ND == Ctor) // If the named decl is the C++ constructor we're mangling, use the // type we were given. mangleCXXCtorType(CtorType); else // Otherwise, use the complete constructor name. This is relevant if a // class with a constructor is declared within a constructor. mangleCXXCtorType(Ctor_Complete); break; case DeclarationName::CXXDestructorName: // <ctor-dtor-name> ::= D0 # deleting destructor // ::= D1 # complete object destructor // ::= D2 # base object destructor // // FIXME: We don't even have all of these destructors in the AST // yet. Out << "D0"; break; case DeclarationName::CXXConversionFunctionName: // <operator-name> ::= cv <type> # (cast) Out << "cv"; mangleType(Context.getCanonicalType(Name.getCXXNameType())); break; case DeclarationName::CXXOperatorName: mangleOperatorName(Name.getCXXOverloadedOperator(), cast<FunctionDecl>(ND)->getNumParams()); break; case DeclarationName::CXXUsingDirective: assert(false && "Can't mangle a using directive name!"); break; } } void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) { // <source-name> ::= <positive length number> <identifier> // <number> ::= [n] <non-negative decimal integer> // <identifier> ::= <unqualified source code identifier> Out << II->getLength() << II->getName(); } void CXXNameMangler::mangleNestedName(const NamedDecl *ND) { // <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E // ::= N [<CV-qualifiers>] <template-prefix> <template-args> E // FIXME: no template support Out << 'N'; if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) mangleCVQualifiers(Method->getTypeQualifiers()); manglePrefix(ND->getDeclContext()); mangleUnqualifiedName(ND); Out << 'E'; } void CXXNameMangler::mangleLocalName(const NamedDecl *ND) { // <local-name> := Z <function encoding> E <entity name> [<discriminator>] // := Z <function encoding> E s [<discriminator>] // <discriminator> := _ <non-negative number> Out << 'Z'; mangleFunctionEncoding(cast<FunctionDecl>(ND->getDeclContext())); Out << 'E'; mangleSourceName(ND->getIdentifier()); } void CXXNameMangler::manglePrefix(const DeclContext *DC) { // <prefix> ::= <prefix> <unqualified-name> // ::= <template-prefix> <template-args> // ::= <template-param> // ::= # empty // ::= <substitution> // FIXME: We only handle mangling of namespaces and classes at the moment. if (!DC->getParent()->isTranslationUnit()) manglePrefix(DC->getParent()); if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC)) mangleSourceName(Namespace->getIdentifier()); else if (const RecordDecl *Record = dyn_cast<RecordDecl>(DC)) mangleSourceName(Record->getIdentifier()); } void CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) { switch (OO) { // <operator-name> ::= nw # new case OO_New: Out << "nw"; break; // ::= na # new[] case OO_Array_New: Out << "na"; break; // ::= dl # delete case OO_Delete: Out << "dl"; break; // ::= da # delete[] case OO_Array_Delete: Out << "da"; break; // ::= ps # + (unary) // ::= pl # + case OO_Plus: Out << (Arity == 1? "ps" : "pl"); break; // ::= ng # - (unary) // ::= mi # - case OO_Minus: Out << (Arity == 1? "ng" : "mi"); break; // ::= ad # & (unary) // ::= an # & case OO_Amp: Out << (Arity == 1? "ad" : "an"); break; // ::= de # * (unary) // ::= ml # * case OO_Star: Out << (Arity == 1? "de" : "ml"); break; // ::= co # ~ case OO_Tilde: Out << "co"; break; // ::= dv # / case OO_Slash: Out << "dv"; break; // ::= rm # % case OO_Percent: Out << "rm"; break; // ::= or # | case OO_Pipe: Out << "or"; break; // ::= eo # ^ case OO_Caret: Out << "eo"; break; // ::= aS # = case OO_Equal: Out << "aS"; break; // ::= pL # += case OO_PlusEqual: Out << "pL"; break; // ::= mI # -= case OO_MinusEqual: Out << "mI"; break; // ::= mL # *= case OO_StarEqual: Out << "mL"; break; // ::= dV # /= case OO_SlashEqual: Out << "dV"; break; // ::= rM # %= case OO_PercentEqual: Out << "rM"; break; // ::= aN # &= case OO_AmpEqual: Out << "aN"; break; // ::= oR # |= case OO_PipeEqual: Out << "oR"; break; // ::= eO # ^= case OO_CaretEqual: Out << "eO"; break; // ::= ls # << case OO_LessLess: Out << "ls"; break; // ::= rs # >> case OO_GreaterGreater: Out << "rs"; break; // ::= lS # <<= case OO_LessLessEqual: Out << "lS"; break; // ::= rS # >>= case OO_GreaterGreaterEqual: Out << "rS"; break; // ::= eq # == case OO_EqualEqual: Out << "eq"; break; // ::= ne # != case OO_ExclaimEqual: Out << "ne"; break; // ::= lt # < case OO_Less: Out << "lt"; break; // ::= gt # > case OO_Greater: Out << "gt"; break; // ::= le # <= case OO_LessEqual: Out << "le"; break; // ::= ge # >= case OO_GreaterEqual: Out << "ge"; break; // ::= nt # ! case OO_Exclaim: Out << "nt"; break; // ::= aa # && case OO_AmpAmp: Out << "aa"; break; // ::= oo # || case OO_PipePipe: Out << "oo"; break; // ::= pp # ++ case OO_PlusPlus: Out << "pp"; break; // ::= mm # -- case OO_MinusMinus: Out << "mm"; break; // ::= cm # , case OO_Comma: Out << "cm"; break; // ::= pm # ->* case OO_ArrowStar: Out << "pm"; break; // ::= pt # -> case OO_Arrow: Out << "pt"; break; // ::= cl # () case OO_Call: Out << "cl"; break; // ::= ix # [] case OO_Subscript: Out << "ix"; break; // UNSUPPORTED: ::= qu # ? case OO_None: case NUM_OVERLOADED_OPERATORS: assert(false && "Not an overloaded operator"); break; } } void CXXNameMangler::mangleCVQualifiers(unsigned Quals) { // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const if (Quals & QualType::Restrict) Out << 'r'; if (Quals & QualType::Volatile) Out << 'V'; if (Quals & QualType::Const) Out << 'K'; } void CXXNameMangler::mangleType(QualType T) { // Only operate on the canonical type! T = Context.getCanonicalType(T); // FIXME: Should we have a TypeNodes.def to make this easier? (YES!) // <type> ::= <CV-qualifiers> <type> mangleCVQualifiers(T.getCVRQualifiers()); // ::= <builtin-type> if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) mangleType(BT); // ::= <function-type> else if (const FunctionType *FT = dyn_cast<FunctionType>(T.getTypePtr())) mangleType(FT); // ::= <class-enum-type> else if (const TagType *TT = dyn_cast<TagType>(T.getTypePtr())) mangleType(TT); // ::= <array-type> else if (const ArrayType *AT = dyn_cast<ArrayType>(T.getTypePtr())) mangleType(AT); // ::= <pointer-to-member-type> else if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) mangleType(MPT); // ::= <template-param> else if (const TemplateTypeParmType *TypeParm = dyn_cast<TemplateTypeParmType>(T.getTypePtr())) mangleType(TypeParm); // FIXME: ::= <template-template-param> <template-args> // FIXME: ::= <substitution> # See Compression below // ::= P <type> # pointer-to else if (const PointerType *PT = dyn_cast<PointerType>(T.getTypePtr())) { Out << 'P'; mangleType(PT->getPointeeType()); } // ::= R <type> # reference-to else if (const LValueReferenceType *RT = dyn_cast<LValueReferenceType>(T.getTypePtr())) { Out << 'R'; mangleType(RT->getPointeeType()); } // ::= O <type> # rvalue reference-to (C++0x) else if (const RValueReferenceType *RT = dyn_cast<RValueReferenceType>(T.getTypePtr())) { Out << 'O'; mangleType(RT->getPointeeType()); } // ::= C <type> # complex pair (C 2000) else if (const ComplexType *CT = dyn_cast<ComplexType>(T.getTypePtr())) { Out << 'C'; mangleType(CT->getElementType()); } else if (const VectorType *VT = dyn_cast<VectorType>(T.getTypePtr())) { // GNU extension: vector types Out << "U8__vector"; mangleType(VT->getElementType()); } else if (const ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(T.getTypePtr())) { mangleType(IT); } // FIXME: ::= G <type> # imaginary (C 2000) // FIXME: ::= U <source-name> <type> # vendor extended type qualifier else assert(false && "Cannot mangle unknown type"); } void CXXNameMangler::mangleType(const BuiltinType *T) { // <builtin-type> ::= v # void // ::= w # wchar_t // ::= b # bool // ::= c # char // ::= a # signed char // ::= h # unsigned char // ::= s # short // ::= t # unsigned short // ::= i # int // ::= j # unsigned int // ::= l # long // ::= m # unsigned long // ::= x # long long, __int64 // ::= y # unsigned long long, __int64 // ::= n # __int128 // UNSUPPORTED: ::= o # unsigned __int128 // ::= f # float // ::= d # double // ::= e # long double, __float80 // UNSUPPORTED: ::= g # __float128 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) // UNSUPPORTED: ::= Dh # IEEE 754r half-precision floating point (16 bits) // UNSUPPORTED: ::= Di # char32_t // UNSUPPORTED: ::= Ds # char16_t // ::= u <source-name> # vendor extended type switch (T->getKind()) { case BuiltinType::Void: Out << 'v'; break; case BuiltinType::Bool: Out << 'b'; break; case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break; case BuiltinType::UChar: Out << 'h'; break; case BuiltinType::UShort: Out << 't'; break; case BuiltinType::UInt: Out << 'j'; break; case BuiltinType::ULong: Out << 'm'; break; case BuiltinType::ULongLong: Out << 'y'; break; case BuiltinType::SChar: Out << 'a'; break; case BuiltinType::WChar: Out << 'w'; break; case BuiltinType::Short: Out << 's'; break; case BuiltinType::Int: Out << 'i'; break; case BuiltinType::Long: Out << 'l'; break; case BuiltinType::LongLong: Out << 'x'; break; case BuiltinType::Float: Out << 'f'; break; case BuiltinType::Double: Out << 'd'; break; case BuiltinType::LongDouble: Out << 'e'; break; case BuiltinType::Overload: case BuiltinType::Dependent: assert(false && "Overloaded and dependent types shouldn't get to name mangling"); break; } } void CXXNameMangler::mangleType(const FunctionType *T) { // <function-type> ::= F [Y] <bare-function-type> E Out << 'F'; // FIXME: We don't have enough information in the AST to produce the // 'Y' encoding for extern "C" function types. mangleBareFunctionType(T, /*MangleReturnType=*/true); Out << 'E'; } void CXXNameMangler::mangleBareFunctionType(const FunctionType *T, bool MangleReturnType) { // <bare-function-type> ::= <signature type>+ if (MangleReturnType) mangleType(T->getResultType()); const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T); assert(Proto && "Can't mangle K&R function prototypes"); if (Proto->getNumArgs() == 0) { Out << 'v'; return; } for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(), ArgEnd = Proto->arg_type_end(); Arg != ArgEnd; ++Arg) mangleType(*Arg); // <builtin-type> ::= z # ellipsis if (Proto->isVariadic()) Out << 'z'; } void CXXNameMangler::mangleType(const TagType *T) { // <class-enum-type> ::= <name> if (!T->getDecl()->getIdentifier()) mangleName(T->getDecl()->getTypedefForAnonDecl()); else mangleName(T->getDecl()); } void CXXNameMangler::mangleType(const ArrayType *T) { // <array-type> ::= A <positive dimension number> _ <element type> // ::= A [<dimension expression>] _ <element type> Out << 'A'; if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) Out << CAT->getSize(); else if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(T)) mangleExpression(VAT->getSizeExpr()); else if (const DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(T)) mangleExpression(DSAT->getSizeExpr()); Out << '_'; mangleType(T->getElementType()); } void CXXNameMangler::mangleType(const MemberPointerType *T) { // <pointer-to-member-type> ::= M <class type> <member type> Out << 'M'; mangleType(QualType(T->getClass(), 0)); mangleType(T->getPointeeType()); } void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { // <template-param> ::= T_ # first template parameter // ::= T <parameter-2 non-negative number> _ if (T->getIndex() == 0) Out << "T_"; else Out << 'T' << (T->getIndex() - 1) << '_'; } void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { mangleSourceName(T->getDecl()->getIdentifier()); } void CXXNameMangler::mangleExpression(Expr *E) { assert(false && "Cannot mangle expressions yet"); } void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) { // <ctor-dtor-name> ::= C1 # complete object constructor // ::= C2 # base object constructor // ::= C3 # complete object allocating constructor // switch (T) { case Ctor_Complete: Out << "C1"; break; case Ctor_Base: Out << "C2"; break; case Ctor_CompleteAllocating: Out << "C3"; break; } } namespace clang { /// \brief Mangles the name of the declaration D and emits that name /// to the given output stream. /// /// If the declaration D requires a mangled name, this routine will /// emit that mangled name to \p os and return true. Otherwise, \p /// os will be unchanged and this routine will return false. In this /// case, the caller should just emit the identifier of the declaration /// (\c D->getIdentifier()) as its name. bool mangleName(const NamedDecl *D, ASTContext &Context, llvm::raw_ostream &os) { CXXNameMangler Mangler(Context, os); if (!Mangler.mangle(D)) return false; os.flush(); return true; } /// mangleGuardVariable - Returns the mangled name for a guard variable /// for the passed in VarDecl. void mangleGuardVariable(const VarDecl *D, ASTContext &Context, llvm::raw_ostream &os) { CXXNameMangler Mangler(Context, os); Mangler.mangleGuardVariable(D); os.flush(); } void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, ASTContext &Context, llvm::raw_ostream &os) { CXXNameMangler Mangler(Context, os); Mangler.mangleCXXCtor(D, Type); os.flush(); } } <file_sep>/test/CodeGen/string-literal.c // RUN: clang-cc -emit-llvm %s -o - int main() { char a[10] = "abc"; void *foo = L"AB"; } <file_sep>/test/CodeGen/volatile.c // RUN: clang-cc -emit-llvm < %s | grep volatile | count 25 // The number 26 comes from the current codegen for volatile loads; // if this number changes, it's not necessarily something wrong, but // something has changed to affect volatile load/store codegen int S; volatile int vS; int* pS; volatile int* pvS; int A[10]; volatile int vA[10]; struct { int x; } F; struct { volatile int x; } vF; struct { int x; } F2; volatile struct { int x; } vF2; volatile struct { int x; } *vpF2; struct { struct { int y; } x; } F3; volatile struct { struct { int y; } x; } vF3; struct { int x:3; } BF; struct { volatile int x:3; } vBF; typedef int v4si __attribute__ ((vector_size (16))); v4si V; volatile v4si vV; typedef __attribute__(( ext_vector_type(4) )) int extv4; extv4 VE; volatile extv4 vVE; volatile struct {int x;} aggFct(void); void main() { int i; // load i=S; i=vS; i=*pS; i=*pvS; i=A[2]; i=vA[2]; i=F.x; i=vF.x; i=F2.x; i=vF2.x; i=vpF2->x; i=F3.x.y; i=vF3.x.y; i=BF.x; i=vBF.x; i=V[3]; i=vV[3]; i=VE.yx[1]; i=vVE.zy[1]; i = aggFct().x; // store S=i; vS=i; *pS=i; *pvS=i; A[2]=i; vA[2]=i; F.x=i; vF.x=i; F2.x=i; vF2.x=i; vpF2->x=i; vF3.x.y=i; BF.x=i; vBF.x=i; V[3]=i; vV[3]=i; // other ops: ++S; ++vS; i+=S; i+=vS; } <file_sep>/test/CodeGenCXX/const-init.cpp // RUN: clang-cc -verify -emit-llvm -o %t %s int a = 10; int &ar = a; void f(); void (&fr)() = f; struct S { int& a; }; S s = { a }; <file_sep>/include/clang/AST/DeclContextInternals.h //===-- DeclContextInternals.h - DeclContext Representation -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the data structures used in the implementation // of DeclContext. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_DECLCONTEXTINTERNALS_H #define LLVM_CLANG_AST_DECLCONTEXTINTERNALS_H #include "clang/AST/DeclBase.h" #include "clang/AST/DeclarationName.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/SmallVector.h" #include <algorithm> namespace clang { /// StoredDeclsList - This is an array of decls optimized a common case of only /// containing one entry. struct StoredDeclsList { /// The kind of data encoded in this list. enum DataKind { /// \brief The data is a NamedDecl*. DK_Decl = 0, /// \brief The data is a declaration ID (an unsigned value), /// shifted left by 2 bits. DK_DeclID = 1, /// \brief The data is a pointer to a vector (of type VectorTy) /// that contains declarations. DK_Decl_Vector = 2, /// \brief The data is a pointer to a vector (of type VectorTy) /// that contains declaration ID. DK_ID_Vector = 3 }; /// VectorTy - When in vector form, this is what the Data pointer points to. typedef llvm::SmallVector<uintptr_t, 4> VectorTy; /// \brief The stored data, which will be either a declaration ID, a /// pointer to a NamedDecl, or a pointer to a vector. uintptr_t Data; public: StoredDeclsList() : Data(0) {} StoredDeclsList(const StoredDeclsList &RHS) : Data(RHS.Data) { if (VectorTy *RHSVec = RHS.getAsVector()) { VectorTy *New = new VectorTy(*RHSVec); Data = reinterpret_cast<uintptr_t>(New) | (Data & 0x03); } } ~StoredDeclsList() { // If this is a vector-form, free the vector. if (VectorTy *Vector = getAsVector()) delete Vector; } StoredDeclsList &operator=(const StoredDeclsList &RHS) { if (VectorTy *Vector = getAsVector()) delete Vector; Data = RHS.Data; if (VectorTy *RHSVec = RHS.getAsVector()) { VectorTy *New = new VectorTy(*RHSVec); Data = reinterpret_cast<uintptr_t>(New) | (Data & 0x03); } return *this; } bool isNull() const { return (Data & ~0x03) == 0; } NamedDecl *getAsDecl() const { if ((Data & 0x03) != DK_Decl) return 0; return reinterpret_cast<NamedDecl *>(Data & ~0x03); } VectorTy *getAsVector() const { if ((Data & 0x03) != DK_ID_Vector && (Data & 0x03) != DK_Decl_Vector) return 0; return reinterpret_cast<VectorTy *>(Data & ~0x03); } void setOnlyValue(NamedDecl *ND) { assert(!getAsVector() && "Not inline"); Data = reinterpret_cast<uintptr_t>(ND); } void setFromDeclIDs(const llvm::SmallVectorImpl<unsigned> &Vec) { if (Vec.size() > 1) { VectorTy *Vector = getAsVector(); if (!Vector) { Vector = new VectorTy; Data = reinterpret_cast<uintptr_t>(Vector) | DK_Decl_Vector; } Vector->resize(Vec.size()); std::copy(Vec.begin(), Vec.end(), Vector->begin()); return; } if (VectorTy *Vector = getAsVector()) delete Vector; if (Vec.empty()) Data = 0; else Data = (Vec[0] << 2) | DK_DeclID; } /// \brief Force the stored declarations list to contain actual /// declarations. /// /// This routine will resolve any declaration IDs for declarations /// that may not yet have been loaded from external storage. void materializeDecls(ASTContext &Context); bool hasDeclarationIDs() const { DataKind DK = (DataKind)(Data & 0x03); return DK == DK_DeclID || DK == DK_ID_Vector; } /// getLookupResult - Return an array of all the decls that this list /// represents. DeclContext::lookup_result getLookupResult(ASTContext &Context) { if (isNull()) return DeclContext::lookup_result(0, 0); if (hasDeclarationIDs()) materializeDecls(Context); // If we have a single NamedDecl, return it. if (getAsDecl()) { assert(!isNull() && "Empty list isn't allowed"); // Data is a raw pointer to a NamedDecl*, return it. void *Ptr = &Data; return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1); } assert(getAsVector() && "Must have a vector at this point"); VectorTy &Vector = *getAsVector(); // Otherwise, we have a range result. return DeclContext::lookup_result((NamedDecl **)&Vector[0], (NamedDecl **)&Vector[0]+Vector.size()); } /// HandleRedeclaration - If this is a redeclaration of an existing decl, /// replace the old one with D and return true. Otherwise return false. bool HandleRedeclaration(ASTContext &Context, NamedDecl *D) { if (hasDeclarationIDs()) materializeDecls(Context); // Most decls only have one entry in their list, special case it. if (NamedDecl *OldD = getAsDecl()) { if (!D->declarationReplaces(OldD)) return false; setOnlyValue(D); return true; } // Determine if this declaration is actually a redeclaration. VectorTy &Vec = *getAsVector(); for (VectorTy::iterator OD = Vec.begin(), ODEnd = Vec.end(); OD != ODEnd; ++OD) { NamedDecl *OldD = reinterpret_cast<NamedDecl *>(*OD); if (D->declarationReplaces(OldD)) { *OD = reinterpret_cast<uintptr_t>(D); return true; } } return false; } /// AddSubsequentDecl - This is called on the second and later decl when it is /// not a redeclaration to merge it into the appropriate place in our list. /// void AddSubsequentDecl(NamedDecl *D) { assert(!hasDeclarationIDs() && "Must materialize before adding decls"); // If this is the second decl added to the list, convert this to vector // form. if (NamedDecl *OldD = getAsDecl()) { VectorTy *VT = new VectorTy(); VT->push_back(reinterpret_cast<uintptr_t>(OldD)); Data = reinterpret_cast<uintptr_t>(VT) | DK_Decl_Vector; } VectorTy &Vec = *getAsVector(); if (isa<UsingDirectiveDecl>(D) || D->getIdentifierNamespace() == Decl::IDNS_Tag) Vec.push_back(reinterpret_cast<uintptr_t>(D)); else if (reinterpret_cast<NamedDecl *>(Vec.back()) ->getIdentifierNamespace() == Decl::IDNS_Tag) { uintptr_t TagD = Vec.back(); Vec.back() = reinterpret_cast<uintptr_t>(D); Vec.push_back(TagD); } else Vec.push_back(reinterpret_cast<uintptr_t>(D)); } }; typedef llvm::DenseMap<DeclarationName, StoredDeclsList> StoredDeclsMap; } // end namespace clang #endif <file_sep>/lib/Sema/SemaDeclObjC.cpp //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for Objective C declarations. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/AST/Expr.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/Parse/DeclSpec.h" using namespace clang; /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible /// and user declared, in the method definition's AST. void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) { assert(getCurMethodDecl() == 0 && "Method parsing confused"); ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D.getAs<Decl>()); // If we don't have a valid method decl, simply return. if (!MDecl) return; // Allow the rest of sema to find private method decl implementations. if (MDecl->isInstanceMethod()) AddInstanceMethodToGlobalPool(MDecl); else AddFactoryMethodToGlobalPool(MDecl); // Allow all of Sema to see that we are entering a method definition. PushDeclContext(FnBodyScope, MDecl); // Create Decl objects for each parameter, entrring them in the scope for // binding to their use. // Insert the invisible arguments, self and _cmd! MDecl->createImplicitParams(Context, MDecl->getClassInterface()); PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); // Introduce all of the other parameters into this scope. for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), E = MDecl->param_end(); PI != E; ++PI) if ((*PI)->getIdentifier()) PushOnScopeChains(*PI, FnBodyScope); } Sema::DeclPtrTy Sema:: ActOnStartClassInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc, AttributeList *AttrList) { assert(ClassName && "Missing class identifier"); // Check for another declaration kind with the same name. NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName); if (PrevDecl && PrevDecl->isTemplateParameter()) { // Maybe we will complain about the shadowed template parameter. DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl); // Just pretend that we didn't see the previous declaration. PrevDecl = 0; } if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; Diag(PrevDecl->getLocation(), diag::note_previous_definition); } ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); if (IDecl) { // Class already seen. Is it a forward declaration? if (!IDecl->isForwardDecl()) { IDecl->setInvalidDecl(); Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName(); Diag(IDecl->getLocation(), diag::note_previous_definition); // Return the previous class interface. // FIXME: don't leak the objects passed in! return DeclPtrTy::make(IDecl); } else { IDecl->setLocation(AtInterfaceLoc); IDecl->setForwardDecl(false); } } else { IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName, ClassLoc); if (AttrList) ProcessDeclAttributeList(IDecl, AttrList); ObjCInterfaceDecls[ClassName] = IDecl; // FIXME: PushOnScopeChains CurContext->addDecl(Context, IDecl); // Remember that this needs to be removed when the scope is popped. TUScope->AddDecl(DeclPtrTy::make(IDecl)); } if (SuperName) { // Check if a different kind of symbol declared in this scope. PrevDecl = LookupName(TUScope, SuperName, LookupOrdinaryName); ObjCInterfaceDecl *SuperClassDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); // Diagnose classes that inherit from deprecated classes. if (SuperClassDecl) (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); if (PrevDecl && SuperClassDecl == 0) { // The previous declaration was not a class decl. Check if we have a // typedef. If we do, get the underlying class type. if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) { QualType T = TDecl->getUnderlyingType(); if (T->isObjCInterfaceType()) { if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl()) SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); } } // This handles the following case: // // typedef int SuperClass; // @interface MyClass : SuperClass {} @end // if (!SuperClassDecl) { Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; Diag(PrevDecl->getLocation(), diag::note_previous_definition); } } if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) { if (!SuperClassDecl) Diag(SuperLoc, diag::err_undef_superclass) << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); else if (SuperClassDecl->isForwardDecl()) Diag(SuperLoc, diag::err_undef_superclass) << SuperClassDecl->getDeclName() << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); } IDecl->setSuperClass(SuperClassDecl); IDecl->setSuperClassLoc(SuperLoc); IDecl->setLocEnd(SuperLoc); } else { // we have a root class. IDecl->setLocEnd(ClassLoc); } /// Check then save referenced protocols. if (NumProtoRefs) { IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs, Context); IDecl->setLocEnd(EndProtoLoc); } CheckObjCDeclScope(IDecl); return DeclPtrTy::make(IDecl); } /// ActOnCompatiblityAlias - this action is called after complete parsing of /// @compatibility_alias declaration. It sets up the alias relationships. Sema::DeclPtrTy Sema::ActOnCompatiblityAlias(SourceLocation AtLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation) { // Look for previous declaration of alias name NamedDecl *ADecl = LookupName(TUScope, AliasName, LookupOrdinaryName); if (ADecl) { if (isa<ObjCCompatibleAliasDecl>(ADecl)) Diag(AliasLocation, diag::warn_previous_alias_decl); else Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; Diag(ADecl->getLocation(), diag::note_previous_declaration); return DeclPtrTy(); } // Check for class declaration NamedDecl *CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName); if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) { QualType T = TDecl->getUnderlyingType(); if (T->isObjCInterfaceType()) { if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl()) { ClassName = IDecl->getIdentifier(); CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName); } } } ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); if (CDecl == 0) { Diag(ClassLocation, diag::warn_undef_interface) << ClassName; if (CDeclU) Diag(CDeclU->getLocation(), diag::note_previous_declaration); return DeclPtrTy(); } // Everything checked out, instantiate a new alias declaration AST. ObjCCompatibleAliasDecl *AliasDecl = ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); ObjCAliasDecls[AliasName] = AliasDecl; // FIXME: PushOnScopeChains? CurContext->addDecl(Context, AliasDecl); if (!CheckObjCDeclScope(AliasDecl)) TUScope->AddDecl(DeclPtrTy::make(AliasDecl)); return DeclPtrTy::make(AliasDecl); } void Sema::CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &Ploc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList) { for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), E = PList.end(); I != E; ++I) { if (ObjCProtocolDecl *PDecl = ObjCProtocols[(*I)->getIdentifier()]) { if (PDecl->getIdentifier() == PName) { Diag(Ploc, diag::err_protocol_has_circular_dependency); Diag(PrevLoc, diag::note_previous_definition); } CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, PDecl->getLocation(), PDecl->getReferencedProtocols()); } } } Sema::DeclPtrTy Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc, AttributeList *AttrList) { // FIXME: Deal with AttrList. assert(ProtocolName && "Missing protocol identifier"); ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName]; if (PDecl) { // Protocol already seen. Better be a forward protocol declaration if (!PDecl->isForwardDecl()) { Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; Diag(PDecl->getLocation(), diag::note_previous_definition); // Just return the protocol we already had. // FIXME: don't leak the objects passed in! return DeclPtrTy::make(PDecl); } ObjCList<ObjCProtocolDecl> PList; PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); CheckForwardProtocolDeclarationForCircularDependency( ProtocolName, ProtocolLoc, PDecl->getLocation(), PList); PList.Destroy(Context); // Make sure the cached decl gets a valid start location. PDecl->setLocation(AtProtoInterfaceLoc); PDecl->setForwardDecl(false); } else { PDecl = ObjCProtocolDecl::Create(Context, CurContext, AtProtoInterfaceLoc,ProtocolName); // FIXME: PushOnScopeChains? CurContext->addDecl(Context, PDecl); PDecl->setForwardDecl(false); ObjCProtocols[ProtocolName] = PDecl; } if (AttrList) ProcessDeclAttributeList(PDecl, AttrList); if (NumProtoRefs) { /// Check then save referenced protocols. PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,Context); PDecl->setLocEnd(EndProtoLoc); } CheckObjCDeclScope(PDecl); return DeclPtrTy::make(PDecl); } /// FindProtocolDeclaration - This routine looks up protocols and /// issues an error if they are not declared. It returns list of /// protocol declarations in its 'Protocols' argument. void Sema::FindProtocolDeclaration(bool WarnOnDeclarations, const IdentifierLocPair *ProtocolId, unsigned NumProtocols, llvm::SmallVectorImpl<DeclPtrTy> &Protocols) { for (unsigned i = 0; i != NumProtocols; ++i) { ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i].first]; if (!PDecl) { Diag(ProtocolId[i].second, diag::err_undeclared_protocol) << ProtocolId[i].first; continue; } (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second); // If this is a forward declaration and we are supposed to warn in this // case, do it. if (WarnOnDeclarations && PDecl->isForwardDecl()) Diag(ProtocolId[i].second, diag::warn_undef_protocolref) << ProtocolId[i].first; Protocols.push_back(DeclPtrTy::make(PDecl)); } } /// DiagnosePropertyMismatch - Compares two properties for their /// attributes and types and warns on a variety of inconsistencies. /// void Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *inheritedName) { ObjCPropertyDecl::PropertyAttributeKind CAttr = Property->getPropertyAttributes(); ObjCPropertyDecl::PropertyAttributeKind SAttr = SuperProperty->getPropertyAttributes(); if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly) && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite)) Diag(Property->getLocation(), diag::warn_readonly_property) << Property->getDeclName() << inheritedName; if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy) != (SAttr & ObjCPropertyDecl::OBJC_PR_copy)) Diag(Property->getLocation(), diag::warn_property_attribute) << Property->getDeclName() << "copy" << inheritedName; else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain) != (SAttr & ObjCPropertyDecl::OBJC_PR_retain)) Diag(Property->getLocation(), diag::warn_property_attribute) << Property->getDeclName() << "retain" << inheritedName; if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic) != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)) Diag(Property->getLocation(), diag::warn_property_attribute) << Property->getDeclName() << "atomic" << inheritedName; if (Property->getSetterName() != SuperProperty->getSetterName()) Diag(Property->getLocation(), diag::warn_property_attribute) << Property->getDeclName() << "setter" << inheritedName; if (Property->getGetterName() != SuperProperty->getGetterName()) Diag(Property->getLocation(), diag::warn_property_attribute) << Property->getDeclName() << "getter" << inheritedName; QualType LHSType = Context.getCanonicalType(SuperProperty->getType()); QualType RHSType = Context.getCanonicalType(Property->getType()); if (!Context.typesAreCompatible(LHSType, RHSType)) { // FIXME: Incorporate this test with typesAreCompatible. if (LHSType->isObjCQualifiedIdType() && RHSType->isObjCQualifiedIdType()) if (ObjCQualifiedIdTypesAreCompatible(LHSType, RHSType, false)) return; Diag(Property->getLocation(), diag::warn_property_types_are_incompatible) << Property->getType() << SuperProperty->getType() << inheritedName; } } /// ComparePropertiesInBaseAndSuper - This routine compares property /// declarations in base and its super class, if any, and issues /// diagnostics in a variety of inconsistant situations. /// void Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) { ObjCInterfaceDecl *SDecl = IDecl->getSuperClass(); if (!SDecl) return; // FIXME: O(N^2) for (ObjCInterfaceDecl::prop_iterator S = SDecl->prop_begin(Context), E = SDecl->prop_end(Context); S != E; ++S) { ObjCPropertyDecl *SuperPDecl = (*S); // Does property in super class has declaration in current class? for (ObjCInterfaceDecl::prop_iterator I = IDecl->prop_begin(Context), E = IDecl->prop_end(Context); I != E; ++I) { ObjCPropertyDecl *PDecl = (*I); if (SuperPDecl->getIdentifier() == PDecl->getIdentifier()) DiagnosePropertyMismatch(PDecl, SuperPDecl, SDecl->getIdentifier()); } } } /// MergeOneProtocolPropertiesIntoClass - This routine goes thru the list /// of properties declared in a protocol and adds them to the list /// of properties for current class/category if it is not there already. void Sema::MergeOneProtocolPropertiesIntoClass(Decl *CDecl, ObjCProtocolDecl *PDecl) { ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl); if (!IDecl) { // Category ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl); assert (CatDecl && "MergeOneProtocolPropertiesIntoClass"); for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(Context), E = PDecl->prop_end(Context); P != E; ++P) { ObjCPropertyDecl *Pr = (*P); ObjCCategoryDecl::prop_iterator CP, CE; // Is this property already in category's list of properties? for (CP = CatDecl->prop_begin(Context), CE = CatDecl->prop_end(Context); CP != CE; ++CP) if ((*CP)->getIdentifier() == Pr->getIdentifier()) break; if (CP != CE) // Property protocol already exist in class. Diagnose any mismatch. DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier()); } return; } for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(Context), E = PDecl->prop_end(Context); P != E; ++P) { ObjCPropertyDecl *Pr = (*P); ObjCInterfaceDecl::prop_iterator CP, CE; // Is this property already in class's list of properties? for (CP = IDecl->prop_begin(Context), CE = IDecl->prop_end(Context); CP != CE; ++CP) if ((*CP)->getIdentifier() == Pr->getIdentifier()) break; if (CP != CE) // Property protocol already exist in class. Diagnose any mismatch. DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier()); } } /// MergeProtocolPropertiesIntoClass - This routine merges properties /// declared in 'MergeItsProtocols' objects (which can be a class or an /// inherited protocol into the list of properties for class/category 'CDecl' /// void Sema::MergeProtocolPropertiesIntoClass(Decl *CDecl, DeclPtrTy MergeItsProtocols) { Decl *ClassDecl = MergeItsProtocols.getAs<Decl>(); ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl); if (!IDecl) { // Category ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl); assert (CatDecl && "MergeProtocolPropertiesIntoClass"); if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(), E = MDecl->protocol_end(); P != E; ++P) // Merge properties of category (*P) into IDECL's MergeOneProtocolPropertiesIntoClass(CatDecl, *P); // Go thru the list of protocols for this category and recursively merge // their properties into this class as well. for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(), E = CatDecl->protocol_end(); P != E; ++P) MergeProtocolPropertiesIntoClass(CatDecl, DeclPtrTy::make(*P)); } else { ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl); for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(), E = MD->protocol_end(); P != E; ++P) MergeOneProtocolPropertiesIntoClass(CatDecl, *P); } return; } if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) { for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(), E = MDecl->protocol_end(); P != E; ++P) // Merge properties of class (*P) into IDECL's MergeOneProtocolPropertiesIntoClass(IDecl, *P); // Go thru the list of protocols for this class and recursively merge // their properties into this class as well. for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(), E = IDecl->protocol_end(); P != E; ++P) MergeProtocolPropertiesIntoClass(IDecl, DeclPtrTy::make(*P)); } else { ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl); for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(), E = MD->protocol_end(); P != E; ++P) MergeOneProtocolPropertiesIntoClass(IDecl, *P); } } /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of /// a class method in its extension. /// void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID) { if (!ID) return; // Possibly due to previous error llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(Context), e = ID->meth_end(Context); i != e; ++i) { ObjCMethodDecl *MD = *i; MethodMap[MD->getSelector()] = MD; } if (MethodMap.empty()) return; for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(Context), e = CAT->meth_end(Context); i != e; ++i) { ObjCMethodDecl *Method = *i; const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) { Diag(Method->getLocation(), diag::err_duplicate_method_decl) << Method->getDeclName(); Diag(PrevMethod->getLocation(), diag::note_previous_declaration); } } } /// ActOnForwardProtocolDeclaration - Handle @protocol foo; Action::DeclPtrTy Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, const IdentifierLocPair *IdentList, unsigned NumElts, AttributeList *attrList) { llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols; for (unsigned i = 0; i != NumElts; ++i) { IdentifierInfo *Ident = IdentList[i].first; ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident]; if (PDecl == 0) { // Not already seen? PDecl = ObjCProtocolDecl::Create(Context, CurContext, IdentList[i].second, Ident); // FIXME: PushOnScopeChains? CurContext->addDecl(Context, PDecl); } if (attrList) ProcessDeclAttributeList(PDecl, attrList); Protocols.push_back(PDecl); } ObjCForwardProtocolDecl *PDecl = ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc, &Protocols[0], Protocols.size()); CurContext->addDecl(Context, PDecl); CheckObjCDeclScope(PDecl); return DeclPtrTy::make(PDecl); } Sema::DeclPtrTy Sema:: ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs, SourceLocation EndProtoLoc) { ObjCCategoryDecl *CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, CategoryName); // FIXME: PushOnScopeChains? CurContext->addDecl(Context, CDecl); ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName); /// Check that class of this category is already completely declared. if (!IDecl || IDecl->isForwardDecl()) { CDecl->setInvalidDecl(); Diag(ClassLoc, diag::err_undef_interface) << ClassName; return DeclPtrTy::make(CDecl); } CDecl->setClassInterface(IDecl); // If the interface is deprecated, warn about it. (void)DiagnoseUseOfDecl(IDecl, ClassLoc); /// Check for duplicate interface declaration for this category ObjCCategoryDecl *CDeclChain; for (CDeclChain = IDecl->getCategoryList(); CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) { if (CategoryName && CDeclChain->getIdentifier() == CategoryName) { Diag(CategoryLoc, diag::warn_dup_category_def) << ClassName << CategoryName; Diag(CDeclChain->getLocation(), diag::note_previous_definition); break; } } if (!CDeclChain) CDecl->insertNextClassCategory(); if (NumProtoRefs) { CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,Context); CDecl->setLocEnd(EndProtoLoc); } CheckObjCDeclScope(CDecl); return DeclPtrTy::make(CDecl); } /// ActOnStartCategoryImplementation - Perform semantic checks on the /// category implementation declaration and build an ObjCCategoryImplDecl /// object. Sema::DeclPtrTy Sema::ActOnStartCategoryImplementation( SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc) { ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName); ObjCCategoryImplDecl *CDecl = ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName, IDecl); /// Check that class of this category is already completely declared. if (!IDecl || IDecl->isForwardDecl()) Diag(ClassLoc, diag::err_undef_interface) << ClassName; // FIXME: PushOnScopeChains? CurContext->addDecl(Context, CDecl); /// TODO: Check that CatName, category name, is not used in another // implementation. ObjCCategoryImpls.push_back(CDecl); CheckObjCDeclScope(CDecl); return DeclPtrTy::make(CDecl); } Sema::DeclPtrTy Sema::ActOnStartClassImplementation( SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc) { ObjCInterfaceDecl* IDecl = 0; // Check for another declaration kind with the same name. NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName); if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; Diag(PrevDecl->getLocation(), diag::note_previous_definition); } else { // Is there an interface declaration of this class; if not, warn! IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); if (!IDecl) Diag(ClassLoc, diag::warn_undef_interface) << ClassName; } // Check that super class name is valid class name ObjCInterfaceDecl* SDecl = 0; if (SuperClassname) { // Check if a different kind of symbol declared in this scope. PrevDecl = LookupName(TUScope, SuperClassname, LookupOrdinaryName); if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { Diag(SuperClassLoc, diag::err_redefinition_different_kind) << SuperClassname; Diag(PrevDecl->getLocation(), diag::note_previous_definition); } else { SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); if (!SDecl) Diag(SuperClassLoc, diag::err_undef_superclass) << SuperClassname << ClassName; else if (IDecl && IDecl->getSuperClass() != SDecl) { // This implementation and its interface do not have the same // super class. Diag(SuperClassLoc, diag::err_conflicting_super_class) << SDecl->getDeclName(); Diag(SDecl->getLocation(), diag::note_previous_definition); } } } if (!IDecl) { // Legacy case of @implementation with no corresponding @interface. // Build, chain & install the interface decl into the identifier. // FIXME: Do we support attributes on the @implementation? If so // we should copy them over. IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, ClassName, ClassLoc, false, true); ObjCInterfaceDecls[ClassName] = IDecl; IDecl->setSuperClass(SDecl); IDecl->setLocEnd(ClassLoc); // FIXME: PushOnScopeChains? CurContext->addDecl(Context, IDecl); // Remember that this needs to be removed when the scope is popped. TUScope->AddDecl(DeclPtrTy::make(IDecl)); } ObjCImplementationDecl* IMPDecl = ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc, IDecl, SDecl); // FIXME: PushOnScopeChains? CurContext->addDecl(Context, IMPDecl); if (CheckObjCDeclScope(IMPDecl)) return DeclPtrTy::make(IMPDecl); // Check that there is no duplicate implementation of this class. if (ObjCImplementations[ClassName]) // FIXME: Don't leak everything! Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; else // add it to the list. ObjCImplementations[ClassName] = IMPDecl; return DeclPtrTy::make(IMPDecl); } void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **ivars, unsigned numIvars, SourceLocation RBrace) { assert(ImpDecl && "missing implementation decl"); ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); if (!IDecl) return; /// Check case of non-existing @interface decl. /// (legacy objective-c @implementation decl without an @interface decl). /// Add implementations's ivar to the synthesize class's ivar list. if (IDecl->ImplicitInterfaceDecl()) { IDecl->setIVarList(ivars, numIvars, Context); IDecl->setLocEnd(RBrace); return; } // If implementation has empty ivar list, just return. if (numIvars == 0) return; assert(ivars && "missing @implementation ivars"); // Check interface's Ivar list against those in the implementation. // names and types must match. // unsigned j = 0; ObjCInterfaceDecl::ivar_iterator IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); for (; numIvars > 0 && IVI != IVE; ++IVI) { ObjCIvarDecl* ImplIvar = ivars[j++]; ObjCIvarDecl* ClsIvar = *IVI; assert (ImplIvar && "missing implementation ivar"); assert (ClsIvar && "missing class ivar"); // First, make sure the types match. if (Context.getCanonicalType(ImplIvar->getType()) != Context.getCanonicalType(ClsIvar->getType())) { Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) << ImplIvar->getIdentifier() << ImplIvar->getType() << ClsIvar->getType(); Diag(ClsIvar->getLocation(), diag::note_previous_definition); } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) { Expr *ImplBitWidth = ImplIvar->getBitWidth(); Expr *ClsBitWidth = ClsIvar->getBitWidth(); if (ImplBitWidth->getIntegerConstantExprValue(Context).getZExtValue() != ClsBitWidth->getIntegerConstantExprValue(Context).getZExtValue()) { Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier(); Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition); } } // Make sure the names are identical. if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); Diag(ClsIvar->getLocation(), diag::note_previous_definition); } --numIvars; } if (numIvars > 0) Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count); else if (IVI != IVE) Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count); } void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, bool &IncompleteImpl) { if (!IncompleteImpl) { Diag(ImpLoc, diag::warn_incomplete_impl); IncompleteImpl = true; } Diag(ImpLoc, diag::warn_undef_method_impl) << method->getDeclName(); } void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, ObjCMethodDecl *IntfMethodDecl) { if (!Context.typesAreCompatible(IntfMethodDecl->getResultType(), ImpMethodDecl->getResultType())) { Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_ret_types) << ImpMethodDecl->getDeclName() << IntfMethodDecl->getResultType() << ImpMethodDecl->getResultType(); Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition); } for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), IF = IntfMethodDecl->param_begin(), EM = ImpMethodDecl->param_end(); IM != EM; ++IM, ++IF) { if (Context.typesAreCompatible((*IF)->getType(), (*IM)->getType())) continue; Diag((*IM)->getLocation(), diag::warn_conflicting_param_types) << ImpMethodDecl->getDeclName() << (*IF)->getType() << (*IM)->getType(); Diag((*IF)->getLocation(), diag::note_previous_definition); } } /// isPropertyReadonly - Return true if property is readonly, by searching /// for the property in the class and in its categories and implementations /// bool Sema::isPropertyReadonly(ObjCPropertyDecl *PDecl, ObjCInterfaceDecl *IDecl) { // by far the most common case. if (!PDecl->isReadOnly()) return false; // Even if property is ready only, if interface has a user defined setter, // it is not considered read only. if (IDecl->getInstanceMethod(Context, PDecl->getSetterName())) return false; // Main class has the property as 'readonly'. Must search // through the category list to see if the property's // attribute has been over-ridden to 'readwrite'. for (ObjCCategoryDecl *Category = IDecl->getCategoryList(); Category; Category = Category->getNextClassCategory()) { // Even if property is ready only, if a category has a user defined setter, // it is not considered read only. if (Category->getInstanceMethod(Context, PDecl->getSetterName())) return false; ObjCPropertyDecl *P = Category->FindPropertyDeclaration(Context, PDecl->getIdentifier()); if (P && !P->isReadOnly()) return false; } // Also, check for definition of a setter method in the implementation if // all else failed. if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurContext)) { if (ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OMD->getDeclContext())) { if (IMD->getInstanceMethod(PDecl->getSetterName())) return false; } else if (ObjCCategoryImplDecl *CIMD = dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) { if (CIMD->getInstanceMethod(PDecl->getSetterName())) return false; } } // Lastly, look through the implementation (if one is in scope). if (ObjCImplementationDecl *ImpDecl = ObjCImplementations[IDecl->getIdentifier()]) if (ImpDecl->getInstanceMethod(PDecl->getSetterName())) return false; // If all fails, look at the super class. if (ObjCInterfaceDecl *SIDecl = IDecl->getSuperClass()) return isPropertyReadonly(PDecl, SIDecl); return true; } /// FIXME: Type hierarchies in Objective-C can be deep. We could most /// likely improve the efficiency of selector lookups and type /// checking by associating with each protocol / interface / category /// the flattened instance tables. If we used an immutable set to keep /// the table then it wouldn't add significant memory cost and it /// would be handy for lookups. /// CheckProtocolMethodDefs - This routine checks unimplemented methods /// Declared in protocol, and those referenced by it. void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc, ObjCProtocolDecl *PDecl, bool& IncompleteImpl, const llvm::DenseSet<Selector> &InsMap, const llvm::DenseSet<Selector> &ClsMap, ObjCInterfaceDecl *IDecl) { ObjCInterfaceDecl *Super = IDecl->getSuperClass(); // If a method lookup fails locally we still need to look and see if // the method was implemented by a base class or an inherited // protocol. This lookup is slow, but occurs rarely in correct code // and otherwise would terminate in a warning. // check unimplemented instance methods. for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(Context), E = PDecl->instmeth_end(Context); I != E; ++I) { ObjCMethodDecl *method = *I; if (method->getImplementationControl() != ObjCMethodDecl::Optional && !method->isSynthesized() && !InsMap.count(method->getSelector()) && (!Super || !Super->lookupInstanceMethod(Context, method->getSelector()))) { // Ugly, but necessary. Method declared in protcol might have // have been synthesized due to a property declared in the class which // uses the protocol. ObjCMethodDecl *MethodInClass = IDecl->lookupInstanceMethod(Context, method->getSelector()); if (!MethodInClass || !MethodInClass->isSynthesized()) WarnUndefinedMethod(ImpLoc, method, IncompleteImpl); } } // check unimplemented class methods for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(Context), E = PDecl->classmeth_end(Context); I != E; ++I) { ObjCMethodDecl *method = *I; if (method->getImplementationControl() != ObjCMethodDecl::Optional && !ClsMap.count(method->getSelector()) && (!Super || !Super->lookupClassMethod(Context, method->getSelector()))) WarnUndefinedMethod(ImpLoc, method, IncompleteImpl); } // Check on this protocols's referenced protocols, recursively. for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(), E = PDecl->protocol_end(); PI != E; ++PI) CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl); } void Sema::ImplMethodsVsClassMethods(ObjCImplDecl* IMPDecl, ObjCContainerDecl* CDecl, bool IncompleteImpl) { llvm::DenseSet<Selector> InsMap; // Check and see if instance methods in class interface have been // implemented in the implementation class. for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I != E; ++I) InsMap.insert((*I)->getSelector()); // Check and see if properties declared in the interface have either 1) // an implementation or 2) there is a @synthesize/@dynamic implementation // of the property in the @implementation. if (isa<ObjCInterfaceDecl>(CDecl)) for (ObjCContainerDecl::prop_iterator P = CDecl->prop_begin(Context), E = CDecl->prop_end(Context); P != E; ++P) { ObjCPropertyDecl *Prop = (*P); if (Prop->isInvalidDecl()) continue; ObjCPropertyImplDecl *PI = 0; // Is there a matching propery synthesize/dynamic? for (ObjCImplDecl::propimpl_iterator I = IMPDecl->propimpl_begin(), EI = IMPDecl->propimpl_end(); I != EI; ++I) if ((*I)->getPropertyDecl() == Prop) { PI = (*I); break; } if (PI) continue; if (!InsMap.count(Prop->getGetterName())) { Diag(Prop->getLocation(), diag::warn_setter_getter_impl_required) << Prop->getDeclName() << Prop->getGetterName(); Diag(IMPDecl->getLocation(), diag::note_property_impl_required); } if (!Prop->isReadOnly() && !InsMap.count(Prop->getSetterName())) { Diag(Prop->getLocation(), diag::warn_setter_getter_impl_required) << Prop->getDeclName() << Prop->getSetterName(); Diag(IMPDecl->getLocation(), diag::note_property_impl_required); } } for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(Context), E = CDecl->instmeth_end(Context); I != E; ++I) { if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector())) { WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl); continue; } ObjCMethodDecl *ImpMethodDecl = IMPDecl->getInstanceMethod((*I)->getSelector()); ObjCMethodDecl *IntfMethodDecl = CDecl->getInstanceMethod(Context, (*I)->getSelector()); assert(IntfMethodDecl && "IntfMethodDecl is null in ImplMethodsVsClassMethods"); // ImpMethodDecl may be null as in a @dynamic property. if (ImpMethodDecl) WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl); } llvm::DenseSet<Selector> ClsMap; // Check and see if class methods in class interface have been // implemented in the implementation class. for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(), E = IMPDecl->classmeth_end(); I != E; ++I) ClsMap.insert((*I)->getSelector()); for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(Context), E = CDecl->classmeth_end(Context); I != E; ++I) if (!ClsMap.count((*I)->getSelector())) WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl); else { ObjCMethodDecl *ImpMethodDecl = IMPDecl->getClassMethod((*I)->getSelector()); ObjCMethodDecl *IntfMethodDecl = CDecl->getClassMethod(Context, (*I)->getSelector()); WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl); } // Check the protocol list for unimplemented methods in the @implementation // class. if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { for (ObjCCategoryDecl::protocol_iterator PI = I->protocol_begin(), E = I->protocol_end(); PI != E; ++PI) CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl, InsMap, ClsMap, I); // Check class extensions (unnamed categories) for (ObjCCategoryDecl *Categories = I->getCategoryList(); Categories; Categories = Categories->getNextClassCategory()) { if (!Categories->getIdentifier()) { ImplMethodsVsClassMethods(IMPDecl, Categories, IncompleteImpl); break; } } } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(), E = C->protocol_end(); PI != E; ++PI) CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl, InsMap, ClsMap, C->getClassInterface()); } else assert(false && "invalid ObjCContainerDecl type."); } /// ActOnForwardClassDeclaration - Action::DeclPtrTy Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, IdentifierInfo **IdentList, unsigned NumElts) { llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces; for (unsigned i = 0; i != NumElts; ++i) { // Check for another declaration kind with the same name. NamedDecl *PrevDecl = LookupName(TUScope, IdentList[i], LookupOrdinaryName); if (PrevDecl && PrevDecl->isTemplateParameter()) { // Maybe we will complain about the shadowed template parameter. DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl); // Just pretend that we didn't see the previous declaration. PrevDecl = 0; } if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { // GCC apparently allows the following idiom: // // typedef NSObject < XCElementTogglerP > XCElementToggler; // @class XCElementToggler; // // FIXME: Make an extension? TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl); if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) { Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; Diag(PrevDecl->getLocation(), diag::note_previous_definition); } } ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); if (!IDecl) { // Not already seen? Make a forward decl. IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, IdentList[i], SourceLocation(), true); ObjCInterfaceDecls[IdentList[i]] = IDecl; // FIXME: PushOnScopeChains? CurContext->addDecl(Context, IDecl); // Remember that this needs to be removed when the scope is popped. TUScope->AddDecl(DeclPtrTy::make(IDecl)); } Interfaces.push_back(IDecl); } ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc, &Interfaces[0], Interfaces.size()); CurContext->addDecl(Context, CDecl); CheckObjCDeclScope(CDecl); return DeclPtrTy::make(CDecl); } /// MatchTwoMethodDeclarations - Checks that two methods have matching type and /// returns true, or false, accordingly. /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, bool matchBasedOnSizeAndAlignment) { QualType T1 = Context.getCanonicalType(Method->getResultType()); QualType T2 = Context.getCanonicalType(PrevMethod->getResultType()); if (T1 != T2) { // The result types are different. if (!matchBasedOnSizeAndAlignment) return false; // Incomplete types don't have a size and alignment. if (T1->isIncompleteType() || T2->isIncompleteType()) return false; // Check is based on size and alignment. if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2)) return false; } ObjCMethodDecl::param_iterator ParamI = Method->param_begin(), E = Method->param_end(); ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin(); for (; ParamI != E; ++ParamI, ++PrevI) { assert(PrevI != PrevMethod->param_end() && "Param mismatch"); T1 = Context.getCanonicalType((*ParamI)->getType()); T2 = Context.getCanonicalType((*PrevI)->getType()); if (T1 != T2) { // The result types are different. if (!matchBasedOnSizeAndAlignment) return false; // Incomplete types don't have a size and alignment. if (T1->isIncompleteType() || T2->isIncompleteType()) return false; // Check is based on size and alignment. if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2)) return false; } } return true; } void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) { ObjCMethodList &Entry = InstanceMethodPool[Method->getSelector()]; if (Entry.Method == 0) { // Haven't seen a method with this selector name yet - add it. Entry.Method = Method; Entry.Next = 0; return; } // We've seen a method with this name, see if we have already seen this type // signature. for (ObjCMethodList *List = &Entry; List; List = List->Next) if (MatchTwoMethodDeclarations(Method, List->Method)) return; // We have a new signature for an existing method - add it. // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". Entry.Next = new ObjCMethodList(Method, Entry.Next); } // FIXME: Finish implementing -Wno-strict-selector-match. ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R) { ObjCMethodList &MethList = InstanceMethodPool[Sel]; bool issueWarning = false; if (MethList.Method && MethList.Next) { for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) // This checks if the methods differ by size & alignment. if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true)) issueWarning = true; } if (issueWarning && (MethList.Method && MethList.Next)) { Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; Diag(MethList.Method->getLocStart(), diag::note_using_decl) << MethList.Method->getSourceRange(); for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) Diag(Next->Method->getLocStart(), diag::note_also_found_decl) << Next->Method->getSourceRange(); } return MethList.Method; } void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) { ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()]; if (!FirstMethod.Method) { // Haven't seen a method with this selector name yet - add it. FirstMethod.Method = Method; FirstMethod.Next = 0; } else { // We've seen a method with this name, now check the type signature(s). bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method); for (ObjCMethodList *Next = FirstMethod.Next; !match && Next; Next = Next->Next) match = MatchTwoMethodDeclarations(Method, Next->Method); if (!match) { // We have a new signature for an existing method - add it. // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next); FirstMethod.Next = OMI; } } } /// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods /// have the property type and issue diagnostics if they don't. /// Also synthesize a getter/setter method if none exist (and update the /// appropriate lookup tables. FIXME: Should reconsider if adding synthesized /// methods is the "right" thing to do. void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property, ObjCContainerDecl *CD) { ObjCMethodDecl *GetterMethod, *SetterMethod; GetterMethod = CD->getInstanceMethod(Context, property->getGetterName()); SetterMethod = CD->getInstanceMethod(Context, property->getSetterName()); if (GetterMethod && GetterMethod->getResultType() != property->getType()) { Diag(property->getLocation(), diag::err_accessor_property_type_mismatch) << property->getDeclName() << GetterMethod->getSelector(); Diag(GetterMethod->getLocation(), diag::note_declared_at); } if (SetterMethod) { if (Context.getCanonicalType(SetterMethod->getResultType()) != Context.VoidTy) Diag(SetterMethod->getLocation(), diag::err_setter_type_void); if (SetterMethod->param_size() != 1 || ((*SetterMethod->param_begin())->getType() != property->getType())) { Diag(property->getLocation(), diag::err_accessor_property_type_mismatch) << property->getDeclName() << SetterMethod->getSelector(); Diag(SetterMethod->getLocation(), diag::note_declared_at); } } // Synthesize getter/setter methods if none exist. // Find the default getter and if one not found, add one. // FIXME: The synthesized property we set here is misleading. We // almost always synthesize these methods unless the user explicitly // provided prototypes (which is odd, but allowed). Sema should be // typechecking that the declarations jive in that situation (which // it is not currently). if (!GetterMethod) { // No instance method of same name as property getter name was found. // Declare a getter method and add it to the list of methods // for this class. GetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(), property->getLocation(), property->getGetterName(), property->getType(), CD, true, false, true, (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) ? ObjCMethodDecl::Optional : ObjCMethodDecl::Required); CD->addDecl(Context, GetterMethod); } else // A user declared getter will be synthesize when @synthesize of // the property with the same name is seen in the @implementation GetterMethod->setIsSynthesized(); property->setGetterMethodDecl(GetterMethod); // Skip setter if property is read-only. if (!property->isReadOnly()) { // Find the default setter and if one not found, add one. if (!SetterMethod) { // No instance method of same name as property setter name was found. // Declare a setter method and add it to the list of methods // for this class. SetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(), property->getLocation(), property->getSetterName(), Context.VoidTy, CD, true, false, true, (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) ? ObjCMethodDecl::Optional : ObjCMethodDecl::Required); // Invent the arguments for the setter. We don't bother making a // nice name for the argument. ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod, property->getLocation(), property->getIdentifier(), property->getType(), VarDecl::None, 0); SetterMethod->setMethodParams(&Argument, 1, Context); CD->addDecl(Context, SetterMethod); } else // A user declared setter will be synthesize when @synthesize of // the property with the same name is seen in the @implementation SetterMethod->setIsSynthesized(); property->setSetterMethodDecl(SetterMethod); } // Add any synthesized methods to the global pool. This allows us to // handle the following, which is supported by GCC (and part of the design). // // @interface Foo // @property double bar; // @end // // void thisIsUnfortunate() { // id foo; // double bar = [foo bar]; // } // if (GetterMethod) AddInstanceMethodToGlobalPool(GetterMethod); if (SetterMethod) AddInstanceMethodToGlobalPool(SetterMethod); } // Note: For class/category implemenations, allMethods/allProperties is // always null. void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclPtrTy classDecl, DeclPtrTy *allMethods, unsigned allNum, DeclPtrTy *allProperties, unsigned pNum, DeclGroupPtrTy *allTUVars, unsigned tuvNum) { Decl *ClassDecl = classDecl.getAs<Decl>(); // FIXME: If we don't have a ClassDecl, we have an error. We should consider // always passing in a decl. If the decl has an error, isInvalidDecl() // should be true. if (!ClassDecl) return; bool isInterfaceDeclKind = isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) || isa<ObjCProtocolDecl>(ClassDecl); bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); DeclContext *DC = dyn_cast<DeclContext>(ClassDecl); // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; for (unsigned i = 0; i < allNum; i++ ) { ObjCMethodDecl *Method = cast_or_null<ObjCMethodDecl>(allMethods[i].getAs<Decl>()); if (!Method) continue; // Already issued a diagnostic. if (Method->isInstanceMethod()) { /// Check for instance method of the same name with incompatible types const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) : false; if ((isInterfaceDeclKind && PrevMethod && !match) || (checkIdenticalMethods && match)) { Diag(Method->getLocation(), diag::err_duplicate_method_decl) << Method->getDeclName(); Diag(PrevMethod->getLocation(), diag::note_previous_declaration); } else { DC->addDecl(Context, Method); InsMap[Method->getSelector()] = Method; /// The following allows us to typecheck messages to "id". AddInstanceMethodToGlobalPool(Method); } } else { /// Check for class method of the same name with incompatible types const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) : false; if ((isInterfaceDeclKind && PrevMethod && !match) || (checkIdenticalMethods && match)) { Diag(Method->getLocation(), diag::err_duplicate_method_decl) << Method->getDeclName(); Diag(PrevMethod->getLocation(), diag::note_previous_declaration); } else { DC->addDecl(Context, Method); ClsMap[Method->getSelector()] = Method; /// The following allows us to typecheck messages to "Class". AddFactoryMethodToGlobalPool(Method); } } } if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) { // Compares properties declared in this class to those of its // super class. ComparePropertiesInBaseAndSuper(I); MergeProtocolPropertiesIntoClass(I, DeclPtrTy::make(I)); } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { // Categories are used to extend the class by declaring new methods. // By the same token, they are also used to add new properties. No // need to compare the added property to those in the class. // Merge protocol properties into category MergeProtocolPropertiesIntoClass(C, DeclPtrTy::make(C)); if (C->getIdentifier() == 0) DiagnoseClassExtensionDupMethods(C, C->getClassInterface()); } if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { // ProcessPropertyDecl is responsible for diagnosing conflicts with any // user-defined setter/getter. It also synthesizes setter/getter methods // and adds them to the DeclContext and global method pools. for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(Context), E = CDecl->prop_end(Context); I != E; ++I) ProcessPropertyDecl(*I, CDecl); CDecl->setAtEndLoc(AtEndLoc); } if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { IC->setLocEnd(AtEndLoc); if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) ImplMethodsVsClassMethods(IC, IDecl); } else if (ObjCCategoryImplDecl* CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { CatImplClass->setLocEnd(AtEndLoc); // Find category interface decl and then check that all methods declared // in this interface are implemented in the category @implementation. if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { for (ObjCCategoryDecl *Categories = IDecl->getCategoryList(); Categories; Categories = Categories->getNextClassCategory()) { if (Categories->getIdentifier() == CatImplClass->getIdentifier()) { ImplMethodsVsClassMethods(CatImplClass, Categories); break; } } } } if (isInterfaceDeclKind) { // Reject invalid vardecls. for (unsigned i = 0; i != tuvNum; i++) { DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>(); for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { if (!VDecl->hasExternalStorage()) Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); } } } } /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for /// objective-c's type qualifier from the parser version of the same info. static Decl::ObjCDeclQualifier CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None; if (PQTVal & ObjCDeclSpec::DQ_In) ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In); if (PQTVal & ObjCDeclSpec::DQ_Inout) ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout); if (PQTVal & ObjCDeclSpec::DQ_Out) ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out); if (PQTVal & ObjCDeclSpec::DQ_Bycopy) ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy); if (PQTVal & ObjCDeclSpec::DQ_Byref) ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref); if (PQTVal & ObjCDeclSpec::DQ_Oneway) ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway); return ret; } Sema::DeclPtrTy Sema::ActOnMethodDeclaration( SourceLocation MethodLoc, SourceLocation EndLoc, tok::TokenKind MethodType, DeclPtrTy classDecl, ObjCDeclSpec &ReturnQT, TypeTy *ReturnType, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, llvm::SmallVectorImpl<Declarator> &Cdecls, AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, bool isVariadic) { Decl *ClassDecl = classDecl.getAs<Decl>(); // Make sure we can establish a context for the method. if (!ClassDecl) { Diag(MethodLoc, diag::error_missing_method_context); return DeclPtrTy(); } QualType resultDeclType; if (ReturnType) { resultDeclType = QualType::getFromOpaquePtr(ReturnType); // Methods cannot return interface types. All ObjC objects are // passed by reference. if (resultDeclType->isObjCInterfaceType()) { Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << resultDeclType; return DeclPtrTy(); } } else // get the type for "id". resultDeclType = Context.getObjCIdType(); ObjCMethodDecl* ObjCMethod = ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType, cast<DeclContext>(ClassDecl), MethodType == tok::minus, isVariadic, false, MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional : ObjCMethodDecl::Required); llvm::SmallVector<ParmVarDecl*, 16> Params; for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { QualType ArgType, UnpromotedArgType; if (ArgInfo[i].Type == 0) { UnpromotedArgType = ArgType = Context.getObjCIdType(); } else { UnpromotedArgType = ArgType = QualType::getFromOpaquePtr(ArgInfo[i].Type); // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). ArgType = adjustParameterType(ArgType); } ParmVarDecl* Param; if (ArgType == UnpromotedArgType) Param = ParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc, ArgInfo[i].Name, ArgType, VarDecl::None, 0); else Param = OriginalParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc, ArgInfo[i].Name, ArgType, UnpromotedArgType, VarDecl::None, 0); if (ArgType->isObjCInterfaceType()) { Diag(ArgInfo[i].NameLoc, diag::err_object_cannot_be_passed_returned_by_value) << 1 << ArgType; Param->setInvalidDecl(); } Param->setObjCDeclQualifier( CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); // Apply the attributes to the parameter. ProcessDeclAttributeList(Param, ArgInfo[i].ArgAttrs); Params.push_back(Param); } ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs(), Context); ObjCMethod->setObjCDeclQualifier( CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); const ObjCMethodDecl *PrevMethod = 0; if (AttrList) ProcessDeclAttributeList(ObjCMethod, AttrList); // For implementations (which can be very "coarse grain"), we add the // method now. This allows the AST to implement lookup methods that work // incrementally (without waiting until we parse the @end). It also allows // us to flag multiple declaration errors as they occur. if (ObjCImplementationDecl *ImpDecl = dyn_cast<ObjCImplementationDecl>(ClassDecl)) { if (MethodType == tok::minus) { PrevMethod = ImpDecl->getInstanceMethod(Sel); ImpDecl->addInstanceMethod(ObjCMethod); } else { PrevMethod = ImpDecl->getClassMethod(Sel); ImpDecl->addClassMethod(ObjCMethod); } } else if (ObjCCategoryImplDecl *CatImpDecl = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { if (MethodType == tok::minus) { PrevMethod = CatImpDecl->getInstanceMethod(Sel); CatImpDecl->addInstanceMethod(ObjCMethod); } else { PrevMethod = CatImpDecl->getClassMethod(Sel); CatImpDecl->addClassMethod(ObjCMethod); } } if (PrevMethod) { // You can never have two method definitions with the same name. Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) << ObjCMethod->getDeclName(); Diag(PrevMethod->getLocation(), diag::note_previous_declaration); } return DeclPtrTy::make(ObjCMethod); } void Sema::CheckObjCPropertyAttributes(QualType PropertyTy, SourceLocation Loc, unsigned &Attributes) { // FIXME: Improve the reported location. // readonly and readwrite/assign/retain/copy conflict. if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && (Attributes & (ObjCDeclSpec::DQ_PR_readwrite | ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain))) { const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ? "readwrite" : (Attributes & ObjCDeclSpec::DQ_PR_assign) ? "assign" : (Attributes & ObjCDeclSpec::DQ_PR_copy) ? "copy" : "retain"; Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ? diag::err_objc_property_attr_mutually_exclusive : diag::warn_objc_property_attr_mutually_exclusive) << "readonly" << which; } // Check for copy or retain on non-object types. if ((Attributes & (ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain)) && !Context.isObjCObjectPointerType(PropertyTy)) { Diag(Loc, diag::err_objc_property_requires_object) << (Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain"); Attributes &= ~(ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain); } // Check for more than one of { assign, copy, retain }. if (Attributes & ObjCDeclSpec::DQ_PR_assign) { if (Attributes & ObjCDeclSpec::DQ_PR_copy) { Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) << "assign" << "copy"; Attributes &= ~ObjCDeclSpec::DQ_PR_copy; } if (Attributes & ObjCDeclSpec::DQ_PR_retain) { Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) << "assign" << "retain"; Attributes &= ~ObjCDeclSpec::DQ_PR_retain; } } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) { if (Attributes & ObjCDeclSpec::DQ_PR_retain) { Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) << "copy" << "retain"; Attributes &= ~ObjCDeclSpec::DQ_PR_retain; } } // Warn if user supplied no assignment attribute, property is // readwrite, and this is an object type. if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain)) && !(Attributes & ObjCDeclSpec::DQ_PR_readonly) && Context.isObjCObjectPointerType(PropertyTy)) { // Skip this warning in gc-only mode. if (getLangOptions().getGCMode() != LangOptions::GCOnly) Diag(Loc, diag::warn_objc_property_no_assignment_attribute); // If non-gc code warn that this is likely inappropriate. if (getLangOptions().getGCMode() == LangOptions::NonGC) Diag(Loc, diag::warn_objc_property_default_assign_on_object); // FIXME: Implement warning dependent on NSCopying being // implemented. See also: // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496> // (please trim this list while you are at it). } } Sema::DeclPtrTy Sema::ActOnProperty(Scope *S, SourceLocation AtLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, DeclPtrTy ClassCategory, bool *isOverridingProperty, tok::ObjCKeywordKind MethodImplKind) { unsigned Attributes = ODS.getPropertyAttributes(); bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) || // default is readwrite! !(Attributes & ObjCDeclSpec::DQ_PR_readonly)); // property is defaulted to 'assign' if it is readwrite and is // not retain or copy bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) || (isReadWrite && !(Attributes & ObjCDeclSpec::DQ_PR_retain) && !(Attributes & ObjCDeclSpec::DQ_PR_copy))); QualType T = GetTypeForDeclarator(FD.D, S); Decl *ClassDecl = ClassCategory.getAs<Decl>(); ObjCInterfaceDecl *CCPrimary = 0; // continuation class's primary class // May modify Attributes. CheckObjCPropertyAttributes(T, AtLoc, Attributes); if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) if (!CDecl->getIdentifier()) { // This is a continuation class. property requires special // handling. if ((CCPrimary = CDecl->getClassInterface())) { // Find the property in continuation class's primary class only. ObjCPropertyDecl *PIDecl = 0; IdentifierInfo *PropertyId = FD.D.getIdentifier(); for (ObjCInterfaceDecl::prop_iterator I = CCPrimary->prop_begin(Context), E = CCPrimary->prop_end(Context); I != E; ++I) if ((*I)->getIdentifier() == PropertyId) { PIDecl = *I; break; } if (PIDecl) { // property 'PIDecl's readonly attribute will be over-ridden // with continuation class's readwrite property attribute! unsigned PIkind = PIDecl->getPropertyAttributes(); if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) { if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) != (PIkind & ObjCPropertyDecl::OBJC_PR_nonatomic)) Diag(AtLoc, diag::warn_property_attr_mismatch); PIDecl->makeitReadWriteAttribute(); if (Attributes & ObjCDeclSpec::DQ_PR_retain) PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain); if (Attributes & ObjCDeclSpec::DQ_PR_copy) PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy); PIDecl->setSetterName(SetterSel); } else Diag(AtLoc, diag::err_use_continuation_class) << CCPrimary->getDeclName(); *isOverridingProperty = true; // Make sure setter decl is synthesized, and added to primary // class's list. ProcessPropertyDecl(PIDecl, CCPrimary); return DeclPtrTy(); } // No matching property found in the primary class. Just fall thru // and add property to continuation class's primary class. ClassDecl = CCPrimary; } else { Diag(CDecl->getLocation(), diag::err_continuation_class); *isOverridingProperty = true; return DeclPtrTy(); } } DeclContext *DC = dyn_cast<DeclContext>(ClassDecl); assert(DC && "ClassDecl is not a DeclContext"); ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC, FD.D.getIdentifierLoc(), FD.D.getIdentifier(), T); DC->addDecl(Context, PDecl); if (T->isArrayType() || T->isFunctionType()) { Diag(AtLoc, diag::err_property_type) << T; PDecl->setInvalidDecl(); } ProcessDeclAttributes(PDecl, FD.D); // Regardless of setter/getter attribute, we save the default getter/setter // selector names in anticipation of declaration of setter/getter methods. PDecl->setGetterName(GetterSel); PDecl->setSetterName(SetterSel); if (Attributes & ObjCDeclSpec::DQ_PR_readonly) PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly); if (Attributes & ObjCDeclSpec::DQ_PR_getter) PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter); if (Attributes & ObjCDeclSpec::DQ_PR_setter) PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter); if (isReadWrite) PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite); if (Attributes & ObjCDeclSpec::DQ_PR_retain) PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain); if (Attributes & ObjCDeclSpec::DQ_PR_copy) PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy); if (isAssign) PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign); if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic) PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic); if (MethodImplKind == tok::objc_required) PDecl->setPropertyImplementation(ObjCPropertyDecl::Required); else if (MethodImplKind == tok::objc_optional) PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional); // A case of continuation class adding a new property in the class. This // is not what it was meant for. However, gcc supports it and so should we. // Make sure setter/getters are declared here. if (CCPrimary) ProcessPropertyDecl(PDecl, CCPrimary); return DeclPtrTy::make(PDecl); } /// ActOnPropertyImplDecl - This routine performs semantic checks and /// builds the AST node for a property implementation declaration; declared /// as @synthesize or @dynamic. /// Sema::DeclPtrTy Sema::ActOnPropertyImplDecl(SourceLocation AtLoc, SourceLocation PropertyLoc, bool Synthesize, DeclPtrTy ClassCatImpDecl, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar) { Decl *ClassImpDecl = ClassCatImpDecl.getAs<Decl>(); // Make sure we have a context for the property implementation declaration. if (!ClassImpDecl) { Diag(AtLoc, diag::error_missing_property_context); return DeclPtrTy(); } ObjCPropertyDecl *property = 0; ObjCInterfaceDecl* IDecl = 0; // Find the class or category class where this property must have // a declaration. ObjCImplementationDecl *IC = 0; ObjCCategoryImplDecl* CatImplClass = 0; if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) { IDecl = IC->getClassInterface(); // We always synthesize an interface for an implementation // without an interface decl. So, IDecl is always non-zero. assert(IDecl && "ActOnPropertyImplDecl - @implementation without @interface"); // Look for this property declaration in the @implementation's @interface property = IDecl->FindPropertyDeclaration(Context, PropertyId); if (!property) { Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName(); return DeclPtrTy(); } } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) { if (Synthesize) { Diag(AtLoc, diag::error_synthesize_category_decl); return DeclPtrTy(); } IDecl = CatImplClass->getClassInterface(); if (!IDecl) { Diag(AtLoc, diag::error_missing_property_interface); return DeclPtrTy(); } ObjCCategoryDecl *Category = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier()); // If category for this implementation not found, it is an error which // has already been reported eralier. if (!Category) return DeclPtrTy(); // Look for this property declaration in @implementation's category property = Category->FindPropertyDeclaration(Context, PropertyId); if (!property) { Diag(PropertyLoc, diag::error_bad_category_property_decl) << Category->getDeclName(); return DeclPtrTy(); } } else { Diag(AtLoc, diag::error_bad_property_context); return DeclPtrTy(); } ObjCIvarDecl *Ivar = 0; // Check that we have a valid, previously declared ivar for @synthesize if (Synthesize) { // @synthesize bool NoExplicitPropertyIvar = (!PropertyIvar); if (!PropertyIvar) PropertyIvar = PropertyId; QualType PropType = Context.getCanonicalType(property->getType()); // Check that this is a previously declared 'ivar' in 'IDecl' interface ObjCInterfaceDecl *ClassDeclared; Ivar = IDecl->lookupInstanceVariable(Context, PropertyIvar, ClassDeclared); if (!Ivar) { Ivar = ObjCIvarDecl::Create(Context, CurContext, PropertyLoc, PropertyIvar, PropType, ObjCIvarDecl::Public, (Expr *)0); property->setPropertyIvarDecl(Ivar); if (!getLangOptions().ObjCNonFragileABI) Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << PropertyId; // Note! I deliberately want it to fall thru so, we have a // a property implementation and to avoid future warnings. } else if (getLangOptions().ObjCNonFragileABI && NoExplicitPropertyIvar && ClassDeclared != IDecl) { Diag(PropertyLoc, diag::error_ivar_in_superclass_use) << property->getDeclName() << Ivar->getDeclName() << ClassDeclared->getDeclName(); Diag(Ivar->getLocation(), diag::note_previous_access_declaration) << Ivar << Ivar->getNameAsCString(); // Note! I deliberately want it to fall thru so more errors are caught. } QualType IvarType = Context.getCanonicalType(Ivar->getType()); // Check that type of property and its ivar are type compatible. if (PropType != IvarType) { if (CheckAssignmentConstraints(PropType, IvarType) != Compatible) { Diag(PropertyLoc, diag::error_property_ivar_type) << property->getDeclName() << Ivar->getDeclName(); // Note! I deliberately want it to fall thru so, we have a // a property implementation and to avoid future warnings. } // FIXME! Rules for properties are somewhat different that those // for assignments. Use a new routine to consolidate all cases; // specifically for property redeclarations as well as for ivars. QualType lhsType =Context.getCanonicalType(PropType).getUnqualifiedType(); QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType(); if (lhsType != rhsType && lhsType->isArithmeticType()) { Diag(PropertyLoc, diag::error_property_ivar_type) << property->getDeclName() << Ivar->getDeclName(); // Fall thru - see previous comment } // __weak is explicit. So it works on Canonical type. if (PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() && getLangOptions().getGCMode() != LangOptions::NonGC) { Diag(PropertyLoc, diag::error_weak_property) << property->getDeclName() << Ivar->getDeclName(); // Fall thru - see previous comment } if ((Context.isObjCObjectPointerType(property->getType()) || PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() && getLangOptions().getGCMode() != LangOptions::NonGC) { Diag(PropertyLoc, diag::error_strong_property) << property->getDeclName() << Ivar->getDeclName(); // Fall thru - see previous comment } } } else if (PropertyIvar) // @dynamic Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl); assert (property && "ActOnPropertyImplDecl - property declaration missing"); ObjCPropertyImplDecl *PIDecl = ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc, property, (Synthesize ? ObjCPropertyImplDecl::Synthesize : ObjCPropertyImplDecl::Dynamic), Ivar); CurContext->addDecl(Context, PIDecl); if (IC) { if (Synthesize) if (ObjCPropertyImplDecl *PPIDecl = IC->FindPropertyImplIvarDecl(PropertyIvar)) { Diag(PropertyLoc, diag::error_duplicate_ivar_use) << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier() << PropertyIvar; Diag(PPIDecl->getLocation(), diag::note_previous_use); } if (ObjCPropertyImplDecl *PPIDecl = IC->FindPropertyImplDecl(PropertyId)) { Diag(PropertyLoc, diag::error_property_implemented) << PropertyId; Diag(PPIDecl->getLocation(), diag::note_previous_declaration); return DeclPtrTy(); } IC->addPropertyImplementation(PIDecl); } else { if (Synthesize) if (ObjCPropertyImplDecl *PPIDecl = CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) { Diag(PropertyLoc, diag::error_duplicate_ivar_use) << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier() << PropertyIvar; Diag(PPIDecl->getLocation(), diag::note_previous_use); } if (ObjCPropertyImplDecl *PPIDecl = CatImplClass->FindPropertyImplDecl(PropertyId)) { Diag(PropertyLoc, diag::error_property_implemented) << PropertyId; Diag(PPIDecl->getLocation(), diag::note_previous_declaration); return DeclPtrTy(); } CatImplClass->addPropertyImplementation(PIDecl); } return DeclPtrTy::make(PIDecl); } bool Sema::CheckObjCDeclScope(Decl *D) { if (isa<TranslationUnitDecl>(CurContext->getLookupContext())) return false; Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); D->setInvalidDecl(); return true; } /// Collect the instance variables declared in an Objective-C object. Used in /// the creation of structures from objects using the @defs directive. /// FIXME: This should be consolidated with CollectObjCIvars as it is also /// part of the AST generation logic of @defs. static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record, ASTContext& Ctx, llvm::SmallVectorImpl<Sema::DeclPtrTy> &ivars) { if (Class->getSuperClass()) CollectIvars(Class->getSuperClass(), Record, Ctx, ivars); // For each ivar, create a fresh ObjCAtDefsFieldDecl. for (ObjCInterfaceDecl::ivar_iterator I = Class->ivar_begin(), E = Class->ivar_end(); I != E; ++I) { ObjCIvarDecl* ID = *I; Decl *FD = ObjCAtDefsFieldDecl::Create(Ctx, Record, ID->getLocation(), ID->getIdentifier(), ID->getType(), ID->getBitWidth()); ivars.push_back(Sema::DeclPtrTy::make(FD)); } } /// Called whenever @defs(ClassName) is encountered in the source. Inserts the /// instance variables of ClassName into Decls. void Sema::ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, llvm::SmallVectorImpl<DeclPtrTy> &Decls) { // Check that ClassName is a valid class ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName); if (!Class) { Diag(DeclStart, diag::err_undef_interface) << ClassName; return; } // Collect the instance variables CollectIvars(Class, dyn_cast<RecordDecl>(TagD.getAs<Decl>()), Context, Decls); // Introduce all of these fields into the appropriate scope. for (llvm::SmallVectorImpl<DeclPtrTy>::iterator D = Decls.begin(); D != Decls.end(); ++D) { FieldDecl *FD = cast<FieldDecl>(D->getAs<Decl>()); if (getLangOptions().CPlusPlus) PushOnScopeChains(cast<FieldDecl>(FD), S); else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>())) Record->addDecl(Context, FD); } } <file_sep>/test/CodeGen/libcalls.c // RUN: clang-cc -fmath-errno=1 -emit-llvm -o %t %s && // RUN: grep "declare " %t | count 6 && // RUN: grep "declare " %t | grep "@llvm." | count 1 && // RUN: clang-cc -fmath-errno=0 -emit-llvm -o %t %s && // RUN: grep "declare " %t | count 6 && // RUN: grep "declare " %t | grep -v "@llvm." | count 0 // IRgen only pays attention to const; it should always call llvm for // this. float sqrtf(float) __attribute__((const)); void test_sqrt(float a0, double a1, long double a2) { float l0 = sqrtf(a0); double l1 = sqrt(a1); long double l2 = sqrtl(a2); } void test_pow(float a0, double a1, long double a2) { float l0 = powf(a0, a0); double l1 = pow(a1, a1); long double l2 = powl(a2, a2); } <file_sep>/test/Analysis/outofbound.c // RUN: clang-cc -analyze -checker-simple -analyzer-store=region -verify %s char f1() { char* s = "abcd"; char c = s[4]; // no-warning return s[5] + c; // expected-warning{{Load or store into an out-of-bound memory position.}} } <file_sep>/lib/Driver/CMakeLists.txt set(LLVM_NO_RTTI 1) add_clang_library(clangDriver Action.cpp Arg.cpp ArgList.cpp Compilation.cpp Driver.cpp HostInfo.cpp Job.cpp OptTable.cpp Option.cpp Phases.cpp Tool.cpp ToolChain.cpp ToolChains.cpp Tools.cpp Types.cpp ) <file_sep>/test/SemaCXX/template-specialization.cpp // RUN: clang-cc -fsyntax-only -verify %s template<int N> void f(int (&array)[N]); template<> void f<1>(int (&array)[1]) { } <file_sep>/test/CodeGen/2008-07-17-no-emit-on-error.c // RUN: rm -f %t1.bc // RUN: not clang-cc %s -emit-llvm-bc -o %t1.bc // RUN: not test -f %t1.bc void f() { } void g() { *10; } <file_sep>/include/clang/Lex/PPCallbacks.h //===--- PPCallbacks.h - Callbacks for Preprocessor actions -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PPCallbacks interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PPCALLBACKS_H #define LLVM_CLANG_LEX_PPCALLBACKS_H #include "clang/Lex/DirectoryLookup.h" #include "clang/Basic/SourceLocation.h" #include <string> namespace clang { class SourceLocation; class IdentifierInfo; class MacroInfo; /// PPCallbacks - This interface provides a way to observe the actions of the /// preprocessor as it does its thing. Clients can define their hooks here to /// implement preprocessor level tools. class PPCallbacks { public: virtual ~PPCallbacks(); enum FileChangeReason { EnterFile, ExitFile, SystemHeaderPragma, RenameFile }; /// FileChanged - This callback is invoked whenever a source file is /// entered or exited. The SourceLocation indicates the new location, and /// EnteringFile indicates whether this is because we are entering a new /// #include'd file (when true) or whether we're exiting one because we ran /// off the end (when false). virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType) { } /// Ident - This callback is invoked when a #ident or #sccs directive is read. /// virtual void Ident(SourceLocation Loc, const std::string &str) { } /// PragmaComment - This callback is invoked when a #pragma comment directive /// is read. /// virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, const std::string &Str) { } /// MacroExpands - This is called by /// Preprocessor::HandleMacroExpandedIdentifier when a macro invocation is /// found. virtual void MacroExpands(const Token &Id, const MacroInfo* MI) { } /// MacroDefined - This hook is called whenever a macro definition is seen. virtual void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI) { } }; } // end namespace clang #endif <file_sep>/lib/Headers/CMakeLists.txt set(files iso646.h mmintrin.h stdarg.h stdbool.h stddef.h ) set(output_dir ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/../Headers) foreach( f ${files} ) set( src ${CMAKE_CURRENT_SOURCE_DIR}/${f} ) set( dst ${output_dir}/${f} ) add_custom_command(OUTPUT ${dst} DEPENDS ${src} COMMAND ${CMAKE_COMMAND} -E copy_if_different ${src} ${dst} COMMENT "Copying clang's ${f}...") endforeach( f ) add_custom_target(clang_headers ALL DEPENDS ${files}) install(FILES ${files} PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ DESTINATION Headers) <file_sep>/test/Preprocessor/macro_expand.c // RUN: clang-cc -E %s | grep '^Y$' #define X() Y #define Y() X X()()() <file_sep>/lib/Parse/ExtensionRAIIObject.h //===--- ExtensionRAIIObject.h - Use RAII for __extension__ -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines and implements the ExtensionRAIIObject class. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_EXTENSION_RAII_OBJECT_H #define LLVM_CLANG_PARSE_EXTENSION_RAII_OBJECT_H #include "clang/Parse/ParseDiagnostic.h" namespace clang { /// ExtensionRAIIObject - This saves the state of extension warnings when /// constructed and disables them. When destructed, it restores them back to /// the way they used to be. This is used to handle __extension__ in the /// parser. class ExtensionRAIIObject { void operator=(const ExtensionRAIIObject &); // DO NOT IMPLEMENT ExtensionRAIIObject(const ExtensionRAIIObject&); // DO NOT IMPLEMENT Diagnostic &Diags; public: ExtensionRAIIObject(Diagnostic &diags) : Diags(diags) { Diags.IncrementAllExtensionsSilenced(); } ~ExtensionRAIIObject() { Diags.DecrementAllExtensionsSilenced(); } }; } #endif <file_sep>/test/SemaTemplate/injected-class-name.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T> struct X { X<T*> *ptr; }; X<int> x; template<> struct X<int***> { typedef X<int***> *ptr; }; // FIXME: EDG rejects this in their strict-conformance mode, but I // don't see any wording making this ill-formed. X<float>::X<int> xi = x; <file_sep>/lib/Sema/SemaInherit.cpp //===---- SemaInherit.cpp - C++ Inheritance ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides Sema routines for C++ inheritance semantics, // including searching the inheritance hierarchy. // //===----------------------------------------------------------------------===// #include "SemaInherit.h" #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/Type.h" #include "clang/AST/TypeOrdering.h" #include <algorithm> #include <memory> #include <set> #include <string> using namespace clang; /// \brief Computes the set of declarations referenced by these base /// paths. void BasePaths::ComputeDeclsFound() { assert(NumDeclsFound == 0 && !DeclsFound && "Already computed the set of declarations"); std::set<NamedDecl *> Decls; for (BasePaths::paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path) Decls.insert(*Path->Decls.first); NumDeclsFound = Decls.size(); DeclsFound = new NamedDecl * [NumDeclsFound]; std::copy(Decls.begin(), Decls.end(), DeclsFound); } NamedDecl **BasePaths::found_decls_begin() { if (NumDeclsFound == 0) ComputeDeclsFound(); return DeclsFound; } NamedDecl **BasePaths::found_decls_end() { if (NumDeclsFound == 0) ComputeDeclsFound(); return DeclsFound + NumDeclsFound; } /// isAmbiguous - Determines whether the set of paths provided is /// ambiguous, i.e., there are two or more paths that refer to /// different base class subobjects of the same type. BaseType must be /// an unqualified, canonical class type. bool BasePaths::isAmbiguous(QualType BaseType) { assert(BaseType->isCanonical() && "Base type must be the canonical type"); assert(BaseType.getCVRQualifiers() == 0 && "Base type must be unqualified"); std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType]; return Subobjects.second + (Subobjects.first? 1 : 0) > 1; } /// clear - Clear out all prior path information. void BasePaths::clear() { Paths.clear(); ClassSubobjects.clear(); ScratchPath.clear(); DetectedVirtual = 0; } /// @brief Swaps the contents of this BasePaths structure with the /// contents of Other. void BasePaths::swap(BasePaths &Other) { std::swap(Origin, Other.Origin); Paths.swap(Other.Paths); ClassSubobjects.swap(Other.ClassSubobjects); std::swap(FindAmbiguities, Other.FindAmbiguities); std::swap(RecordPaths, Other.RecordPaths); std::swap(DetectVirtual, Other.DetectVirtual); std::swap(DetectedVirtual, Other.DetectedVirtual); } /// IsDerivedFrom - Determine whether the type Derived is derived from /// the type Base, ignoring qualifiers on Base and Derived. This /// routine does not assess whether an actual conversion from a /// Derived* to a Base* is legal, because it does not account for /// ambiguous conversions or conversions to private/protected bases. bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { BasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false, /*DetectVirtual=*/false); return IsDerivedFrom(Derived, Base, Paths); } /// IsDerivedFrom - Determine whether the type Derived is derived from /// the type Base, ignoring qualifiers on Base and Derived. This /// routine does not assess whether an actual conversion from a /// Derived* to a Base* is legal, because it does not account for /// ambiguous conversions or conversions to private/protected /// bases. This routine will use Paths to determine if there are /// ambiguous paths (if @c Paths.isFindingAmbiguities()) and record /// information about all of the paths (if @c Paths.isRecordingPaths()). bool Sema::IsDerivedFrom(QualType Derived, QualType Base, BasePaths &Paths) { Derived = Context.getCanonicalType(Derived).getUnqualifiedType(); Base = Context.getCanonicalType(Base).getUnqualifiedType(); if (!Derived->isRecordType() || !Base->isRecordType()) return false; if (Derived == Base) return false; Paths.setOrigin(Derived); return LookupInBases(cast<CXXRecordDecl>(Derived->getAsRecordType()->getDecl()), MemberLookupCriteria(Base), Paths); } /// LookupInBases - Look for something that meets the specified /// Criteria within the base classes of Class (or any of its base /// classes, transitively). This routine populates BasePaths with the /// list of paths that one can take to find the entity that meets the /// search criteria, and returns true if any such entity is found. The /// various options passed to the BasePath constructor will affect the /// behavior of this lookup, e.g., whether it finds ambiguities, /// records paths, or attempts to detect the use of virtual base /// classes. bool Sema::LookupInBases(CXXRecordDecl *Class, const MemberLookupCriteria& Criteria, BasePaths &Paths) { bool FoundPath = false; for (CXXRecordDecl::base_class_const_iterator BaseSpec = Class->bases_begin(), BaseSpecEnd = Class->bases_end(); BaseSpec != BaseSpecEnd; ++BaseSpec) { // Find the record of the base class subobjects for this type. QualType BaseType = Context.getCanonicalType(BaseSpec->getType()); BaseType = BaseType.getUnqualifiedType(); // Determine whether we need to visit this base class at all, // updating the count of subobjects appropriately. std::pair<bool, unsigned>& Subobjects = Paths.ClassSubobjects[BaseType]; bool VisitBase = true; bool SetVirtual = false; if (BaseSpec->isVirtual()) { VisitBase = !Subobjects.first; Subobjects.first = true; if (Paths.isDetectingVirtual() && Paths.DetectedVirtual == 0) { // If this is the first virtual we find, remember it. If it turns out // there is no base path here, we'll reset it later. Paths.DetectedVirtual = BaseType->getAsRecordType(); SetVirtual = true; } } else ++Subobjects.second; if (Paths.isRecordingPaths()) { // Add this base specifier to the current path. BasePathElement Element; Element.Base = &*BaseSpec; Element.Class = Class; if (BaseSpec->isVirtual()) Element.SubobjectNumber = 0; else Element.SubobjectNumber = Subobjects.second; Paths.ScratchPath.push_back(Element); } CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseSpec->getType()->getAsRecordType()->getDecl()); // Either look at the base class type or look into the base class // type to see if we've found a member that meets the search // criteria. bool FoundPathToThisBase = false; if (Criteria.LookupBase) { FoundPathToThisBase = (Context.getCanonicalType(BaseSpec->getType()) == Criteria.Base); } else { Paths.ScratchPath.Decls = BaseRecord->lookup(Context, Criteria.Name); while (Paths.ScratchPath.Decls.first != Paths.ScratchPath.Decls.second) { if (isAcceptableLookupResult(*Paths.ScratchPath.Decls.first, Criteria.NameKind, Criteria.IDNS)) { FoundPathToThisBase = true; break; } ++Paths.ScratchPath.Decls.first; } } if (FoundPathToThisBase) { // We've found a path that terminates that this base. FoundPath = true; if (Paths.isRecordingPaths()) { // We have a path. Make a copy of it before moving on. Paths.Paths.push_back(Paths.ScratchPath); } else if (!Paths.isFindingAmbiguities()) { // We found a path and we don't care about ambiguities; // return immediately. return FoundPath; } } // C++ [class.member.lookup]p2: // A member name f in one sub-object B hides a member name f in // a sub-object A if A is a base class sub-object of B. Any // declarations that are so hidden are eliminated from // consideration. else if (VisitBase && LookupInBases(BaseRecord, Criteria, Paths)) { // There is a path to a base class that meets the criteria. If we're not // collecting paths or finding ambiguities, we're done. FoundPath = true; if (!Paths.isFindingAmbiguities()) return FoundPath; } // Pop this base specifier off the current path (if we're // collecting paths). if (Paths.isRecordingPaths()) Paths.ScratchPath.pop_back(); // If we set a virtual earlier, and this isn't a path, forget it again. if (SetVirtual && !FoundPath) { Paths.DetectedVirtual = 0; } } return FoundPath; } /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base /// conversion (where Derived and Base are class types) is /// well-formed, meaning that the conversion is unambiguous (and /// that all of the base classes are accessible). Returns true /// and emits a diagnostic if the code is ill-formed, returns false /// otherwise. Loc is the location where this routine should point to /// if there is an error, and Range is the source range to highlight /// if there is an error. bool Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range) { // First, determine whether the path from Derived to Base is // ambiguous. This is slightly more expensive than checking whether // the Derived to Base conversion exists, because here we need to // explore multiple paths to determine if there is an ambiguity. BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/false); bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); assert(DerivationOkay && "Can only be used with a derived-to-base conversion"); (void)DerivationOkay; if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { // Check that the base class can be accessed. return CheckBaseClassAccess(Derived, Base, Paths, Loc); } // We know that the derived-to-base conversion is ambiguous, and // we're going to produce a diagnostic. Perform the derived-to-base // search just one more time to compute all of the possible paths so // that we can print them out. This is more expensive than any of // the previous derived-to-base checks we've done, but at this point // performance isn't as much of an issue. Paths.clear(); Paths.setRecordingPaths(true); bool StillOkay = IsDerivedFrom(Derived, Base, Paths); assert(StillOkay && "Can only be used with a derived-to-base conversion"); (void)StillOkay; // Build up a textual representation of the ambiguous paths, e.g., // D -> B -> A, that will be used to illustrate the ambiguous // conversions in the diagnostic. We only print one of the paths // to each base class subobject. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); Diag(Loc, diag::err_ambiguous_derived_to_base_conv) << Derived << Base << PathDisplayStr << Range; return true; } /// @brief Builds a string representing ambiguous paths from a /// specific derived class to different subobjects of the same base /// class. /// /// This function builds a string that can be used in error messages /// to show the different paths that one can take through the /// inheritance hierarchy to go from the derived class to different /// subobjects of a base class. The result looks something like this: /// @code /// struct D -> struct B -> struct A /// struct D -> struct C -> struct A /// @endcode std::string Sema::getAmbiguousPathsDisplayString(BasePaths &Paths) { std::string PathDisplayStr; std::set<unsigned> DisplayedPaths; for (BasePaths::paths_iterator Path = Paths.begin(); Path != Paths.end(); ++Path) { if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { // We haven't displayed a path to this particular base // class subobject yet. PathDisplayStr += "\n "; PathDisplayStr += Paths.getOrigin().getAsString(); for (BasePath::const_iterator Element = Path->begin(); Element != Path->end(); ++Element) PathDisplayStr += " -> " + Element->Base->getType().getAsString(); } } return PathDisplayStr; } <file_sep>/test/CodeGen/linkage-redecl.c // RUN: clang-cc -emit-llvm %s -o - |grep internal // C99 6.2.2p3 // PR3425 static void f(int x); void g0() { f(5); } extern void f(int x) { } // still has internal linkage <file_sep>/test/CodeGen/struct-x86-darwin.c // RUN: clang-cc < %s -emit-llvm > %t1 -triple=i686-apple-darwin9 // Run grep "STest1 = type <{ i32, \[4 x i16\], double }>" %t1 && // RUN: grep "STest2 = type <{ i16, i16, i32, i32 }>" %t1 && // RUN: grep "STest3 = type <{ i8, i8, i16, i32 }>" %t1 && // RUN: grep "STestB1 = type <{ i8, i8 }>" %t1 && // RUN: grep "STestB2 = type <{ i8, i8, i8 }>" %t1 && // RUN: grep "STestB3 = type <{ i8, i8 }>" %t1 && // RUN: grep "STestB4 = type <{ i8, i8, i8, i8 }>" %t1 && // RUN: grep "STestB5 = type <{ i8, i8, i8, i8, i8, i8 }>" %t1 && // RUN: grep "STestB6 = type <{ i8, i8, i8, i8 }>" %t1 // Test struct layout for x86-darwin target struct STest1 {int x; short y[4]; double z; } st1; struct STest2 {short a,b; int c,d; } st2; struct STest3 {char a; short b; int c; } st3; // Bitfields struct STestB1 {char a; char b:2; } stb1; struct STestB2 {char a; char b:5; char c:4; } stb2; struct STestB3 {char a; char b:2; } stb3; struct STestB4 {char a; short b:2; char c; } stb4; struct STestB5 {char a; short b:10; char c; } stb5; struct STestB6 {int a:1; char b; int c:13 } stb6; // Packed struct STestP1 {char a; short b; int c; } __attribute__((__packed__)) stp1; <file_sep>/test/CodeGen/bitfield-init.c // RUN: clang-cc %s -emit-llvm -o %t typedef struct { unsigned int i: 1; } c; const c d = { 1 }; // PR2310 struct Token { unsigned n : 31; }; void sqlite3CodeSubselect(){ struct Token one = { 1 }; } <file_sep>/test/SemaCXX/linkage-spec.cpp // RUN: clang-cc -fsyntax-only -verify %s extern "C" { extern "C" void f(int); } extern "C++" { extern "C++" int& g(int); float& g(); } double& g(double); void test(int x, double d) { f(x); float &f1 = g(); int& i1 = g(x); double& d1 = g(d); } extern "C" int foo; extern "C" int foo; extern "C" const int bar; extern "C" int const bar; <file_sep>/lib/CodeGen/CodeGenTypes.cpp //===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the code that handles AST -> LLVM type lowering. // //===----------------------------------------------------------------------===// #include "CodeGenTypes.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Expr.h" #include "clang/AST/RecordLayout.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Target/TargetData.h" #include "CGCall.h" using namespace clang; using namespace CodeGen; namespace { /// RecordOrganizer - This helper class, used by CGRecordLayout, layouts /// structs and unions. It manages transient information used during layout. /// FIXME : Handle field aligments. Handle packed structs. class RecordOrganizer { public: explicit RecordOrganizer(CodeGenTypes &Types, const RecordDecl& Record) : CGT(Types), RD(Record), STy(NULL) {} /// layoutStructFields - Do the actual work and lay out all fields. Create /// corresponding llvm struct type. This should be invoked only after /// all fields are added. void layoutStructFields(const ASTRecordLayout &RL); /// layoutUnionFields - Do the actual work and lay out all fields. Create /// corresponding llvm struct type. This should be invoked only after /// all fields are added. void layoutUnionFields(const ASTRecordLayout &RL); /// getLLVMType - Return associated llvm struct type. This may be NULL /// if fields are not laid out. llvm::Type *getLLVMType() const { return STy; } llvm::SmallSet<unsigned, 8> &getPaddingFields() { return PaddingFields; } private: CodeGenTypes &CGT; const RecordDecl& RD; llvm::Type *STy; llvm::SmallSet<unsigned, 8> PaddingFields; }; } CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M, const llvm::TargetData &TD) : Context(Ctx), Target(Ctx.Target), TheModule(M), TheTargetData(TD), TheABIInfo(0) { } CodeGenTypes::~CodeGenTypes() { for(llvm::DenseMap<const Type *, CGRecordLayout *>::iterator I = CGRecordLayouts.begin(), E = CGRecordLayouts.end(); I != E; ++I) delete I->second; CGRecordLayouts.clear(); } /// ConvertType - Convert the specified type to its LLVM form. const llvm::Type *CodeGenTypes::ConvertType(QualType T) { llvm::PATypeHolder Result = ConvertTypeRecursive(T); // Any pointers that were converted defered evaluation of their pointee type, // creating an opaque type instead. This is in order to avoid problems with // circular types. Loop through all these defered pointees, if any, and // resolve them now. while (!PointersToResolve.empty()) { std::pair<QualType, llvm::OpaqueType*> P = PointersToResolve.back(); PointersToResolve.pop_back(); // We can handle bare pointers here because we know that the only pointers // to the Opaque type are P.second and from other types. Refining the // opqaue type away will invalidate P.second, but we don't mind :). const llvm::Type *NT = ConvertTypeForMemRecursive(P.first); P.second->refineAbstractTypeTo(NT); } return Result; } const llvm::Type *CodeGenTypes::ConvertTypeRecursive(QualType T) { T = Context.getCanonicalType(T); // See if type is already cached. llvm::DenseMap<Type *, llvm::PATypeHolder>::iterator I = TypeCache.find(T.getTypePtr()); // If type is found in map and this is not a definition for a opaque // place holder type then use it. Otherwise, convert type T. if (I != TypeCache.end()) return I->second.get(); const llvm::Type *ResultType = ConvertNewType(T); TypeCache.insert(std::make_pair(T.getTypePtr(), llvm::PATypeHolder(ResultType))); return ResultType; } const llvm::Type *CodeGenTypes::ConvertTypeForMemRecursive(QualType T) { const llvm::Type *ResultType = ConvertTypeRecursive(T); if (ResultType == llvm::Type::Int1Ty) return llvm::IntegerType::get((unsigned)Context.getTypeSize(T)); return ResultType; } /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from /// ConvertType in that it is used to convert to the memory representation for /// a type. For example, the scalar representation for _Bool is i1, but the /// memory representation is usually i8 or i32, depending on the target. const llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) { const llvm::Type *R = ConvertType(T); // If this is a non-bool type, don't map it. if (R != llvm::Type::Int1Ty) return R; // Otherwise, return an integer of the target-specified size. return llvm::IntegerType::get((unsigned)Context.getTypeSize(T)); } // Code to verify a given function type is complete, i.e. the return type // and all of the argument types are complete. static const TagType *VerifyFuncTypeComplete(const Type* T) { const FunctionType *FT = cast<FunctionType>(T); if (const TagType* TT = FT->getResultType()->getAsTagType()) if (!TT->getDecl()->isDefinition()) return TT; if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(T)) for (unsigned i = 0; i < FPT->getNumArgs(); i++) if (const TagType* TT = FPT->getArgType(i)->getAsTagType()) if (!TT->getDecl()->isDefinition()) return TT; return 0; } /// UpdateCompletedType - When we find the full definition for a TagDecl, /// replace the 'opaque' type we previously made for it if applicable. void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) { const Type *Key = Context.getTagDeclType(const_cast<TagDecl*>(TD)).getTypePtr(); llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI = TagDeclTypes.find(Key); if (TDTI == TagDeclTypes.end()) return; // Remember the opaque LLVM type for this tagdecl. llvm::PATypeHolder OpaqueHolder = TDTI->second; assert(isa<llvm::OpaqueType>(OpaqueHolder.get()) && "Updating compilation of an already non-opaque type?"); // Remove it from TagDeclTypes so that it will be regenerated. TagDeclTypes.erase(TDTI); // Generate the new type. const llvm::Type *NT = ConvertTagDeclType(TD); // Refine the old opaque type to its new definition. cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NT); // Since we just completed a tag type, check to see if any function types // were completed along with the tag type. // FIXME: This is very inefficient; if we track which function types depend // on which tag types, though, it should be reasonably efficient. llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator i; for (i = FunctionTypes.begin(); i != FunctionTypes.end(); ++i) { if (const TagType* TT = VerifyFuncTypeComplete(i->first)) { // This function type still depends on an incomplete tag type; make sure // that tag type has an associated opaque type. ConvertTagDeclType(TT->getDecl()); } else { // This function no longer depends on an incomplete tag type; create the // function type, and refine the opaque type to the new function type. llvm::PATypeHolder OpaqueHolder = i->second; const llvm::Type *NFT = ConvertNewType(QualType(i->first, 0)); cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NFT); FunctionTypes.erase(i); } } } void CodeGenTypes::UpdateCompletedType(const ObjCInterfaceDecl *OID) { // Check to see if we have already laid this type out, if not, just return. QualType OIDTy = Context.getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID)); llvm::DenseMap<Type *, llvm::PATypeHolder>::iterator TCI = TypeCache.find(OIDTy.getTypePtr()); if (TCI == TypeCache.end()) return; // Remember the opaque LLVM type for this interface. llvm::PATypeHolder OpaqueHolder = TCI->second; assert(isa<llvm::OpaqueType>(OpaqueHolder.get()) && "Updating compilation of an already non-opaque type?"); // Remove it from TagDeclTypes so that it will be regenerated. TypeCache.erase(TCI); // Update the "shadow" struct that is laid out. // FIXME: REMOVE THIS. const RecordDecl *RD = Context.addRecordToClass(OID); UpdateCompletedType(RD); // Generate the new type. const llvm::Type *NT = ConvertType(OIDTy); assert(!isa<llvm::OpaqueType>(NT) && "Didn't do layout!"); // FIXME: Remove this check when shadow structs go away. if (isa<llvm::OpaqueType>(OpaqueHolder)) { // Refine the old opaque type to its new definition. cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NT); } } static const llvm::Type* getTypeForFormat(const llvm::fltSemantics &format) { if (&format == &llvm::APFloat::IEEEsingle) return llvm::Type::FloatTy; if (&format == &llvm::APFloat::IEEEdouble) return llvm::Type::DoubleTy; if (&format == &llvm::APFloat::IEEEquad) return llvm::Type::FP128Ty; if (&format == &llvm::APFloat::PPCDoubleDouble) return llvm::Type::PPC_FP128Ty; if (&format == &llvm::APFloat::x87DoubleExtended) return llvm::Type::X86_FP80Ty; assert(0 && "Unknown float format!"); return 0; } const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { const clang::Type &Ty = *Context.getCanonicalType(T); switch (Ty.getTypeClass()) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: #define DEPENDENT_TYPE(Class, Base) case Type::Class: #include "clang/AST/TypeNodes.def" assert(false && "Non-canonical or dependent types aren't possible."); break; case Type::Builtin: { switch (cast<BuiltinType>(Ty).getKind()) { default: assert(0 && "Unknown builtin type!"); case BuiltinType::Void: // LLVM void type can only be used as the result of a function call. Just // map to the same as char. return llvm::IntegerType::get(8); case BuiltinType::Bool: // Note that we always return bool as i1 for use as a scalar type. return llvm::Type::Int1Ty; case BuiltinType::Char_S: case BuiltinType::Char_U: case BuiltinType::SChar: case BuiltinType::UChar: case BuiltinType::Short: case BuiltinType::UShort: case BuiltinType::Int: case BuiltinType::UInt: case BuiltinType::Long: case BuiltinType::ULong: case BuiltinType::LongLong: case BuiltinType::ULongLong: case BuiltinType::WChar: return llvm::IntegerType::get( static_cast<unsigned>(Context.getTypeSize(T))); case BuiltinType::Float: case BuiltinType::Double: case BuiltinType::LongDouble: return getTypeForFormat(Context.getFloatTypeSemantics(T)); } break; } case Type::FixedWidthInt: return llvm::IntegerType::get(cast<FixedWidthIntType>(T)->getWidth()); case Type::Complex: { const llvm::Type *EltTy = ConvertTypeRecursive(cast<ComplexType>(Ty).getElementType()); return llvm::StructType::get(EltTy, EltTy, NULL); } case Type::LValueReference: case Type::RValueReference: { const ReferenceType &RTy = cast<ReferenceType>(Ty); QualType ETy = RTy.getPointeeType(); llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(); PointersToResolve.push_back(std::make_pair(ETy, PointeeType)); return llvm::PointerType::get(PointeeType, ETy.getAddressSpace()); } case Type::Pointer: { const PointerType &PTy = cast<PointerType>(Ty); QualType ETy = PTy.getPointeeType(); llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(); PointersToResolve.push_back(std::make_pair(ETy, PointeeType)); return llvm::PointerType::get(PointeeType, ETy.getAddressSpace()); } case Type::VariableArray: { const VariableArrayType &A = cast<VariableArrayType>(Ty); assert(A.getIndexTypeQualifier() == 0 && "FIXME: We only handle trivial array types so far!"); // VLAs resolve to the innermost element type; this matches // the return of alloca, and there isn't any obviously better choice. return ConvertTypeForMemRecursive(A.getElementType()); } case Type::IncompleteArray: { const IncompleteArrayType &A = cast<IncompleteArrayType>(Ty); assert(A.getIndexTypeQualifier() == 0 && "FIXME: We only handle trivial array types so far!"); // int X[] -> [0 x int] return llvm::ArrayType::get(ConvertTypeForMemRecursive(A.getElementType()), 0); } case Type::ConstantArray: { const ConstantArrayType &A = cast<ConstantArrayType>(Ty); const llvm::Type *EltTy = ConvertTypeForMemRecursive(A.getElementType()); return llvm::ArrayType::get(EltTy, A.getSize().getZExtValue()); } case Type::ExtVector: case Type::Vector: { const VectorType &VT = cast<VectorType>(Ty); return llvm::VectorType::get(ConvertTypeRecursive(VT.getElementType()), VT.getNumElements()); } case Type::FunctionNoProto: case Type::FunctionProto: { // First, check whether we can build the full function type. if (const TagType* TT = VerifyFuncTypeComplete(&Ty)) { // This function's type depends on an incomplete tag type; make sure // we have an opaque type corresponding to the tag type. ConvertTagDeclType(TT->getDecl()); // Create an opaque type for this function type, save it, and return it. llvm::Type *ResultType = llvm::OpaqueType::get(); FunctionTypes.insert(std::make_pair(&Ty, ResultType)); return ResultType; } // The function type can be built; call the appropriate routines to // build it. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(&Ty)) return GetFunctionType(getFunctionInfo(FPT), FPT->isVariadic()); const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(&Ty); return GetFunctionType(getFunctionInfo(FNPT), true); } case Type::ExtQual: return ConvertTypeRecursive(QualType(cast<ExtQualType>(Ty).getBaseType(), 0)); case Type::ObjCQualifiedInterface: { // Lower foo<P1,P2> just like foo. ObjCInterfaceDecl *ID = cast<ObjCQualifiedInterfaceType>(Ty).getDecl(); return ConvertTypeRecursive(Context.getObjCInterfaceType(ID)); } case Type::ObjCInterface: { ObjCInterfaceDecl *ID = cast<ObjCInterfaceType>(Ty).getDecl(); return ConvertTagDeclType(Context.addRecordToClass(ID)); } case Type::ObjCQualifiedId: case Type::ObjCQualifiedClass: // Protocols don't influence the LLVM type. return ConvertTypeRecursive(Context.getObjCIdType()); case Type::Record: case Type::Enum: { const TagDecl *TD = cast<TagType>(Ty).getDecl(); const llvm::Type *Res = ConvertTagDeclType(TD); std::string TypeName(TD->getKindName()); TypeName += '.'; // Name the codegen type after the typedef name // if there is no tag type name available if (TD->getIdentifier()) TypeName += TD->getNameAsString(); else if (const TypedefType *TdT = dyn_cast<TypedefType>(T)) TypeName += TdT->getDecl()->getNameAsString(); else TypeName += "anon"; TheModule.addTypeName(TypeName, Res); return Res; } case Type::BlockPointer: { const QualType FTy = cast<BlockPointerType>(Ty).getPointeeType(); llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(); PointersToResolve.push_back(std::make_pair(FTy, PointeeType)); return llvm::PointerType::get(PointeeType, FTy.getAddressSpace()); } case Type::MemberPointer: // FIXME: Implement C++ pointer-to-member. The GCC representation is // documented here: // http://gcc.gnu.org/onlinedocs/gccint/Type-Layout.html#Type-Layout assert(0 && "FIXME: We can't handle member pointers yet."); return llvm::OpaqueType::get(); case Type::TemplateSpecialization: assert(false && "Dependent types can't get here"); } // FIXME: implement. return llvm::OpaqueType::get(); } /// ConvertTagDeclType - Lay out a tagged decl type like struct or union or /// enum. const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) { // TagDecl's are not necessarily unique, instead use the (clang) // type connected to the decl. const Type *Key = Context.getTagDeclType(const_cast<TagDecl*>(TD)).getTypePtr(); llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI = TagDeclTypes.find(Key); // If we've already compiled this tag type, use the previous definition. if (TDTI != TagDeclTypes.end()) return TDTI->second; // If this is still a forward definition, just define an opaque type to use // for this tagged decl. if (!TD->isDefinition()) { llvm::Type *ResultType = llvm::OpaqueType::get(); TagDeclTypes.insert(std::make_pair(Key, ResultType)); return ResultType; } // Okay, this is a definition of a type. Compile the implementation now. if (TD->isEnum()) { // Don't bother storing enums in TagDeclTypes. return ConvertTypeRecursive(cast<EnumDecl>(TD)->getIntegerType()); } // This decl could well be recursive. In this case, insert an opaque // definition of this type, which the recursive uses will get. We will then // refine this opaque version later. // Create new OpaqueType now for later use in case this is a recursive // type. This will later be refined to the actual type. llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get(); TagDeclTypes.insert(std::make_pair(Key, ResultHolder)); const llvm::Type *ResultType; const RecordDecl *RD = cast<const RecordDecl>(TD); if (TD->isStruct() || TD->isClass()) { // Layout fields. RecordOrganizer RO(*this, *RD); RO.layoutStructFields(Context.getASTRecordLayout(RD)); // Get llvm::StructType. const Type *Key = Context.getTagDeclType(const_cast<TagDecl*>(TD)).getTypePtr(); CGRecordLayouts[Key] = new CGRecordLayout(RO.getLLVMType(), RO.getPaddingFields()); ResultType = RO.getLLVMType(); } else if (TD->isUnion()) { // Just use the largest element of the union, breaking ties with the // highest aligned member. if (!RD->field_empty(getContext())) { RecordOrganizer RO(*this, *RD); RO.layoutUnionFields(Context.getASTRecordLayout(RD)); // Get llvm::StructType. const Type *Key = Context.getTagDeclType(const_cast<TagDecl*>(TD)).getTypePtr(); CGRecordLayouts[Key] = new CGRecordLayout(RO.getLLVMType(), RO.getPaddingFields()); ResultType = RO.getLLVMType(); } else { ResultType = llvm::StructType::get(std::vector<const llvm::Type*>()); } } else { assert(0 && "FIXME: Unknown tag decl kind!"); abort(); } // Refine our Opaque type to ResultType. This can invalidate ResultType, so // make sure to read the result out of the holder. cast<llvm::OpaqueType>(ResultHolder.get()) ->refineAbstractTypeTo(ResultType); return ResultHolder.get(); } /// getLLVMFieldNo - Return llvm::StructType element number /// that corresponds to the field FD. unsigned CodeGenTypes::getLLVMFieldNo(const FieldDecl *FD) { llvm::DenseMap<const FieldDecl*, unsigned>::iterator I = FieldInfo.find(FD); assert (I != FieldInfo.end() && "Unable to find field info"); return I->second; } /// addFieldInfo - Assign field number to field FD. void CodeGenTypes::addFieldInfo(const FieldDecl *FD, unsigned No) { FieldInfo[FD] = No; } /// getBitFieldInfo - Return the BitFieldInfo that corresponds to the field FD. CodeGenTypes::BitFieldInfo CodeGenTypes::getBitFieldInfo(const FieldDecl *FD) { llvm::DenseMap<const FieldDecl *, BitFieldInfo>::iterator I = BitFields.find(FD); assert (I != BitFields.end() && "Unable to find bitfield info"); return I->second; } /// addBitFieldInfo - Assign a start bit and a size to field FD. void CodeGenTypes::addBitFieldInfo(const FieldDecl *FD, unsigned Begin, unsigned Size) { BitFields.insert(std::make_pair(FD, BitFieldInfo(Begin, Size))); } /// getCGRecordLayout - Return record layout info for the given llvm::Type. const CGRecordLayout * CodeGenTypes::getCGRecordLayout(const TagDecl *TD) const { const Type *Key = Context.getTagDeclType(const_cast<TagDecl*>(TD)).getTypePtr(); llvm::DenseMap<const Type*, CGRecordLayout *>::iterator I = CGRecordLayouts.find(Key); assert (I != CGRecordLayouts.end() && "Unable to find record layout information for type"); return I->second; } /// layoutStructFields - Do the actual work and lay out all fields. Create /// corresponding llvm struct type. /// Note that this doesn't actually try to do struct layout; it depends on /// the layout built by the AST. (We have to do struct layout to do Sema, /// and there's no point to duplicating the work.) void RecordOrganizer::layoutStructFields(const ASTRecordLayout &RL) { // FIXME: This code currently always generates packed structures. // Unpacked structures are more readable, and sometimes more efficient! // (But note that any changes here are likely to impact CGExprConstant, // which makes some messy assumptions.) uint64_t llvmSize = 0; // FIXME: Make this a SmallVector std::vector<const llvm::Type*> LLVMFields; unsigned curField = 0; for (RecordDecl::field_iterator Field = RD.field_begin(CGT.getContext()), FieldEnd = RD.field_end(CGT.getContext()); Field != FieldEnd; ++Field) { uint64_t offset = RL.getFieldOffset(curField); const llvm::Type *Ty = CGT.ConvertTypeForMemRecursive(Field->getType()); uint64_t size = CGT.getTargetData().getTypePaddedSizeInBits(Ty); if (Field->isBitField()) { Expr *BitWidth = Field->getBitWidth(); llvm::APSInt FieldSize(32); bool isBitField = BitWidth->isIntegerConstantExpr(FieldSize, CGT.getContext()); assert(isBitField && "Invalid BitField size expression"); isBitField=isBitField; // silence warning. uint64_t BitFieldSize = FieldSize.getZExtValue(); // Bitfield field info is different from other field info; // it actually ignores the underlying LLVM struct because // there isn't any convenient mapping. CGT.addFieldInfo(*Field, offset / size); CGT.addBitFieldInfo(*Field, offset % size, BitFieldSize); } else { // Put the element into the struct. This would be simpler // if we didn't bother, but it seems a bit too strange to // allocate all structs as i8 arrays. while (llvmSize < offset) { LLVMFields.push_back(llvm::Type::Int8Ty); llvmSize += 8; } llvmSize += size; CGT.addFieldInfo(*Field, LLVMFields.size()); LLVMFields.push_back(Ty); } ++curField; } while (llvmSize < RL.getSize()) { LLVMFields.push_back(llvm::Type::Int8Ty); llvmSize += 8; } STy = llvm::StructType::get(LLVMFields, true); assert(CGT.getTargetData().getTypePaddedSizeInBits(STy) == RL.getSize()); } /// layoutUnionFields - Do the actual work and lay out all fields. Create /// corresponding llvm struct type. This should be invoked only after /// all fields are added. void RecordOrganizer::layoutUnionFields(const ASTRecordLayout &RL) { unsigned curField = 0; for (RecordDecl::field_iterator Field = RD.field_begin(CGT.getContext()), FieldEnd = RD.field_end(CGT.getContext()); Field != FieldEnd; ++Field) { // The offset should usually be zero, but bitfields could be strange uint64_t offset = RL.getFieldOffset(curField); CGT.ConvertTypeRecursive(Field->getType()); if (Field->isBitField()) { Expr *BitWidth = Field->getBitWidth(); uint64_t BitFieldSize = BitWidth->getIntegerConstantExprValue(CGT.getContext()).getZExtValue(); CGT.addFieldInfo(*Field, 0); CGT.addBitFieldInfo(*Field, offset, BitFieldSize); } else { CGT.addFieldInfo(*Field, 0); } ++curField; } // This looks stupid, but it is correct in the sense that // it works no matter how complicated the sizes and alignments // of the union elements are. The natural alignment // of the result doesn't matter because anyone allocating // structures should be aligning them appropriately anyway. // FIXME: We can be a bit more intuitive in a lot of cases. // FIXME: Make this a struct type to work around PR2399; the // C backend doesn't like structs using array types. std::vector<const llvm::Type*> LLVMFields; LLVMFields.push_back(llvm::ArrayType::get(llvm::Type::Int8Ty, RL.getSize() / 8)); STy = llvm::StructType::get(LLVMFields, true); assert(CGT.getTargetData().getTypePaddedSizeInBits(STy) == RL.getSize()); } <file_sep>/test/Driver/lto.c // -emit-llvm, -flto, and -O4 all cause a switch to llvm-bc object // files. // RUN: clang -ccc-print-phases -c %s -flto 2> %t.log && // RUN: grep '2: compiler, {1}, llvm-bc' %t.log && // RUN: clang -ccc-print-phases -c %s -O4 2> %t.log && // RUN: grep '2: compiler, {1}, llvm-bc' %t.log && // and -emit-llvm doesn't alter pipeline (unfortunately?). // RUN: clang -ccc-print-phases %s -emit-llvm 2> %t.log && // RUN: grep '0: input, ".*lto.c", c' %t.log && // RUN: grep '1: preprocessor, {0}, cpp-output' %t.log && // RUN: grep '2: compiler, {1}, llvm-bc' %t.log && // RUN: grep '3: linker, {2}, image' %t.log && // llvm-bc and llvm-ll outputs need to match regular suffixes // (unfortunately). // RUN: clang %s -emit-llvm -save-temps -### 2> %t.log && // RUN: grep '"-o" ".*lto\.i" "-x" "c" ".*lto\.c"' %t.log && // RUN: grep '"-o" ".*lto\.o" .*".*lto\.i"' %t.log && // RUN: grep '".*a.out" .*".*lto\.o"' %t.log && // RUN: clang %s -emit-llvm -S -### 2> %t.log && // RUN: grep '"-o" ".*lto\.s" "-x" "c" ".*lto\.c"' %t.log && // RUN: true <file_sep>/lib/Parse/AstGuard.h //===--- AstGuard.h - Parser Ownership Tracking Utilities -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines RAII objects for managing ExprTy* and StmtTy*. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_ASTGUARD_H #define LLVM_CLANG_PARSE_ASTGUARD_H #include "clang/Parse/Action.h" #include "llvm/ADT/SmallVector.h" namespace clang { /// RAII SmallVector wrapper that holds Action::ExprTy* and similar, /// automatically freeing them on destruction unless it's been disowned. /// Instantiated for statements and expressions (Action::DeleteStmt and /// Action::DeleteExpr). template <ASTDestroyer Destroyer, unsigned N> class ASTVector : public llvm::SmallVector<void*, N> { private: #if !defined(DISABLE_SMART_POINTERS) Action &Actions; bool Owns; void destroy() { if (Owns) { while (!this->empty()) { (Actions.*Destroyer)(this->back()); this->pop_back(); } } } ASTVector(const ASTVector&); // DO NOT IMPLEMENT // Reference member prevents copy assignment. #endif public: #if !defined(DISABLE_SMART_POINTERS) ASTVector(Action &actions) : Actions(actions), Owns(true) {} ~ASTVector() { destroy(); } #else ASTVector(Action &) {} #endif void **take() { #if !defined(DISABLE_SMART_POINTERS) Owns = false; #endif return &(*this)[0]; } #if !defined(DISABLE_SMART_POINTERS) Action &getActions() const { return Actions; } #endif }; /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef ASTVector<&Action::DeleteStmt, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef ASTVector<&Action::DeleteExpr, 12> ExprVector; template <ASTDestroyer Destroyer, unsigned N> inline ASTMultiPtr<Destroyer> move_arg(ASTVector<Destroyer, N> &vec) { #if !defined(DISABLE_SMART_POINTERS) return ASTMultiPtr<Destroyer>(vec.getActions(), vec.take(), vec.size()); #else return ASTMultiPtr<Destroyer>(vec.take(), vec.size()); #endif } } #endif <file_sep>/tools/ccc/ccclib/ToolChain.py import os import Arguments import Phases import Tools import Types ### class ToolChain(object): """ToolChain - Provide mappings of Actions to Tools.""" def __init__(self, driver, archName, filePathPrefixes=[], programPathPrefixes=[]): self.driver = driver self.archName = archName self.filePathPrefixes = list(filePathPrefixes) self.programPathPrefixes = list(programPathPrefixes) def getFilePath(self, name): return self.driver.getFilePath(name, self) def getProgramPath(self, name): return self.driver.getProgramPath(name, self) def selectTool(self, action): """selectTool - Return a Tool instance to use for handling some particular action.""" abstract def translateArgs(self, args, arch): """translateArgs - Callback to allow argument translation for an entire toolchain.""" # FIXME: Would be nice to move arch handling out of generic # code. if arch: archName = args.getValue(arch) al = Arguments.DerivedArgList(args) for arg in args.args: if arg.opt is args.parser.archOption: if arg is arch: al.append(arg) elif arg.opt is args.parser.XarchOption: if args.getJoinedValue(arg) == archName: # FIXME: Fix this. arg = args.parser.lookupOptForArg(Arguments.InputIndex(0, arg.index.pos + 1), args.getSeparateValue(arg), iter([])) al.append(arg) else: al.append(arg) return al else: return args def shouldUseClangCompiler(self, action): # If user requested no clang, or this isn't a "compile" phase, # or this isn't an input clang understands, then don't use clang. if (self.driver.cccNoClang or not isinstance(action.phase, (Phases.PreprocessPhase, Phases.CompilePhase, Phases.SyntaxOnlyPhase, Phases.EmitLLVMPhase, Phases.PrecompilePhase)) or action.inputs[0].type not in Types.clangableTypesSet): return False if self.driver.cccNoClangPreprocessor: if isinstance(action.phase, Phases.PreprocessPhase): return False if self.driver.cccNoClangCXX: if action.inputs[0].type in Types.cxxTypesSet: return False # Don't use clang if this isn't one of the user specified # archs to build. if (self.driver.cccClangArchs and self.archName not in self.driver.cccClangArchs): return False return True def isMathErrnoDefault(self): return True def isUnwindTablesDefault(self): # FIXME: Target hook. if self.archName == 'x86_64': return True return False def getDefaultRelocationModel(self): return 'static' def getForcedPicModel(self): return class Darwin_X86_ToolChain(ToolChain): def __init__(self, driver, archName, darwinVersion, gccVersion): super(Darwin_X86_ToolChain, self).__init__(driver, archName) assert isinstance(darwinVersion, tuple) and len(darwinVersion) == 3 assert isinstance(gccVersion, tuple) and len(gccVersion) == 3 self.darwinVersion = darwinVersion self.gccVersion = gccVersion self.clangTool = Tools.Clang_CompileTool(self) cc = Tools.Darwin_X86_CompileTool(self) self.toolMap = { Phases.PreprocessPhase : Tools.Darwin_X86_PreprocessTool(self), Phases.AnalyzePhase : self.clangTool, Phases.SyntaxOnlyPhase : cc, Phases.EmitLLVMPhase : cc, Phases.CompilePhase : cc, Phases.PrecompilePhase : cc, Phases.AssemblePhase : Tools.Darwin_AssembleTool(self), Phases.LinkPhase : Tools.Darwin_X86_LinkTool(self), Phases.LipoPhase : Tools.LipoTool(self), } if archName == 'x86_64': self.filePathPrefixes.append(os.path.join(self.driver.driverDir, '../lib/gcc', self.getToolChainDir(), 'x86_64')) self.filePathPrefixes.append(os.path.join('/usr/lib/gcc', self.getToolChainDir(), 'x86_64')) self.filePathPrefixes.append(os.path.join(self.driver.driverDir, '../lib/gcc', self.getToolChainDir())) self.filePathPrefixes.append(os.path.join('/usr/lib/gcc', self.getToolChainDir())) self.programPathPrefixes.append(os.path.join(self.driver.driverDir, '../libexec/gcc', self.getToolChainDir())) self.programPathPrefixes.append(os.path.join('/usr/libexec/gcc', self.getToolChainDir())) self.programPathPrefixes.append(os.path.join(self.driver.driverDir, '../libexec')) self.programPathPrefixes.append(self.driver.driverDir) def getToolChainDir(self): return 'i686-apple-darwin%d/%s' % (self.darwinVersion[0], '.'.join(map(str,self.gccVersion))) def getMacosxVersionMin(self): major,minor,minorminor = self.darwinVersion return '%d.%d.%d' % (10, major-4, minor) def selectTool(self, action): assert isinstance(action, Phases.JobAction) if self.shouldUseClangCompiler(action): return self.clangTool return self.toolMap[action.phase.__class__] def translateArgs(self, args, arch): args = super(Darwin_X86_ToolChain, self).translateArgs(args, arch) # If arch hasn't been bound we don't need to do anything yet. if not arch: return args # FIXME: We really want to get out of the tool chain level # argument translation business, as it makes the driver # functionality much more opaque. For now, we follow gcc # closely solely for the purpose of easily achieving feature # parity & testability. Once we have something that works, we # should reevaluate each translation and try to push it down # into tool specific logic. al = Arguments.DerivedArgList(args) if not args.getLastArg(args.parser.m_macosxVersionMinOption): al.append(al.makeJoinedArg(self.getMacosxVersionMin(), args.parser.m_macosxVersionMinOption)) for arg in args: # Sob. These is strictly gcc compatible for the time # being. Apple gcc translates options twice, which means # that self-expanding options add duplicates. if arg.opt is args.parser.m_kernelOption: al.append(arg) al.append(al.makeFlagArg(args.parser.staticOption)) al.append(al.makeFlagArg(args.parser.staticOption)) elif arg.opt is args.parser.dependencyFileOption: al.append(al.makeSeparateArg(args.getValue(arg), args.parser.MFOption)) elif arg.opt is args.parser.gfullOption: al.append(al.makeFlagArg(args.parser.gOption)) al.append(al.makeFlagArg(args.parser.f_noEliminateUnusedDebugSymbolsOption)) elif arg.opt is args.parser.gusedOption: al.append(al.makeFlagArg(args.parser.gOption)) al.append(al.makeFlagArg(args.parser.f_eliminateUnusedDebugSymbolsOption)) elif arg.opt is args.parser.f_appleKextOption: al.append(arg) al.append(al.makeFlagArg(args.parser.staticOption)) al.append(al.makeFlagArg(args.parser.staticOption)) elif arg.opt is args.parser.f_terminatedVtablesOption: al.append(al.makeFlagArg(args.parser.f_appleKextOption)) al.append(al.makeFlagArg(args.parser.staticOption)) elif arg.opt is args.parser.f_indirectVirtualCallsOption: al.append(al.makeFlagArg(args.parser.f_appleKextOption)) al.append(al.makeFlagArg(args.parser.staticOption)) elif arg.opt is args.parser.sharedOption: al.append(al.makeFlagArg(args.parser.dynamiclibOption)) elif arg.opt is args.parser.f_constantCfstringsOption: al.append(al.makeFlagArg(args.parser.m_constantCfstringsOption)) elif arg.opt is args.parser.f_noConstantCfstringsOption: al.append(al.makeFlagArg(args.parser.m_noConstantCfstringsOption)) elif arg.opt is args.parser.WnonportableCfstringsOption: al.append(al.makeFlagArg(args.parser.m_warnNonportableCfstringsOption)) elif arg.opt is args.parser.WnoNonportableCfstringsOption: al.append(al.makeFlagArg(args.parser.m_noWarnNonportableCfstringsOption)) elif arg.opt is args.parser.f_pascalStringsOption: al.append(al.makeFlagArg(args.parser.m_pascalStringsOption)) elif arg.opt is args.parser.f_noPascalStringsOption: al.append(al.makeFlagArg(args.parser.m_noPascalStringsOption)) else: al.append(arg) # FIXME: Actually, gcc always adds this, but it is filtered # for duplicates somewhere. This also changes the order of # things, so look it up. if arch and args.getValue(arch) == 'x86_64': if not args.getLastArg(args.parser.m_64Option): al.append(al.makeFlagArg(args.parser.m_64Option)) if not args.getLastArg(args.parser.m_tuneOption): al.append(al.makeJoinedArg('core2', args.parser.m_tuneOption)) return al def isMathErrnoDefault(self): return False def getDefaultRelocationModel(self): return 'pic' def getForcedPicModel(self): if self.archName == 'x86_64': return 'pic' class Generic_GCC_ToolChain(ToolChain): """Generic_GCC_ToolChain - A tool chain using the 'gcc' command to perform all subcommands; this relies on gcc translating the options appropriately.""" def __init__(self, driver, archName): super(Generic_GCC_ToolChain, self).__init__(driver, archName) cc = Tools.GCC_CompileTool(self) self.clangTool = Tools.Clang_CompileTool(self) self.toolMap = { Phases.PreprocessPhase : Tools.GCC_PreprocessTool(self), Phases.AnalyzePhase : self.clangTool, Phases.SyntaxOnlyPhase : cc, Phases.EmitLLVMPhase : cc, Phases.CompilePhase : cc, Phases.PrecompilePhase : Tools.GCC_PrecompileTool(self), Phases.AssemblePhase : Tools.GCC_AssembleTool(self), Phases.LinkPhase : Tools.GCC_LinkTool(self), } self.programPathPrefixes.append(os.path.join(self.driver.driverDir, '../libexec')) self.programPathPrefixes.append(self.driver.driverDir) def selectTool(self, action): assert isinstance(action, Phases.JobAction) if self.shouldUseClangCompiler(action): return self.clangTool return self.toolMap[action.phase.__class__] class Darwin_GCC_ToolChain(Generic_GCC_ToolChain): def getRelocationModel(self, picEnabled, picDisabled): if picEnabled: return 'pic' elif picDisabled: return 'static' else: return 'dynamic-no-pic' <file_sep>/tools/ccc/test/ccc/argument-types.c // Input argument: // RUN: xcc -ccc-print-options %s | grep 'Name: "<input>", Values: {"%s"}' | count 1 && // Joined or separate arguments: // RUN: xcc -ccc-print-options -xc -x c | grep 'Name: "-x", Values: {"c"}' | count 2 && // Joined and separate arguments: // RUN: xcc -ccc-print-options -Xarch_mips -run | grep 'Name: "-Xarch_", Values: {"mips", "-run"}' | count 1 && // Multiple arguments: // RUN: xcc -ccc-print-options -sectorder 1 2 3 | grep 'Name: "-sectorder", Values: {"1", "2", "3"}' | count 1 && // Unknown argument: // RUN: xcc -ccc-print-options -=== | grep 'Name: "<unknown>", Values: {"-==="}' | count 1 && // RUN: true <file_sep>/include/clang/Basic/TypeTraits.h //===--- TypeTraits.h - C++ Type Traits Support Enumerations ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines enumerations for the type traits support. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TYPETRAITS_H #define LLVM_CLANG_TYPETRAITS_H namespace clang { /// UnaryTypeTrait - Names for the unary type traits. enum UnaryTypeTrait { UTT_HasNothrowAssign, UTT_HasNothrowCopy, UTT_HasNothrowConstructor, UTT_HasTrivialAssign, UTT_HasTrivialCopy, UTT_HasTrivialConstructor, UTT_HasTrivialDestructor, UTT_HasVirtualDestructor, UTT_IsAbstract, UTT_IsClass, UTT_IsEmpty, UTT_IsEnum, UTT_IsPOD, UTT_IsPolymorphic, UTT_IsUnion }; } #endif <file_sep>/test/Preprocessor/line-directive.c // RUN: clang-cc -fsyntax-only -verify -pedantic %s && // RUN: clang-cc -E %s 2>&1 | grep 'blonk.c:92:2: error: #error ABC' && // RUN: clang-cc -E %s 2>&1 | grep 'blonk.c:93:2: error: #error DEF' #line 'a' // expected-error {{#line directive requires a positive integer argument}} #line 0 // expected-error {{#line directive requires a positive integer argument}} #line 2147483648 // expected-warning {{C requires #line number to be less than 2147483648, allowed as extension}} #line 42 // ok #line 42 'a' // expected-error {{invalid filename for #line directive}} #line 42 "foo/bar/baz.h" // ok // #line directives expand macros. #define A 42 "foo" #line A # 42 # 42 "foo" # 42 "foo" 2 // expected-error {{invalid line marker flag '2': cannot pop empty include stack}} # 42 "foo" 1 3 // enter # 42 "foo" 2 3 // exit # 42 "foo" 2 3 4 // expected-error {{invalid line marker flag '2': cannot pop empty include stack}} # 42 "foo" 3 4 # 'a' // expected-error {{invalid preprocessing directive}} # 42 'f' // expected-error {{invalid filename for line marker directive}} # 42 1 3 // expected-error {{invalid filename for line marker directive}} # 42 "foo" 3 1 // expected-error {{invalid flag line marker directive}} # 42 "foo" 42 // expected-error {{invalid flag line marker directive}} # 42 "foo" 1 2 // expected-error {{invalid flag line marker directive}} // These are checked by the RUN line. #line 92 "blonk.c" #error ABC // expected-error {{#error ABC}} #error DEF // expected-error {{#error DEF}} // Verify that linemarker diddling of the system header flag works. # 192 "glomp.h" // not a system header. typedef int x; // expected-note {{previous definition is here}} typedef int x; // expected-error {{redefinition of 'x'}} # 192 "glomp.h" 3 // System header. typedef int y; // ok typedef int y; // ok #line 42 "blonk.h" // doesn't change system headerness. typedef int z; // ok typedef int z; // ok # 97 // doesn't change system headerness. typedef int z1; // ok typedef int z1; // ok # 42 "blonk.h" // DOES change system headerness. typedef int w; // expected-note {{previous definition is here}} typedef int w; // expected-error {{redefinition of 'w'}} <file_sep>/include/clang/AST/DeclNodes.def //===-- DeclNodes.def - Metadata about Decl AST nodes -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the declaration nodes within the AST. The // description of the declaration nodes uses six macros: // // DECL(Derived, Base) describes a normal declaration type Derived // and specifies its base class. Note that Derived should not have // the Decl suffix on it, while Base should. // // LAST_DECL(Derived, Base) is like DECL, but is used for the last // declaration in the list. // // ABSTRACT_DECL(Derived, Base) describes an abstract class that is // used to specify a classification of declarations. For example, // TagDecl is an abstract class used to describe the various kinds of // "tag" declarations (unions, structs, classes, enums). // // DECL_CONTEXT(Decl) specifies that Decl is a kind of declaration // that is also a DeclContext. // // LAST_DECL_CONTEXT(Decl) is like DECL_CONTEXT, but is used for the // last declaration context. // // DECL_RANGE(CommonBase, Start, End) specifies a range of // declaration values that have a common (potentially indirect) base // class. // // LAST_DECL_RANGE(CommonBase, Start, End) is like DECL_RANGE, but is // used for the last declaration range. // // Note that, due to the use of ranges, the order of the these // declarations is significant. A declaration should be listed under // its base class. // ===----------------------------------------------------------------------===// #ifndef DECL # define DECL(Derived, Base) #endif #ifndef LAST_DECL # define LAST_DECL(Derived, Base) DECL(Derived, Base) #endif #ifndef ABSTRACT_DECL # define ABSTRACT_DECL(Derived, Base) #endif #ifndef DECL_CONTEXT # define DECL_CONTEXT(Decl) #endif #ifndef DECL_CONTEXT_BASE # define DECL_CONTEXT_BASE(Decl) DECL_CONTEXT(Decl) #endif #ifndef LAST_DECL_CONTEXT # define LAST_DECL_CONTEXT(Decl) DECL_CONTEXT(Decl) #endif #ifndef DECL_RANGE # define DECL_RANGE(CommonBase, Start, End) #endif #ifndef LAST_DECL_RANGE # define LAST_DECL_RANGE(CommonBase, Start, End) \ DECL_RANGE(CommonBase, Start, End) #endif DECL(TranslationUnit, Decl) ABSTRACT_DECL(Named, Decl) DECL(OverloadedFunction, NamedDecl) DECL(Namespace, NamedDecl) DECL(UsingDirective, NamedDecl) DECL(NamespaceAlias, NamedDecl) ABSTRACT_DECL(Type, NamedDecl) DECL(Typedef, TypeDecl) ABSTRACT_DECL(Tag, TypeDecl) DECL(Enum, TagDecl) DECL(Record, TagDecl) DECL(CXXRecord, RecordDecl) DECL(ClassTemplateSpecialization, CXXRecordDecl) DECL(TemplateTypeParm, TypeDecl) ABSTRACT_DECL(Value, NamedDecl) DECL(EnumConstant, ValueDecl) DECL(Function, ValueDecl) DECL(CXXMethod, FunctionDecl) DECL(CXXConstructor, CXXMethodDecl) DECL(CXXDestructor, CXXMethodDecl) DECL(CXXConversion, CXXMethodDecl) DECL(Field, ValueDecl) DECL(ObjCIvar, FieldDecl) DECL(ObjCAtDefsField, FieldDecl) DECL(Var, ValueDecl) DECL(ImplicitParam, VarDecl) DECL(ParmVar, VarDecl) DECL(OriginalParmVar, ParmVarDecl) DECL(NonTypeTemplateParm, VarDecl) DECL(Template, NamedDecl) DECL(FunctionTemplate, TemplateDecl) DECL(ClassTemplate, TemplateDecl) DECL(TemplateTemplateParm, TemplateDecl) DECL(ObjCMethod, NamedDecl) DECL(ObjCContainer, NamedDecl) DECL(ObjCCategory, ObjCContainerDecl) DECL(ObjCProtocol, ObjCContainerDecl) DECL(ObjCInterface, ObjCContainerDecl) DECL(ObjCProperty, NamedDecl) DECL(ObjCCompatibleAlias, NamedDecl) ABSTRACT_DECL(ObjCImpl, Decl) DECL(ObjCCategoryImpl, ObjCImplDecl) DECL(ObjCImplementation, ObjCImplDecl) DECL(LinkageSpec, Decl) DECL(ObjCPropertyImpl, Decl) DECL(ObjCForwardProtocol, Decl) DECL(ObjCClass, Decl) DECL(FileScopeAsm, Decl) DECL(StaticAssert, Decl) LAST_DECL(Block, Decl) // Declaration contexts. DECL_CONTEXT_BASE indicates that it has subclasses. DECL_CONTEXT(TranslationUnit) DECL_CONTEXT(Namespace) DECL_CONTEXT(LinkageSpec) DECL_CONTEXT(ObjCMethod) DECL_CONTEXT(ObjCCategoryImpl) DECL_CONTEXT(ObjCImplementation) DECL_CONTEXT_BASE(Tag) DECL_CONTEXT_BASE(Function) DECL_CONTEXT_BASE(ObjCContainer) LAST_DECL_CONTEXT(Block) // Declaration ranges DECL_RANGE(Named, OverloadedFunction, ObjCCompatibleAlias) DECL_RANGE(ObjCContainer, ObjCContainer, ObjCInterface) DECL_RANGE(Field, Field, ObjCAtDefsField) DECL_RANGE(Type, Typedef, TemplateTypeParm) DECL_RANGE(Tag, Enum, ClassTemplateSpecialization) DECL_RANGE(Record, Record, ClassTemplateSpecialization) DECL_RANGE(Value, EnumConstant, NonTypeTemplateParm) DECL_RANGE(Function, Function, CXXConversion) DECL_RANGE(Template, Template, TemplateTemplateParm) DECL_RANGE(ObjCImpl, ObjCCategoryImpl, ObjCImplementation) LAST_DECL_RANGE(Var, Var, NonTypeTemplateParm) #undef LAST_DECL_RANGE #undef DECL_RANGE #undef LAST_DECL_CONTEXT #undef DECL_CONTEXT_BASE #undef DECL_CONTEXT #undef ABSTRACT_DECL #undef LAST_DECL #undef DECL <file_sep>/test/CodeGen/empty-union-init.c // RUN: clang-cc -emit-llvm < %s -o - // PR2419 struct Mem { union { } u; }; struct Mem *columnMem(){ static const struct Mem nullMem = { {} }; } <file_sep>/test/CodeGen/statements.c // RUN: clang-cc < %s -emit-llvm void test1(int x) { switch (x) { case 111111111111111111111111111111111111111: bar(); } } // Mismatched type between return and function result. int test2() { return; } void test3() { return 4; } <file_sep>/tools/ccc/ccclib/Phases.py import Util class Action(object): def __init__(self, inputs, type): self.inputs = inputs self.type = type class BindArchAction(Action): """BindArchAction - Represent an architecture binding for child actions.""" def __init__(self, input, arch): super(BindArchAction, self).__init__([input], input.type) self.arch = arch def __repr__(self): return Util.prefixAndPPrint(self.__class__.__name__, (self.inputs[0], self.arch)) class InputAction(Action): """InputAction - Adapt an input file to an action & type. """ def __init__(self, filename, type): super(InputAction, self).__init__([], type) self.filename = filename def __repr__(self): return Util.prefixAndPPrint(self.__class__.__name__, (self.filename, self.type)) class JobAction(Action): """JobAction - Represent a job tied to a particular compilation phase.""" def __init__(self, phase, inputs, type): super(JobAction, self).__init__(inputs, type) self.phase = phase def __repr__(self): return Util.prefixAndPPrint(self.__class__.__name__, (self.phase, self.inputs, self.type)) ### class Phase(object): """Phase - Represent an abstract task in the compilation pipeline.""" eOrderNone = 0 eOrderPreprocess = 1 eOrderCompile = 2 eOrderAssemble = 3 eOrderPostAssemble = 4 def __init__(self, name, order): self.name = name self.order = order def __repr__(self): return Util.prefixAndPPrint(self.__class__.__name__, (self.name, self.order)) class PreprocessPhase(Phase): def __init__(self): super(PreprocessPhase, self).__init__("preprocessor", Phase.eOrderPreprocess) class PrecompilePhase(Phase): def __init__(self): super(PrecompilePhase, self).__init__("precompiler", Phase.eOrderCompile) class AnalyzePhase(Phase): def __init__(self): super(AnalyzePhase, self).__init__("analyzer", Phase.eOrderCompile) class SyntaxOnlyPhase(Phase): def __init__(self): super(SyntaxOnlyPhase, self).__init__("syntax-only", Phase.eOrderCompile) class EmitLLVMPhase(Phase): def __init__(self): super(EmitLLVMPhase, self).__init__("emit-llvm", Phase.eOrderCompile) class CompilePhase(Phase): def __init__(self): super(CompilePhase, self).__init__("compiler", Phase.eOrderCompile) class AssemblePhase(Phase): def __init__(self): super(AssemblePhase, self).__init__("assembler", Phase.eOrderAssemble) class LinkPhase(Phase): def __init__(self): super(LinkPhase, self).__init__("linker", Phase.eOrderPostAssemble) class LipoPhase(Phase): def __init__(self): super(LipoPhase, self).__init__("lipo", Phase.eOrderPostAssemble) <file_sep>/include/clang/Driver/Options.def //===--- Options.def - Driver option info -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the driver option information. Users of this file // must define the OPTION macro to make use of this information. // //===----------------------------------------------------------------------===// #ifndef OPTION #error "Define OPTION prior to including this file!" #endif // OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, // HELPTEXT, METAVARNAME) // The NAME value is the option name as a string. // The ID is the internal option id, which must be a valid // C++ identifier, and results in a clang::driver::options::OPT_XX // enum constant for XX. // // We want to unambiguously be able to refer to options from the // driver source code, for this reason the option name is mangled into // an id. This mangling isn't guaranteed to have an inverse, but for // practical purposes it does. // // The mangling scheme is to ignore the leading '-', and perform the // following substitutions: // _ => __ // - => _ // # => _HASH // , => _COMMA // = => _EQ // C++ => CXX // The KIND value is the option type, one of Group, Flag, Joined, // Separate, CommaJoined, JoinedOrSeparate, JoinedAndSeparate. // The GROUP value is the internal name of the option group, or // INVALID if the option is not part of a group. // The ALIAS value is the internal name of an aliased option, or // INVALID if the option is not an alias. // The PARAM value is a string containing option flags. Valid values: // d: The option is a "driver" option, and should not be forwarded to // gcc. // // i: The option should not render the name when rendered as an // input (i.e., the option is rendered as values). // // l: The option is a linker input. // // q: Don't report argument unused warnings for this option; this is // useful for options like -static or -dynamic which a user may // always end up passing, even if the platform defaults to (or // only supports) that option. // // u: The option is unsupported, and the driver will reject command // lines that use it. // // S: The option should be rendered separately, even if joined (only // sensible on joined options). // // J: The option should be rendered joined, even if separate (only // sensible on single value separate options). // The PARAM value is an arbitrary integer parameter; currently // this is only used for specifying the number of arguments for // Separate options. // The HELPTEXT value is the string to print for this option in // --help, or 0 if undocumented. // The METAVAR value is the name to use for this values arguments (if // any) in the help text. This must be defined if the help text is // specified and this option takes extra arguments. // // For now (pre-TableGen, that is) Options must be in order. The // ordering is *almost* lexicographic, with two exceptions. First, // '\0' comes at the end of the alphabet instead of the beginning // (thus options preceed any other options which prefix them). Second, // for options with the same name, the less permissive version should // come first; a Flag option should preceed a Joined option, for // example. ///////// // Groups OPTION("<I group>", I_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<M group>", M_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<T group>", T_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<O group>", O_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<W group>", W_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<X group>", X_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<a group>", a_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<d group>", d_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<f group>", f_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<g group>", g_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<i group>", i_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<clang i group>", clang_i_Group, Group, i_Group, INVALID, "", 0, 0, 0) OPTION("<m group>", m_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<u group>", u_Group, Group, INVALID, INVALID, "", 0, 0, 0) OPTION("<pedantic group>", pedantic_Group, Group, INVALID, INVALID, "", 0, 0, 0) // Temporary groups for clang options which we know we don't support, // but don't want to verbosely warn the user about. OPTION("<clang ignored f group>", clang_ignored_f_Group, Group, f_Group, INVALID, "", 0, 0, 0) OPTION("<clang ignored m group>", clang_ignored_m_Group, Group, m_Group, INVALID, "", 0, 0, 0) ////////// // Options OPTION("-###", _HASH_HASH_HASH, Flag, INVALID, INVALID, "d", 0, "Print the commands to run for this compilation", 0) OPTION("--CLASSPATH=", _CLASSPATH_EQ, Joined, INVALID, fclasspath_EQ, "", 0, 0, 0) OPTION("--CLASSPATH", _CLASSPATH, Separate, INVALID, fclasspath_EQ, "J", 0, 0, 0) OPTION("--all-warnings", _all_warnings, Flag, INVALID, Wall, "", 0, 0, 0) OPTION("--analyze", _analyze, Flag, INVALID, INVALID, "d", 0, "Run the static analyzer", 0) OPTION("--ansi", _ansi, Flag, INVALID, ansi, "", 0, 0, 0) OPTION("--assemble", _assemble, Flag, INVALID, S, "", 0, 0, 0) OPTION("--assert=", _assert_EQ, Joined, INVALID, A, "S", 0, 0, 0) OPTION("--assert", _assert, Separate, INVALID, A, "", 0, 0, 0) OPTION("--bootclasspath=", _bootclasspath_EQ, Joined, INVALID, fbootclasspath_EQ, "", 0, 0, 0) OPTION("--bootclasspath", _bootclasspath, Separate, INVALID, fbootclasspath_EQ, "J", 0, 0, 0) OPTION("--classpath=", _classpath_EQ, Joined, INVALID, fclasspath_EQ, "", 0, 0, 0) OPTION("--classpath", _classpath, Separate, INVALID, fclasspath_EQ, "J", 0, 0, 0) OPTION("--combine", _combine, Flag, INVALID, combine, "u", 0, 0, 0) OPTION("--comments-in-macros", _comments_in_macros, Flag, INVALID, CC, "", 0, 0, 0) OPTION("--comments", _comments, Flag, INVALID, C, "", 0, 0, 0) OPTION("--compile", _compile, Flag, INVALID, c, "", 0, 0, 0) OPTION("--constant-cfstrings", _constant_cfstrings, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("--coverage", _coverage, Flag, INVALID, coverage, "", 0, 0, 0) OPTION("--debug=", _debug_EQ, Joined, INVALID, g_Flag, "u", 0, 0, 0) OPTION("--debug", _debug, Flag, INVALID, g_Flag, "u", 0, 0, 0) OPTION("--define-macro=", _define_macro_EQ, Joined, INVALID, D, "", 0, 0, 0) OPTION("--define-macro", _define_macro, Separate, INVALID, D, "J", 0, 0, 0) OPTION("--dependencies", _dependencies, Flag, INVALID, M, "", 0, 0, 0) OPTION("--encoding=", _encoding_EQ, Joined, INVALID, fencoding_EQ, "", 0, 0, 0) OPTION("--encoding", _encoding, Separate, INVALID, fencoding_EQ, "J", 0, 0, 0) OPTION("--entry", _entry, Flag, INVALID, e, "", 0, 0, 0) OPTION("--extdirs=", _extdirs_EQ, Joined, INVALID, fextdirs_EQ, "", 0, 0, 0) OPTION("--extdirs", _extdirs, Separate, INVALID, fextdirs_EQ, "J", 0, 0, 0) OPTION("--extra-warnings", _extra_warnings, Flag, INVALID, W_Joined, "", 0, 0, 0) OPTION("--for-linker=", _for_linker_EQ, Joined, INVALID, Xlinker, "liS", 0, 0, 0) OPTION("--for-linker", _for_linker, Separate, INVALID, Xlinker, "li", 0, 0, 0) OPTION("--force-link=", _force_link_EQ, Joined, INVALID, u, "S", 0, 0, 0) OPTION("--force-link", _force_link, Separate, INVALID, u, "", 0, 0, 0) OPTION("--help-hidden", _help_hidden, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("--help", _help, Flag, INVALID, INVALID, "", 0, "Display available options", 0) OPTION("--imacros=", _imacros_EQ, Joined, INVALID, imacros, "S", 0, 0, 0) OPTION("--imacros", _imacros, Separate, INVALID, imacros, "", 0, 0, 0) OPTION("--include-barrier", _include_barrier, Flag, INVALID, I_, "", 0, 0, 0) OPTION("--include-directory-after=", _include_directory_after_EQ, Joined, INVALID, idirafter, "S", 0, 0, 0) OPTION("--include-directory-after", _include_directory_after, Separate, INVALID, idirafter, "", 0, 0, 0) OPTION("--include-directory=", _include_directory_EQ, Joined, INVALID, I, "", 0, 0, 0) OPTION("--include-directory", _include_directory, Separate, INVALID, I, "J", 0, 0, 0) OPTION("--include-prefix=", _include_prefix_EQ, Joined, INVALID, iprefix, "S", 0, 0, 0) OPTION("--include-prefix", _include_prefix, Separate, INVALID, iprefix, "", 0, 0, 0) OPTION("--include-with-prefix-after=", _include_with_prefix_after_EQ, Joined, INVALID, iwithprefix, "S", 0, 0, 0) OPTION("--include-with-prefix-after", _include_with_prefix_after, Separate, INVALID, iwithprefix, "", 0, 0, 0) OPTION("--include-with-prefix-before=", _include_with_prefix_before_EQ, Joined, INVALID, iwithprefixbefore, "S", 0, 0, 0) OPTION("--include-with-prefix-before", _include_with_prefix_before, Separate, INVALID, iwithprefixbefore, "", 0, 0, 0) OPTION("--include-with-prefix=", _include_with_prefix_EQ, Joined, INVALID, iwithprefix, "S", 0, 0, 0) OPTION("--include-with-prefix", _include_with_prefix, Separate, INVALID, iwithprefix, "", 0, 0, 0) OPTION("--include=", _include_EQ, Joined, INVALID, include, "S", 0, 0, 0) OPTION("--include", _include, Separate, INVALID, include, "", 0, 0, 0) OPTION("--language=", _language_EQ, Joined, INVALID, x, "S", 0, 0, 0) OPTION("--language", _language, Separate, INVALID, x, "", 0, 0, 0) OPTION("--library-directory=", _library_directory_EQ, Joined, INVALID, L, "S", 0, 0, 0) OPTION("--library-directory", _library_directory, Separate, INVALID, L, "", 0, 0, 0) OPTION("--machine-=", _machine__EQ, Joined, INVALID, m_Joined, "u", 0, 0, 0) OPTION("--machine-", _machine_, Joined, INVALID, m_Joined, "u", 0, 0, 0) OPTION("--machine=", _machine_EQ, Joined, INVALID, m_Joined, "", 0, 0, 0) OPTION("--machine", _machine, Separate, INVALID, m_Joined, "J", 0, 0, 0) OPTION("--no-integrated-cpp", _no_integrated_cpp, Flag, INVALID, no_integrated_cpp, "", 0, 0, 0) OPTION("--no-line-commands", _no_line_commands, Flag, INVALID, P, "", 0, 0, 0) OPTION("--no-standard-includes", _no_standard_includes, Flag, INVALID, nostdinc, "", 0, 0, 0) OPTION("--no-standard-libraries", _no_standard_libraries, Flag, INVALID, nostdlib, "", 0, 0, 0) OPTION("--no-warnings", _no_warnings, Flag, INVALID, w, "", 0, 0, 0) OPTION("--optimize=", _optimize_EQ, Joined, INVALID, O, "u", 0, 0, 0) OPTION("--optimize", _optimize, Flag, INVALID, O, "u", 0, 0, 0) OPTION("--output-class-directory=", _output_class_directory_EQ, Joined, INVALID, foutput_class_dir_EQ, "", 0, 0, 0) OPTION("--output-class-directory", _output_class_directory, Separate, INVALID, foutput_class_dir_EQ, "J", 0, 0, 0) OPTION("--output=", _output_EQ, Joined, INVALID, o, "S", 0, 0, 0) OPTION("--output", _output, Separate, INVALID, o, "", 0, 0, 0) OPTION("--param=", _param_EQ, Joined, INVALID, _param, "S", 0, 0, 0) OPTION("--param", _param, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("--pass-exit-codes", _pass_exit_codes, Flag, INVALID, pass_exit_codes, "", 0, 0, 0) OPTION("--pedantic-errors", _pedantic_errors, Flag, INVALID, pedantic_errors, "", 0, 0, 0) OPTION("--pedantic", _pedantic, Flag, INVALID, pedantic, "", 0, 0, 0) OPTION("--pipe", _pipe, Flag, INVALID, pipe, "d", 0, 0, 0) OPTION("--prefix=", _prefix_EQ, Joined, INVALID, B, "S", 0, 0, 0) OPTION("--prefix", _prefix, Separate, INVALID, B, "", 0, 0, 0) OPTION("--preprocess", _preprocess, Flag, INVALID, E, "", 0, 0, 0) OPTION("--print-file-name=", _print_file_name_EQ, Joined, INVALID, print_file_name_EQ, "", 0, 0, 0) OPTION("--print-file-name", _print_file_name, Separate, INVALID, print_file_name_EQ, "", 0, 0, 0) OPTION("--print-libgcc-file-name", _print_libgcc_file_name, Flag, INVALID, print_libgcc_file_name, "", 0, 0, 0) OPTION("--print-missing-file-dependencies", _print_missing_file_dependencies, Flag, INVALID, MG, "", 0, 0, 0) OPTION("--print-multi-directory", _print_multi_directory, Flag, INVALID, print_multi_directory, "", 0, 0, 0) OPTION("--print-multi-lib", _print_multi_lib, Flag, INVALID, print_multi_lib, "", 0, 0, 0) OPTION("--print-multi-os-directory", _print_multi_os_directory, Flag, INVALID, print_multi_os_directory, "", 0, 0, 0) OPTION("--print-prog-name=", _print_prog_name_EQ, Joined, INVALID, print_prog_name_EQ, "", 0, 0, 0) OPTION("--print-prog-name", _print_prog_name, Separate, INVALID, print_prog_name_EQ, "", 0, 0, 0) OPTION("--print-search-dirs", _print_search_dirs, Flag, INVALID, print_search_dirs, "", 0, 0, 0) OPTION("--profile-blocks", _profile_blocks, Flag, INVALID, a, "", 0, 0, 0) OPTION("--profile", _profile, Flag, INVALID, p, "", 0, 0, 0) OPTION("--resource=", _resource_EQ, Joined, INVALID, fcompile_resource_EQ, "", 0, 0, 0) OPTION("--resource", _resource, Separate, INVALID, fcompile_resource_EQ, "J", 0, 0, 0) OPTION("--save-temps", _save_temps, Flag, INVALID, save_temps, "", 0, 0, 0) OPTION("--specs=", _specs_EQ, Joined, INVALID, specs_EQ, "u", 0, 0, 0) OPTION("--specs", _specs, Separate, INVALID, specs_EQ, "uJ", 0, 0, 0) OPTION("--static", _static, Flag, INVALID, static, "", 0, 0, 0) OPTION("--std=", _std_EQ, Joined, INVALID, std_EQ, "", 0, 0, 0) OPTION("--std", _std, Separate, INVALID, std_EQ, "J", 0, 0, 0) OPTION("--sysroot=", _sysroot_EQ, Joined, INVALID, INVALID, "", 0, 0, 0) OPTION("--sysroot", _sysroot, Separate, INVALID, _sysroot_EQ, "J", 0, 0, 0) OPTION("--target-help", _target_help, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("--trace-includes", _trace_includes, Flag, INVALID, H, "", 0, 0, 0) OPTION("--traditional-cpp", _traditional_cpp, Flag, INVALID, traditional_cpp, "", 0, 0, 0) OPTION("--traditional", _traditional, Flag, INVALID, traditional, "", 0, 0, 0) OPTION("--trigraphs", _trigraphs, Flag, INVALID, trigraphs, "", 0, 0, 0) OPTION("--undefine-macro=", _undefine_macro_EQ, Joined, INVALID, U, "", 0, 0, 0) OPTION("--undefine-macro", _undefine_macro, Separate, INVALID, U, "J", 0, 0, 0) OPTION("--user-dependencies", _user_dependencies, Flag, INVALID, MM, "", 0, 0, 0) OPTION("--verbose", _verbose, Flag, INVALID, v, "", 0, 0, 0) OPTION("--version", _version, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("--warn-=", _warn__EQ, Joined, INVALID, W_Joined, "u", 0, 0, 0) OPTION("--warn-", _warn_, Joined, INVALID, W_Joined, "u", 0, 0, 0) OPTION("--write-dependencies", _write_dependencies, Flag, INVALID, MD, "", 0, 0, 0) OPTION("--write-user-dependencies", _write_user_dependencies, Flag, INVALID, MMD, "", 0, 0, 0) OPTION("--", _, Joined, INVALID, f, "u", 0, 0, 0) OPTION("-A", A, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-B", B, JoinedOrSeparate, INVALID, INVALID, "u", 0, 0, 0) OPTION("-CC", CC, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-C", C, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-D", D, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-E", E, Flag, INVALID, INVALID, "d", 0, "Only run the preprocessor", 0) OPTION("-F", F, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-H", H, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-I-", I_, Flag, I_Group, INVALID, "", 0, 0, 0) OPTION("-I", I, JoinedOrSeparate, I_Group, INVALID, "", 0, 0, 0) OPTION("-L", L, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-MD", MD, Flag, M_Group, INVALID, "", 0, 0, 0) OPTION("-MF", MF, JoinedOrSeparate, M_Group, INVALID, "", 0, 0, 0) OPTION("-MG", MG, Flag, M_Group, INVALID, "", 0, 0, 0) OPTION("-MMD", MMD, Flag, M_Group, INVALID, "", 0, 0, 0) OPTION("-MM", MM, Flag, M_Group, INVALID, "", 0, 0, 0) OPTION("-MP", MP, Flag, M_Group, INVALID, "", 0, 0, 0) OPTION("-MQ", MQ, JoinedOrSeparate, M_Group, INVALID, "", 0, 0, 0) OPTION("-MT", MT, JoinedOrSeparate, M_Group, INVALID, "", 0, 0, 0) OPTION("-Mach", Mach, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-M", M, Flag, M_Group, INVALID, "", 0, 0, 0) OPTION("-O4", O4, Joined, O_Group, INVALID, "", 0, 0, 0) OPTION("-ObjC++", ObjCXX, Flag, INVALID, INVALID, "d", 0, "Treat source input files as Objective-C++ inputs", 0) OPTION("-ObjC", ObjC, Flag, INVALID, INVALID, "d", 0, "Treat source input files as Objective-C inputs", 0) OPTION("-O", O, Joined, O_Group, INVALID, "", 0, 0, 0) OPTION("-P", P, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-Qn", Qn, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-Qunused-arguments", Qunused_arguments, Flag, INVALID, INVALID, "d", 0, "Don't emit warning for unused driver arguments", 0) OPTION("-Q", Q, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-R", R, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-S", S, Flag, INVALID, INVALID, "d", 0, "Only run preprocess and compilation steps", 0) OPTION("-Tbss", Tbss, JoinedOrSeparate, T_Group, INVALID, "", 0, 0, 0) OPTION("-Tdata", Tdata, JoinedOrSeparate, T_Group, INVALID, "", 0, 0, 0) OPTION("-Ttext", Ttext, JoinedOrSeparate, T_Group, INVALID, "", 0, 0, 0) OPTION("-T", T, JoinedOrSeparate, T_Group, INVALID, "", 0, 0, 0) OPTION("-U", U, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-V", V, JoinedOrSeparate, INVALID, INVALID, "du", 0, 0, 0) OPTION("-Wa,", Wa_COMMA, CommaJoined, INVALID, INVALID, "", 0, "Pass the comma separated arguments in <arg> to the assembler", "<arg>") OPTION("-Wall", Wall, Flag, W_Group, INVALID, "", 0, 0, 0) OPTION("-Wextra", Wextra, Flag, W_Group, INVALID, "", 0, 0, 0) OPTION("-Wl,", Wl_COMMA, CommaJoined, INVALID, INVALID, "li", 0, "Pass the comma separated arguments in <arg> to the linker", "<arg>") OPTION("-Wno-nonportable-cfstrings", Wno_nonportable_cfstrings, Joined, W_Group, INVALID, "", 0, 0, 0) OPTION("-Wnonportable-cfstrings", Wnonportable_cfstrings, Joined, W_Group, INVALID, "", 0, 0, 0) OPTION("-Wp,", Wp_COMMA, CommaJoined, INVALID, INVALID, "", 0, "Pass the comma separated arguments in <arg> to the preprocessor", "<arg>") OPTION("-W", W_Joined, Joined, W_Group, INVALID, "", 0, 0, 0) OPTION("-Xanalyzer", Xanalyzer, Separate, INVALID, INVALID, "", 0, "Pass <arg> to the static analyzer", "<arg>") OPTION("-Xarch_", Xarch__, JoinedAndSeparate, INVALID, INVALID, "d", 0, 0, 0) OPTION("-Xassembler", Xassembler, Separate, INVALID, INVALID, "", 0, "Pass <arg> to the assembler", "<arg>") OPTION("-Xclang", Xclang, Separate, INVALID, INVALID, "", 0, "Pass <arg> to the clang compiler", "<arg>") OPTION("-Xlinker", Xlinker, Separate, INVALID, INVALID, "li", 0, "Pass <arg> to the linker", "<arg>") OPTION("-Xpreprocessor", Xpreprocessor, Separate, INVALID, INVALID, "", 0, "Pass <arg> to the preprocessor", "<arg>") OPTION("-X", X_Flag, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-X", X_Joined, Joined, INVALID, INVALID, "", 0, 0, 0) OPTION("-Z", Z_Flag, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-Z", Z_Joined, Joined, INVALID, INVALID, "", 0, 0, 0) OPTION("-all_load", all__load, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-allowable_client", allowable__client, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-ansi", ansi, Flag, a_Group, INVALID, "", 0, 0, 0) OPTION("-arch", arch, Separate, INVALID, INVALID, "d", 0, 0, 0) OPTION("-a", a, Joined, a_Group, INVALID, "", 0, 0, 0) OPTION("-bind_at_load", bind__at__load, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-bundle_loader", bundle__loader, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-bundle", bundle, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-b", b, JoinedOrSeparate, INVALID, INVALID, "u", 0, 0, 0) OPTION("-client_name", client__name, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-combine", combine, Flag, INVALID, INVALID, "du", 0, 0, 0) OPTION("-compatibility_version", compatibility__version, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-coverage", coverage, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-cpp-precomp", cpp_precomp, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-current_version", current__version, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-c", c, Flag, INVALID, INVALID, "d", 0, "Only run preprocess, compile, and assemble steps", 0) OPTION("-dA", dA, Flag, d_Group, INVALID, "", 0, 0, 0) OPTION("-dD", dD, Flag, d_Group, INVALID, "", 0, 0, 0) OPTION("-dM", dM, Flag, d_Group, INVALID, "", 0, 0, 0) OPTION("-dead_strip", dead__strip, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-dependency-file", dependency_file, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-dumpmachine", dumpmachine, Flag, INVALID, INVALID, "u", 0, 0, 0) OPTION("-dumpspecs", dumpspecs, Flag, INVALID, INVALID, "u", 0, 0, 0) OPTION("-dumpversion", dumpversion, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-dylib_file", dylib__file, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-dylinker_install_name", dylinker__install__name, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-dylinker", dylinker, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-dynamiclib", dynamiclib, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-dynamic", dynamic, Flag, INVALID, INVALID, "q", 0, 0, 0) OPTION("-d", d_Flag, Flag, d_Group, INVALID, "", 0, 0, 0) OPTION("-d", d_Joined, Joined, d_Group, INVALID, "", 0, 0, 0) OPTION("-emit-llvm", emit_llvm, Flag, INVALID, INVALID, "", 0, "Use the LLVM representation for assembler and object files", 0) OPTION("-exported_symbols_list", exported__symbols__list, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-e", e, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-fPIC", fPIC, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fPIE", fPIE, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fapple-kext", fapple_kext, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fasm-blocks", fasm_blocks, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fastcp", fastcp, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fastf", fastf, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fast", fast, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fblocks", fblocks, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fbootclasspath=", fbootclasspath_EQ, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-fbuiltin", fbuiltin, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fclasspath=", fclasspath_EQ, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-fcommon", fcommon, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fcompile-resource=", fcompile_resource_EQ, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-fconstant-cfstrings", fconstant_cfstrings, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fcreate-profile", fcreate_profile, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fdebug-pass-arguments", fdebug_pass_arguments, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fdebug-pass-structure", fdebug_pass_structure, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fdiagnostics-show-option", fdiagnostics_show_option, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fdollars-in-identifiers", fdollars_in_identifiers, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-feliminate-unused-debug-symbols", feliminate_unused_debug_symbols, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-femit-all-decls", femit_all_decls, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fencoding=", fencoding_EQ, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-fexceptions", fexceptions, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fextdirs=", fextdirs_EQ, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-ffreestanding", ffreestanding, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fgnu-runtime", fgnu_runtime, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fheinous-gnu-extensions", fheinous_gnu_extensions, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-filelist", filelist, Separate, INVALID, INVALID, "l", 0, 0, 0) OPTION("-findirect-virtual-calls", findirect_virtual_calls, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-finline-functions", finline_functions, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-finline", finline, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fkeep-inline-functions", fkeep_inline_functions, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-flat_namespace", flat__namespace, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-flax-vector-conversions", flax_vector_conversions, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-flimited-precision=", flimited_precision_EQ, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-flto", flto, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fmath-errno", fmath_errno, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fmessage-length=", fmessage_length_EQ, Joined, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fms-extensions", fms_extensions, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fmudflapth", fmudflapth, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fmudflap", fmudflap, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fnested-functions", fnested_functions, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fnext-runtime", fnext_runtime, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-blocks", fno_blocks, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-builtin", fno_builtin, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-caret-diagnostics", fno_caret_diagnostics, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-common", fno_common, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-constant-cfstrings", fno_constant_cfstrings, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-diagnostics-show-option", fno_diagnostics_show_option, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-eliminate-unused-debug-symbols", fno_eliminate_unused_debug_symbols, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-inline-functions", fno_inline_functions, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-inline", fno_inline, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-keep-inline-functions", fno_keep_inline_functions, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-math-errno", fno_math_errno, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-pascal-strings", fno_pascal_strings, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-show-column", fno_show_column, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-stack-protector", fno_stack_protector, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-strict-aliasing", fno_strict_aliasing, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-unwind-tables", fno_unwind_tables, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-working-directory", fno_working_directory, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fno-zero-initialized-in-bss", fno_zero_initialized_in_bss, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fobjc-atdefs", fobjc_atdefs, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fobjc-call-cxx-cdtors", fobjc_call_cxx_cdtors, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fobjc-gc-only", fobjc_gc_only, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fobjc-gc", fobjc_gc, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fobjc-new-property", fobjc_new_property, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fobjc-nonfragile-abi", fobjc_nonfragile_abi, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fobjc", fobjc, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fomit-frame-pointer", fomit_frame_pointer, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fopenmp", fopenmp, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-force_cpusubtype_ALL", force__cpusubtype__ALL, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-force_flat_namespace", force__flat__namespace, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-foutput-class-dir=", foutput_class_dir_EQ, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-fpascal-strings", fpascal_strings, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fpch-preprocess", fpch_preprocess, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fpic", fpic, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fpie", fpie, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fprint-source-range-info", fprint_source_range_info, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fprofile-arcs", fprofile_arcs, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fprofile-generate", fprofile_generate, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-framework", framework, Separate, INVALID, INVALID, "l", 0, 0, 0) OPTION("-fsigned-bitfields", fsigned_bitfields, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fstack-protector", fstack_protector, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fstrict-aliasing", fstrict_aliasing, Flag, clang_ignored_f_Group, INVALID, "", 0, 0, 0) OPTION("-fsyntax-only", fsyntax_only, Flag, INVALID, INVALID, "d", 0, 0, 0) OPTION("-ftemplate-depth-", ftemplate_depth_, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-fterminated-vtables", fterminated_vtables, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-ftime-report", ftime_report, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-ftraditional", ftraditional, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-ftrapv", ftrapv, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-funsigned-bitfields", funsigned_bitfields, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-funwind-tables", funwind_tables, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fverbose-asm", fverbose_asm, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fvisibility=", fvisibility_EQ, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-fwritable-strings", fwritable_strings, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-fzero-initialized-in-bss", fzero_initialized_in_bss, Flag, f_Group, INVALID, "", 0, 0, 0) OPTION("-f", f, Joined, f_Group, INVALID, "", 0, 0, 0) OPTION("-g0", g0, Joined, g_Group, INVALID, "", 0, 0, 0) OPTION("-g3", g3, Joined, g_Group, INVALID, "", 0, 0, 0) OPTION("-gfull", gfull, Joined, g_Group, INVALID, "", 0, 0, 0) OPTION("-gstabs", gstabs, Joined, g_Group, INVALID, "", 0, 0, 0) OPTION("-gused", gused, Joined, g_Group, INVALID, "", 0, 0, 0) OPTION("-g", g_Flag, Flag, g_Group, INVALID, "", 0, 0, 0) OPTION("-g", g_Joined, Joined, g_Group, INVALID, "", 0, 0, 0) OPTION("-headerpad_max_install_names", headerpad__max__install__names, Joined, INVALID, INVALID, "", 0, 0, 0) OPTION("-idirafter", idirafter, JoinedOrSeparate, clang_i_Group, INVALID, "", 0, 0, 0) OPTION("-imacros", imacros, JoinedOrSeparate, clang_i_Group, INVALID, "", 0, 0, 0) OPTION("-image_base", image__base, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-include", include, JoinedOrSeparate, clang_i_Group, INVALID, "", 0, 0, 0) OPTION("-init", init, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-install_name", install__name, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-iprefix", iprefix, JoinedOrSeparate, clang_i_Group, INVALID, "", 0, 0, 0) OPTION("-iquote", iquote, JoinedOrSeparate, clang_i_Group, INVALID, "", 0, 0, 0) OPTION("-isysroot", isysroot, JoinedOrSeparate, i_Group, INVALID, "", 0, 0, 0) OPTION("-isystem", isystem, JoinedOrSeparate, clang_i_Group, INVALID, "", 0, 0, 0) OPTION("-iwithprefixbefore", iwithprefixbefore, JoinedOrSeparate, clang_i_Group, INVALID, "", 0, 0, 0) OPTION("-iwithprefix", iwithprefix, JoinedOrSeparate, clang_i_Group, INVALID, "", 0, 0, 0) OPTION("-iwithsysroot", iwithsysroot, JoinedOrSeparate, i_Group, INVALID, "", 0, 0, 0) OPTION("-i", i, Joined, i_Group, INVALID, "", 0, 0, 0) OPTION("-keep_private_externs", keep__private__externs, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-l", l, JoinedOrSeparate, INVALID, INVALID, "l", 0, 0, 0) OPTION("-m32", m32, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-m3dnowa", m3dnowa, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-m3dnow", m3dnow, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-m64", m64, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mconstant-cfstrings", mconstant_cfstrings, Flag, clang_ignored_m_Group, INVALID, "", 0, 0, 0) OPTION("-mdynamic-no-pic", mdynamic_no_pic, Joined, m_Group, INVALID, "q", 0, 0, 0) OPTION("-mfix-and-continue", mfix_and_continue, Flag, clang_ignored_m_Group, INVALID, "", 0, 0, 0) OPTION("-miphoneos-version-min=", miphoneos_version_min_EQ, Joined, m_Group, INVALID, "", 0, 0, 0) OPTION("-mkernel", mkernel, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mmacosx-version-min=", mmacosx_version_min_EQ, Joined, m_Group, INVALID, "", 0, 0, 0) OPTION("-mmmx", mmmx, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-3dnowa", mno_3dnowa, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-3dnow", mno_3dnow, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-constant-cfstrings", mno_constant_cfstrings, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-mmx", mno_mmx, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-pascal-strings", mno_pascal_strings, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-red-zone", mno_red_zone, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-soft-float", mno_soft_float, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-sse2", mno_sse2, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-sse3", mno_sse3, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-sse41", mno_sse41, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-sse42", mno_sse42, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-sse4a", mno_sse4a, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-sse", mno_sse, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-ssse3", mno_ssse3, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mno-warn-nonportable-cfstrings", mno_warn_nonportable_cfstrings, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mpascal-strings", mpascal_strings, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mred-zone", mred_zone, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-msoft-float", msoft_float, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-msse2", msse2, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-msse3", msse3, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-msse41", msse41, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-msse42", msse42, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-msse4a", msse4a, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-msse", msse, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mssse3", mssse3, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-mtune=", mtune_EQ, Joined, m_Group, INVALID, "", 0, 0, 0) OPTION("-multi_module", multi__module, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-multiply_defined_unused", multiply__defined__unused, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-multiply_defined", multiply__defined, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-mwarn-nonportable-cfstrings", mwarn_nonportable_cfstrings, Flag, m_Group, INVALID, "", 0, 0, 0) OPTION("-m", m_Separate, Separate, m_Group, INVALID, "", 0, 0, 0) OPTION("-m", m_Joined, Joined, m_Group, INVALID, "", 0, 0, 0) OPTION("-no-cpp-precomp", no_cpp_precomp, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-no-integrated-cpp", no_integrated_cpp, Flag, INVALID, INVALID, "d", 0, 0, 0) OPTION("-no_dead_strip_inits_and_terms", no__dead__strip__inits__and__terms, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-nodefaultlibs", nodefaultlibs, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-nofixprebinding", nofixprebinding, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-nomultidefs", nomultidefs, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-noprebind", noprebind, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-noseglinkedit", noseglinkedit, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-nostartfiles", nostartfiles, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-nostdinc", nostdinc, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-nostdlib", nostdlib, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-object", object, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-o", o, JoinedOrSeparate, INVALID, INVALID, "di", 0, "Write output to <file>", "<file>") OPTION("-pagezero_size", pagezero__size, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-pass-exit-codes", pass_exit_codes, Flag, INVALID, INVALID, "u", 0, 0, 0) OPTION("-pedantic-errors", pedantic_errors, Flag, pedantic_Group, INVALID, "", 0, 0, 0) OPTION("-pedantic", pedantic, Flag, pedantic_Group, INVALID, "", 0, 0, 0) OPTION("-pg", pg, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-pipe", pipe, Flag, INVALID, INVALID, "", 0, "Use pipes between commands, when possible", 0) OPTION("-prebind_all_twolevel_modules", prebind__all__twolevel__modules, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-prebind", prebind, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-preload", preload, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-print-file-name=", print_file_name_EQ, Joined, INVALID, INVALID, "", 0, "Print the full library path of <file>", "<file>") OPTION("-print-libgcc-file-name", print_libgcc_file_name, Flag, INVALID, INVALID, "", 0, "Print the library path for \"libgcc.a\"", 0) OPTION("-print-multi-directory", print_multi_directory, Flag, INVALID, INVALID, "u", 0, 0, 0) OPTION("-print-multi-lib", print_multi_lib, Flag, INVALID, INVALID, "u", 0, 0, 0) OPTION("-print-multi-os-directory", print_multi_os_directory, Flag, INVALID, INVALID, "u", 0, 0, 0) OPTION("-print-prog-name=", print_prog_name_EQ, Joined, INVALID, INVALID, "", 0, "Print the full program path of <name>", "<name>") OPTION("-print-search-dirs", print_search_dirs, Flag, INVALID, INVALID, "", 0, "Print the paths used for finding libraries and programs", 0) OPTION("-private_bundle", private__bundle, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-pthreads", pthreads, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-pthread", pthread, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-p", p, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-read_only_relocs", read__only__relocs, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-remap", remap, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-r", r, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-save-temps", save_temps, Flag, INVALID, INVALID, "d", 0, "Save intermediate compilation results", 0) OPTION("-sectalign", sectalign, MultiArg, INVALID, INVALID, "", 3, 0, 0) OPTION("-sectcreate", sectcreate, MultiArg, INVALID, INVALID, "", 3, 0, 0) OPTION("-sectobjectsymbols", sectobjectsymbols, MultiArg, INVALID, INVALID, "", 2, 0, 0) OPTION("-sectorder", sectorder, MultiArg, INVALID, INVALID, "", 3, 0, 0) OPTION("-seg1addr", seg1addr, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-seg_addr_table_filename", seg__addr__table__filename, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-seg_addr_table", seg__addr__table, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-segaddr", segaddr, MultiArg, INVALID, INVALID, "", 2, 0, 0) OPTION("-segcreate", segcreate, MultiArg, INVALID, INVALID, "", 3, 0, 0) OPTION("-seglinkedit", seglinkedit, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-segprot", segprot, MultiArg, INVALID, INVALID, "", 3, 0, 0) OPTION("-segs_read_only_addr", segs__read__only__addr, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-segs_read_write_addr", segs__read__write__addr, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-segs_read_", segs__read__, Joined, INVALID, INVALID, "", 0, 0, 0) OPTION("-shared-libgcc", shared_libgcc, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-shared", shared, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-single_module", single__module, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-specs=", specs_EQ, Joined, INVALID, INVALID, "", 0, 0, 0) OPTION("-specs", specs, Separate, INVALID, INVALID, "u", 0, 0, 0) OPTION("-static-libgcc", static_libgcc, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-static", static, Flag, INVALID, INVALID, "q", 0, 0, 0) OPTION("-std=", std_EQ, Joined, INVALID, INVALID, "", 0, 0, 0) OPTION("-sub_library", sub__library, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-sub_umbrella", sub__umbrella, JoinedOrSeparate, INVALID, INVALID, "", 0, 0, 0) OPTION("-s", s, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-time", time, Flag, INVALID, INVALID, "", 0, "Time individual commands", 0) OPTION("-traditional-cpp", traditional_cpp, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-traditional", traditional, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-trigraphs", trigraphs, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-twolevel_namespace_hints", twolevel__namespace__hints, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-twolevel_namespace", twolevel__namespace, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-t", t, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-umbrella", umbrella, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-undefined", undefined, JoinedOrSeparate, u_Group, INVALID, "", 0, 0, 0) OPTION("-undef", undef, Flag, u_Group, INVALID, "", 0, 0, 0) OPTION("-unexported_symbols_list", unexported__symbols__list, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-u", u, JoinedOrSeparate, u_Group, INVALID, "", 0, 0, 0) OPTION("-v", v, Flag, INVALID, INVALID, "", 0, "Show commands to run and use verbose output", 0) OPTION("-weak-l", weak_l, Joined, INVALID, INVALID, "l", 0, 0, 0) OPTION("-weak_framework", weak__framework, Separate, INVALID, INVALID, "l", 0, 0, 0) OPTION("-weak_library", weak__library, Separate, INVALID, INVALID, "l", 0, 0, 0) OPTION("-weak_reference_mismatches", weak__reference__mismatches, Separate, INVALID, INVALID, "", 0, 0, 0) OPTION("-whatsloaded", whatsloaded, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-whyload", whyload, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-w", w, Flag, INVALID, INVALID, "", 0, 0, 0) OPTION("-x", x, JoinedOrSeparate, INVALID, INVALID, "d", 0, "Treat subsequent input files as having type <language>", "<language>") OPTION("-y", y, Joined, INVALID, INVALID, "", 0, 0, 0) <file_sep>/test/Analysis/conditional-op-missing-lhs.c // RUN: clang-cc -analyze -warn-dead-stores -warn-uninit-values -verify %s void f1() { int i; int j = i ? : 1; // expected-warning{{use of uninitialized variable}} //expected-warning{{Value stored to 'j' during its initialization is never read}} } void *f2(int *i) { return i ? : 0; } void *f3(int *i) { int a; return &a ? : i; } void f4() { char c[1 ? : 2]; } <file_sep>/utils/SummarizeErrors #!/usr/bin/python import os, sys, re class multidict: def __init__(self, elts=()): self.data = {} for key,value in elts: self[key] = value def __getitem__(self, item): return self.data[item] def __setitem__(self, key, value): if key in self.data: self.data[key].append(value) else: self.data[key] = [value] def items(self): return self.data.items() def values(self): return self.data.values() def keys(self): return self.data.keys() def __len__(self): return len(self.data) kDiagnosticRE = re.compile(': (error|warning): (.*)') kAssertionRE = re.compile('Assertion failed: (.*, function .*, file .*, line [0-9]+\\.)') def readInfo(path, opts): lastProgress = [-100,0] def progress(pos): pct = (100. * pos) / (size * 2) if (pct - lastProgress[0]) >= 10: lastProgress[0] = pct print '%d/%d = %.2f%%' % (pos, size*2, pct) f = open(path) data = f.read() f.close() if opts.truncate != -1: data = data[:opts.truncate] size = len(data) warnings = multidict() errors = multidict() for m in kDiagnosticRE.finditer(data): progress(m.end()) if m.group(1) == 'error': d = errors else: d = warnings d[m.group(2)] = m warnings = warnings.items() errors = errors.items() assertions = multidict() for m in kAssertionRE.finditer(data): print '%d/%d = %.2f%%' % (size + m.end(), size, (float(m.end()) / (size*2)) * 100.) assertions[m.group(1)] = m assertions = assertions.items() # Manual scan for stack traces aborts = multidict() if 0: prevLine = None lnIter = iter(data.split('\n')) for ln in lnIter: m = kStackDumpLineRE.match(ln) if m: stack = [m.group(2)] for ln in lnIter: m = kStackDumpLineRE.match(ln) if not m: break stack.append(m.group(2)) if prevLine is None or not kAssertionRE.match(prevLine): aborts[tuple(stack)] = stack prevLine = ln sections = [ (warnings, 'Warnings'), (errors, 'Errors'), (assertions, 'Assertions'), (aborts.items(), 'Aborts'), ] if opts.ascending: sections.reverse() for l,title in sections: l.sort(key = lambda (a,b): -len(b)) if l: print '-- %d %s (%d kinds) --' % (sum([len(b) for a,b in l]), title, len(l)) for name,elts in l: print '%5d:' % len(elts), name def main(): global options from optparse import OptionParser parser = OptionParser("usage: %prog [options] {inputs}") parser.add_option("", "--ascending", dest="ascending", help="Print output in ascending order of severity.", action="store_true", default=False) parser.add_option("", "--truncate", dest="truncate", help="Truncate input file (for testing).", type=int, action="store", default=-1) (opts, args) = parser.parse_args() if not args: parser.error('No inputs specified') for arg in args: readInfo(arg, opts) if __name__=='__main__': main() <file_sep>/lib/Frontend/TextDiagnosticBuffer.cpp //===--- TextDiagnosticBuffer.cpp - Buffer Text Diagnostics ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a concrete diagnostic client, which buffers the diagnostic messages. // //===----------------------------------------------------------------------===// #include "clang/Frontend/TextDiagnosticBuffer.h" #include "llvm/ADT/SmallString.h" using namespace clang; /// HandleDiagnostic - Store the errors, warnings, and notes that are /// reported. /// void TextDiagnosticBuffer::HandleDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info) { llvm::SmallString<100> StrC; Info.FormatDiagnostic(StrC); std::string Str(StrC.begin(), StrC.end()); switch (Level) { default: assert(0 && "Diagnostic not handled during diagnostic buffering!"); case Diagnostic::Note: Notes.push_back(std::make_pair(Info.getLocation(), Str)); break; case Diagnostic::Warning: Warnings.push_back(std::make_pair(Info.getLocation(), Str)); break; case Diagnostic::Error: case Diagnostic::Fatal: Errors.push_back(std::make_pair(Info.getLocation(), Str)); break; } } <file_sep>/lib/AST/DeclSerialization.cpp //===--- DeclSerialization.cpp - Serialization of Decls ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines methods that implement bitcode serialization for Decls. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "llvm/Bitcode/Serialize.h" #include "llvm/Bitcode/Deserialize.h" using llvm::Serializer; using llvm::Deserializer; using llvm::SerializedPtrID; using namespace clang; //===----------------------------------------------------------------------===// // Decl Serialization: Dispatch code to handle specialized decl types. //===----------------------------------------------------------------------===// void Decl::Emit(Serializer& S) const { S.EmitInt(getKind()); EmitImpl(S); S.Emit(getLocation()); S.EmitBool(InvalidDecl); // FIXME: HasAttrs? S.EmitBool(Implicit); S.EmitInt(IdentifierNamespace); S.EmitInt(Access); S.EmitPtr(cast_or_null<Decl>(getDeclContext())); // From Decl. S.EmitPtr(cast_or_null<Decl>(getLexicalDeclContext())); // From Decl. if (const DeclContext *DC = dyn_cast<const DeclContext>(this)) DC->EmitOutRec(S); if (getDeclContext() && !getDeclContext()->isFunctionOrMethod()) { S.EmitBool(true); S.EmitOwnedPtr(NextDeclInContext); } else { S.EmitBool(false); S.EmitPtr(NextDeclInContext); } } Decl* Decl::Create(Deserializer& D, ASTContext& C) { Decl *Dcl; Kind k = static_cast<Kind>(D.ReadInt()); switch (k) { default: assert (false && "Not implemented."); case TranslationUnit: Dcl = TranslationUnitDecl::CreateImpl(D, C); break; case Namespace: Dcl = NamespaceDecl::CreateImpl(D, C); break; case Var: Dcl = VarDecl::CreateImpl(D, C); break; case Enum: Dcl = EnumDecl::CreateImpl(D, C); break; case EnumConstant: Dcl = EnumConstantDecl::CreateImpl(D, C); break; case Field: Dcl = FieldDecl::CreateImpl(D, C); break; case ParmVar: Dcl = ParmVarDecl::CreateImpl(D, C); break; case OriginalParmVar: Dcl = OriginalParmVarDecl::CreateImpl(D, C); break; case Function: Dcl = FunctionDecl::CreateImpl(D, C); break; case OverloadedFunction: Dcl = OverloadedFunctionDecl::CreateImpl(D, C); break; case Record: Dcl = RecordDecl::CreateImpl(D, C); break; case Typedef: Dcl = TypedefDecl::CreateImpl(D, C); break; case TemplateTypeParm: Dcl = TemplateTypeParmDecl::CreateImpl(D, C); break; case FileScopeAsm: Dcl = FileScopeAsmDecl::CreateImpl(D, C); break; } Dcl->Loc = SourceLocation::ReadVal(D); // From Decl. Dcl->InvalidDecl = D.ReadBool(); // FIXME: HasAttrs? Dcl->Implicit = D.ReadBool(); Dcl->IdentifierNamespace = D.ReadInt(); Dcl->Access = D.ReadInt(); assert(Dcl->DeclCtx.getOpaqueValue() == 0); const SerializedPtrID &SemaDCPtrID = D.ReadPtrID(); const SerializedPtrID &LexicalDCPtrID = D.ReadPtrID(); if (SemaDCPtrID == LexicalDCPtrID) { // Allow back-patching. Observe that we register the variable of the // *object* for back-patching. Its actual value will get filled in later. uintptr_t X; D.ReadUIntPtr(X, SemaDCPtrID); Dcl->DeclCtx = reinterpret_cast<DeclContext*>(X); } else { MultipleDC *MDC = new MultipleDC(); Dcl->DeclCtx = MDC; // Allow back-patching. Observe that we register the variable of the // *object* for back-patching. Its actual value will get filled in later. D.ReadPtr(MDC->SemanticDC, SemaDCPtrID); D.ReadPtr(MDC->LexicalDC, LexicalDCPtrID); } if (DeclContext *DC = dyn_cast<DeclContext>(Dcl)) DC->ReadOutRec(D, C); bool OwnsNext = D.ReadBool(); if (OwnsNext) Dcl->NextDeclInContext = D.ReadOwnedPtr<Decl>(C); else D.ReadPtr(Dcl->NextDeclInContext); return Dcl; } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of DeclContext. //===----------------------------------------------------------------------===// void DeclContext::EmitOutRec(Serializer& S) const { bool Owned = !isFunctionOrMethod(); S.EmitBool(Owned); if (Owned) S.EmitOwnedPtr(FirstDecl); else S.EmitPtr(FirstDecl); S.EmitPtr(LastDecl); } void DeclContext::ReadOutRec(Deserializer& D, ASTContext& C) { bool Owned = D.ReadBool(); if (Owned) FirstDecl = cast_or_null<Decl>(D.ReadOwnedPtr<Decl>(C)); else D.ReadPtr(FirstDecl); D.ReadPtr(LastDecl); } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of NamedDecl. //===----------------------------------------------------------------------===// void NamedDecl::EmitInRec(Serializer& S) const { S.EmitInt(Name.getNameKind()); switch (Name.getNameKind()) { case DeclarationName::Identifier: S.EmitPtr(Name.getAsIdentifierInfo()); break; case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: Name.getObjCSelector().Emit(S); break; case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: Name.getCXXNameType().Emit(S); break; case DeclarationName::CXXOperatorName: S.EmitInt(Name.getCXXOverloadedOperator()); break; case DeclarationName::CXXUsingDirective: // No extra data to emit break; } } void NamedDecl::ReadInRec(Deserializer& D, ASTContext& C) { DeclarationName::NameKind Kind = static_cast<DeclarationName::NameKind>(D.ReadInt()); switch (Kind) { case DeclarationName::Identifier: { // Don't allow back-patching. The IdentifierInfo table must already // be loaded. Name = D.ReadPtr<IdentifierInfo>(); break; } case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: Name = Selector::ReadVal(D); break; case DeclarationName::CXXConstructorName: Name = C.DeclarationNames.getCXXConstructorName(QualType::ReadVal(D)); break; case DeclarationName::CXXDestructorName: Name = C.DeclarationNames.getCXXDestructorName(QualType::ReadVal(D)); break; case DeclarationName::CXXConversionFunctionName: Name = C.DeclarationNames.getCXXConversionFunctionName(QualType::ReadVal(D)); break; case DeclarationName::CXXOperatorName: { OverloadedOperatorKind Op = static_cast<OverloadedOperatorKind>(D.ReadInt()); Name = C.DeclarationNames.getCXXOperatorName(Op); break; } case DeclarationName::CXXUsingDirective: Name = DeclarationName::getUsingDirectiveName(); break; } } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of ValueDecl. //===----------------------------------------------------------------------===// void ValueDecl::EmitInRec(Serializer& S) const { NamedDecl::EmitInRec(S); S.Emit(getType()); // From ValueDecl. } void ValueDecl::ReadInRec(Deserializer& D, ASTContext& C) { NamedDecl::ReadInRec(D, C); DeclType = QualType::ReadVal(D); // From ValueDecl. } //===----------------------------------------------------------------------===// // Common serialization logic for subclasses of VarDecl. //===----------------------------------------------------------------------===// void VarDecl::EmitInRec(Serializer& S) const { ValueDecl::EmitInRec(S); S.EmitInt(getStorageClass()); // From VarDecl. S.EmitBool(ThreadSpecified); S.EmitBool(HasCXXDirectInit); S.EmitBool(DeclaredInCondition); S.EmitPtr(PreviousDeclaration); S.Emit(TypeSpecStartLoc); } void VarDecl::ReadInRec(Deserializer& D, ASTContext& C) { ValueDecl::ReadInRec(D, C); SClass = static_cast<StorageClass>(D.ReadInt()); // From VarDecl. ThreadSpecified = D.ReadBool(); HasCXXDirectInit = D.ReadBool(); DeclaredInCondition = D.ReadBool(); D.ReadPtr(PreviousDeclaration); TypeSpecStartLoc = SourceLocation::ReadVal(D); } void VarDecl::EmitOutRec(Serializer& S) const { // Emit this last because it will create a record of its own. S.EmitOwnedPtr(getInit()); } void VarDecl::ReadOutRec(Deserializer& D, ASTContext& C) { Init = D.ReadOwnedPtr<Stmt>(C); } void VarDecl::EmitImpl(Serializer& S) const { VarDecl::EmitInRec(S); VarDecl::EmitOutRec(S); } void VarDecl::ReadImpl(Deserializer& D, ASTContext& C) { ReadInRec(D, C); ReadOutRec(D, C); } //===----------------------------------------------------------------------===// // TranslationUnitDecl Serialization. //===----------------------------------------------------------------------===// void TranslationUnitDecl::EmitImpl(llvm::Serializer& S) const { } TranslationUnitDecl* TranslationUnitDecl::CreateImpl(Deserializer& D, ASTContext& C) { return new (C) TranslationUnitDecl(); } //===----------------------------------------------------------------------===// // NamespaceDecl Serialization. //===----------------------------------------------------------------------===// void NamespaceDecl::EmitImpl(llvm::Serializer& S) const { NamedDecl::EmitInRec(S); S.Emit(getLBracLoc()); S.Emit(getRBracLoc()); } NamespaceDecl* NamespaceDecl::CreateImpl(Deserializer& D, ASTContext& C) { NamespaceDecl* decl = new (C) NamespaceDecl(0, SourceLocation(), 0); decl->NamedDecl::ReadInRec(D, C); decl->LBracLoc = SourceLocation::ReadVal(D); decl->RBracLoc = SourceLocation::ReadVal(D); return decl; } //===----------------------------------------------------------------------===// // VarDecl Serialization. //===----------------------------------------------------------------------===// VarDecl* VarDecl::CreateImpl(Deserializer& D, ASTContext& C) { VarDecl* decl = new (C) VarDecl(Var, 0, SourceLocation(), NULL, QualType(), None); decl->VarDecl::ReadImpl(D, C); return decl; } //===----------------------------------------------------------------------===// // ParmVarDecl Serialization. //===----------------------------------------------------------------------===// void ParmVarDecl::EmitImpl(llvm::Serializer& S) const { VarDecl::EmitImpl(S); S.EmitInt(getObjCDeclQualifier()); // From ParmVarDecl. S.EmitOwnedPtr(getDefaultArg()); // From ParmVarDecl. } ParmVarDecl* ParmVarDecl::CreateImpl(Deserializer& D, ASTContext& C) { ParmVarDecl* decl = new (C) ParmVarDecl(ParmVar, 0, SourceLocation(), NULL, QualType(), None, NULL); decl->VarDecl::ReadImpl(D, C); decl->objcDeclQualifier = static_cast<ObjCDeclQualifier>(D.ReadInt()); decl->DefaultArg = D.ReadOwnedPtr<Expr>(C); return decl; } //===----------------------------------------------------------------------===// // OriginalParmVarDecl Serialization. //===----------------------------------------------------------------------===// void OriginalParmVarDecl::EmitImpl(llvm::Serializer& S) const { ParmVarDecl::EmitImpl(S); S.Emit(OriginalType); } OriginalParmVarDecl* OriginalParmVarDecl::CreateImpl( Deserializer& D, ASTContext& C) { OriginalParmVarDecl* decl = new (C) OriginalParmVarDecl(0, SourceLocation(), NULL, QualType(), QualType(), None, NULL); decl->ParmVarDecl::ReadImpl(D, C); decl->OriginalType = QualType::ReadVal(D); return decl; } //===----------------------------------------------------------------------===// // EnumDecl Serialization. //===----------------------------------------------------------------------===// void EnumDecl::EmitImpl(Serializer& S) const { NamedDecl::EmitInRec(S); S.EmitBool(isDefinition()); S.Emit(IntegerType); } EnumDecl* EnumDecl::CreateImpl(Deserializer& D, ASTContext& C) { EnumDecl* decl = new (C) EnumDecl(0, SourceLocation(), NULL); decl->NamedDecl::ReadInRec(D, C); decl->setDefinition(D.ReadBool()); decl->IntegerType = QualType::ReadVal(D); return decl; } //===----------------------------------------------------------------------===// // EnumConstantDecl Serialization. //===----------------------------------------------------------------------===// void EnumConstantDecl::EmitImpl(Serializer& S) const { S.Emit(Val); ValueDecl::EmitInRec(S); S.EmitOwnedPtr(Init); } EnumConstantDecl* EnumConstantDecl::CreateImpl(Deserializer& D, ASTContext& C) { llvm::APSInt val(1); D.Read(val); EnumConstantDecl* decl = new (C) EnumConstantDecl(0, SourceLocation(), NULL, QualType(), NULL, val); decl->ValueDecl::ReadInRec(D, C); decl->Init = D.ReadOwnedPtr<Stmt>(C); return decl; } //===----------------------------------------------------------------------===// // FieldDecl Serialization. //===----------------------------------------------------------------------===// void FieldDecl::EmitImpl(Serializer& S) const { S.EmitBool(Mutable); S.Emit(getType()); ValueDecl::EmitInRec(S); S.EmitOwnedPtr(BitWidth); } FieldDecl* FieldDecl::CreateImpl(Deserializer& D, ASTContext& C) { FieldDecl* decl = new (C) FieldDecl(Field, 0, SourceLocation(), NULL, QualType(), 0, false); decl->Mutable = D.ReadBool(); decl->ValueDecl::ReadInRec(D, C); decl->BitWidth = D.ReadOwnedPtr<Expr>(C); return decl; } //===----------------------------------------------------------------------===// // FunctionDecl Serialization. //===----------------------------------------------------------------------===// void FunctionDecl::EmitImpl(Serializer& S) const { S.EmitInt(SClass); // From FunctionDecl. S.EmitBool(IsInline); // From FunctionDecl. ValueDecl::EmitInRec(S); S.EmitPtr(PreviousDeclaration); // NOTE: We do not need to serialize out the number of parameters, because // that is encoded in the type (accessed via getNumParams()). if (ParamInfo != NULL) { S.EmitBool(true); S.EmitInt(getNumParams()); S.BatchEmitOwnedPtrs(getNumParams(),&ParamInfo[0], Body); } else { S.EmitBool(false); S.EmitOwnedPtr(Body); } } FunctionDecl* FunctionDecl::CreateImpl(Deserializer& D, ASTContext& C) { StorageClass SClass = static_cast<StorageClass>(D.ReadInt()); bool IsInline = D.ReadBool(); FunctionDecl* decl = new (C) FunctionDecl(Function, 0, SourceLocation(), DeclarationName(), QualType(), SClass, IsInline); decl->ValueDecl::ReadInRec(D, C); D.ReadPtr(decl->PreviousDeclaration); int numParams = 0; bool hasParamDecls = D.ReadBool(); if (hasParamDecls) numParams = D.ReadInt(); decl->ParamInfo = hasParamDecls ? new ParmVarDecl*[numParams] : NULL; if (hasParamDecls) D.BatchReadOwnedPtrs(numParams, reinterpret_cast<Decl**>(&decl->ParamInfo[0]), decl->Body, C); else decl->Body = D.ReadOwnedPtr<Stmt>(C); return decl; } void BlockDecl::EmitImpl(Serializer& S) const { // FIXME: what about arguments? S.Emit(getCaretLocation()); S.EmitOwnedPtr(Body); } BlockDecl* BlockDecl::CreateImpl(Deserializer& D, ASTContext& C) { QualType Q = QualType::ReadVal(D); SourceLocation L = SourceLocation::ReadVal(D); /*CompoundStmt* BodyStmt = cast<CompoundStmt>(*/D.ReadOwnedPtr<Stmt>(C)/*)*/; assert(0 && "Cannot deserialize BlockBlockExpr yet"); // FIXME: need to handle parameters. //return new BlockBlockExpr(L, Q, BodyStmt); return 0; } //===----------------------------------------------------------------------===// // OverloadedFunctionDecl Serialization. //===----------------------------------------------------------------------===// void OverloadedFunctionDecl::EmitImpl(Serializer& S) const { NamedDecl::EmitInRec(S); S.EmitInt(getNumFunctions()); for (unsigned func = 0; func < getNumFunctions(); ++func) S.EmitPtr(Functions[func]); } OverloadedFunctionDecl * OverloadedFunctionDecl::CreateImpl(Deserializer& D, ASTContext& C) { OverloadedFunctionDecl* decl = new (C) OverloadedFunctionDecl(0, DeclarationName()); decl->NamedDecl::ReadInRec(D, C); unsigned numFunctions = D.ReadInt(); decl->Functions.reserve(numFunctions); for (unsigned func = 0; func < numFunctions; ++func) D.ReadPtr(decl->Functions[func]); return decl; } //===----------------------------------------------------------------------===// // RecordDecl Serialization. //===----------------------------------------------------------------------===// void RecordDecl::EmitImpl(Serializer& S) const { S.EmitInt(getTagKind()); NamedDecl::EmitInRec(S); S.EmitBool(isDefinition()); S.EmitBool(hasFlexibleArrayMember()); S.EmitBool(isAnonymousStructOrUnion()); } RecordDecl* RecordDecl::CreateImpl(Deserializer& D, ASTContext& C) { TagKind TK = TagKind(D.ReadInt()); RecordDecl* decl = new (C) RecordDecl(Record, TK, 0, SourceLocation(), NULL); decl->NamedDecl::ReadInRec(D, C); decl->setDefinition(D.ReadBool()); decl->setHasFlexibleArrayMember(D.ReadBool()); decl->setAnonymousStructOrUnion(D.ReadBool()); return decl; } //===----------------------------------------------------------------------===// // TypedefDecl Serialization. //===----------------------------------------------------------------------===// void TypedefDecl::EmitImpl(Serializer& S) const { S.Emit(UnderlyingType); NamedDecl::EmitInRec(S); } TypedefDecl* TypedefDecl::CreateImpl(Deserializer& D, ASTContext& C) { QualType T = QualType::ReadVal(D); TypedefDecl* decl = new (C) TypedefDecl(0, SourceLocation(), NULL, T); decl->NamedDecl::ReadInRec(D, C); return decl; } //===----------------------------------------------------------------------===// // TemplateTypeParmDecl Serialization. //===----------------------------------------------------------------------===// void TemplateTypeParmDecl::EmitImpl(Serializer& S) const { S.EmitBool(Typename); TypeDecl::EmitInRec(S); } TemplateTypeParmDecl * TemplateTypeParmDecl::CreateImpl(Deserializer& D, ASTContext& C) { bool Typename = D.ReadBool(); TemplateTypeParmDecl *decl = new (C) TemplateTypeParmDecl(0, SourceLocation(), 0, Typename, QualType()); decl->TypeDecl::ReadInRec(D, C); return decl; } //===----------------------------------------------------------------------===// // NonTypeTemplateParmDecl Serialization. //===----------------------------------------------------------------------===// void NonTypeTemplateParmDecl::EmitImpl(Serializer& S) const { S.EmitInt(Depth); S.EmitInt(Position); NamedDecl::Emit(S); } NonTypeTemplateParmDecl* NonTypeTemplateParmDecl::CreateImpl(Deserializer& D, ASTContext& C) { unsigned Depth = D.ReadInt(); unsigned Position = D.ReadInt(); NonTypeTemplateParmDecl *decl = new (C) NonTypeTemplateParmDecl(0, SourceLocation(), Depth, Position, 0, QualType(), SourceLocation()); decl->NamedDecl::ReadInRec(D, C); return decl; } //===----------------------------------------------------------------------===// // TemplateTemplateParmDecl Serialization. //===----------------------------------------------------------------------===// void TemplateTemplateParmDecl::EmitImpl(Serializer& S) const { S.EmitInt(Depth); S.EmitInt(Position); NamedDecl::EmitInRec(S); } TemplateTemplateParmDecl* TemplateTemplateParmDecl::CreateImpl(Deserializer& D, ASTContext& C) { unsigned Depth = D.ReadInt(); unsigned Position = D.ReadInt(); TemplateTemplateParmDecl *decl = new (C) TemplateTemplateParmDecl(0, SourceLocation(), Depth, Position, 0, 0); decl->NamedDecl::ReadInRec(D, C); return decl; } //===----------------------------------------------------------------------===// // LinkageSpec Serialization. //===----------------------------------------------------------------------===// void LinkageSpecDecl::EmitInRec(Serializer& S) const { S.EmitInt(getLanguage()); S.EmitBool(HadBraces); } void LinkageSpecDecl::ReadInRec(Deserializer& D, ASTContext& C) { Language = static_cast<LanguageIDs>(D.ReadInt()); HadBraces = D.ReadBool(); } //===----------------------------------------------------------------------===// // FileScopeAsm Serialization. //===----------------------------------------------------------------------===// void FileScopeAsmDecl::EmitImpl(llvm::Serializer& S) const { S.EmitOwnedPtr(AsmString); } FileScopeAsmDecl* FileScopeAsmDecl::CreateImpl(Deserializer& D, ASTContext& C) { FileScopeAsmDecl* decl = new (C) FileScopeAsmDecl(0, SourceLocation(), 0); decl->AsmString = cast<StringLiteral>(D.ReadOwnedPtr<Expr>(C)); // D.ReadOwnedPtr(D.ReadOwnedPtr<StringLiteral>())<#T * * Ptr#>, <#bool AutoRegister#>)(decl->AsmString); return decl; } <file_sep>/test/CodeGenCXX/mangle.cpp // RUN: clang-cc -emit-llvm %s -o %t && // FIXME: This test is intentionally trivial, because we can't yet // CodeGen anything real in C++. struct X { }; struct Y { }; // RUN: grep _ZplRK1YRA100_P1X %t | count 1 && bool operator+(const Y&, X* (&xs)[100]) { return false; } // RUN: grep _Z1f1s %t | count 1 && typedef struct { int a; } s; void f(s) { } // RUN: grep _Z1f1e %t| count 1 && typedef enum { foo } e; void f(e) { } // RUN: grep _Z1f1u %t | count 1 && typedef union { int a; } u; void f(u) { } // RUN: grep _Z1f1x %t | count 1 && typedef struct { int a; } x,y; void f(y) { } // RUN: grep _Z1fv %t | count 1 && void f() { } // RUN: grep _ZN1N1fEv %t | count 1 && namespace N { void f() { } } // RUN: grep _ZN1N1N1fEv %t | count 1 && namespace N { namespace N { void f() { } } } // RUN: grep unmangled_function %t | count 1 && extern "C" { namespace N { void unmangled_function() { } } } // RUN: grep unmangled_variable %t | count 1 && extern "C" { namespace N { int unmangled_variable; } } // RUN: grep _ZN1N1iE %t | count 1 && namespace N { int i; } // RUN: grep _ZZN1N1fEiiE1b %t | count 2 && namespace N { int f(int, int) { static int b; return b; } } // RUN: grep "_ZZN1N1gEvE1a =" %t | count 1 && // RUN: grep "_ZGVZN1N1gEvE1a =" %t | count 1 namespace N { int h(); void g() { static int a = h(); } } <file_sep>/lib/Basic/LangOptions.cpp //===--- LangOptions.cpp - Language feature info --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the methods for LangOptions. // //===----------------------------------------------------------------------===// #include "clang/Basic/LangOptions.h" #include "llvm/Bitcode/Serialize.h" #include "llvm/Bitcode/Deserialize.h" using namespace clang; void LangOptions::Emit(llvm::Serializer& S) const { S.EmitBool((bool) Trigraphs); S.EmitBool((bool) BCPLComment); S.EmitBool((bool) DollarIdents); S.EmitBool((bool) Digraphs); S.EmitBool((bool) HexFloats); S.EmitBool((bool) C99); S.EmitBool((bool) Microsoft); S.EmitBool((bool) CPlusPlus); S.EmitBool((bool) CPlusPlus0x); S.EmitBool((bool) NoExtensions); S.EmitBool((bool) CXXOperatorNames); S.EmitBool((bool) ObjC1); S.EmitBool((bool) ObjC2); S.EmitBool((unsigned) GC); S.EmitBool((bool) PascalStrings); S.EmitBool((bool) Boolean); S.EmitBool((bool) WritableStrings); S.EmitBool((bool) LaxVectorConversions); } void LangOptions::Read(llvm::Deserializer& D) { Trigraphs = D.ReadBool() ? 1 : 0; BCPLComment = D.ReadBool() ? 1 : 0; DollarIdents = D.ReadBool() ? 1 : 0; Digraphs = D.ReadBool() ? 1 : 0; HexFloats = D.ReadBool() ? 1 : 0; C99 = D.ReadBool() ? 1 : 0; Microsoft = D.ReadBool() ? 1 : 0; CPlusPlus = D.ReadBool() ? 1 : 0; CPlusPlus0x = D.ReadBool() ? 1 : 0; NoExtensions = D.ReadBool() ? 1 : 0; CXXOperatorNames = D.ReadBool() ? 1 : 0; ObjC1 = D.ReadBool() ? 1 : 0; ObjC2 = D.ReadBool() ? 1 : 0; GC = D.ReadInt(); PascalStrings = D.ReadBool() ? 1 : 0; Boolean = D.ReadBool() ? 1 : 0; WritableStrings = D.ReadBool() ? 1 : 0; LaxVectorConversions = D.ReadBool() ? 1 : 0; } <file_sep>/utils/ABITest/return-types/Makefile # Usage: make test.N.report # # COUNT can be over-ridden to change the number of tests generated per # file, and TESTARGS is used to change the type generation. Make sure # to 'make clean' after changing either of these parameters. ABITESTGEN := ../ABITestGen.py TESTARGS := --max-args 0 COUNT := 1 TIMEOUT := 5 CFLAGS := -std=gnu99 X_COMPILER := llvm-gcc X_LL_CFLAGS := -emit-llvm -S Y_COMPILER := xcc -ccc-clang Y_LL_CFLAGS := -emit-llvm -S CC := gcc ifeq (0, 1) X_CFLAGS := -m32 Y_CFLAGS := -m32 CC_CFLAGS := -m32 else X_CFLAGS := -m64 Y_CFLAGS := -m64 CC_CFLAGS := -m64 endif ifndef VERBOSE Verb := @ endif .PHONY: test.%.report test.%.report: test.%.xx.diff test.%.xy.diff test.%.yx.diff test.%.yy.diff @ok=1;\ for t in $^; do \ if [ -s $$t ]; then \ echo "TEST $*: $$t failed"; \ ok=0;\ fi; \ done; \ if [ $$ok == 1 ]; then \ echo "TEST $*: OK"; \ else \ false; \ fi .PHONY: test.%.defs-report test.%.defs-report: test.%.defs.diff @for t in $^; do \ if [ -s $$t ]; then \ echo "TEST $*: $$t failed"; \ cat $$t; \ fi; \ done .PHONY: test.%.build test.%.build: test.%.ref test.%.xx test.%.xy test.%.yx test.%.yy test.%.x.defs test.%.y.defs @true ### .PRECIOUS: test.%.xx.diff test.%.xx.diff: test.%.ref.out test.%.xx.out $(Verb) diff $^ > $@ || true .PRECIOUS: test.%.xy.diff test.%.xy.diff: test.%.ref.out test.%.xy.out $(Verb) diff $^ > $@ || true .PRECIOUS: test.%.yx.diff test.%.yx.diff: test.%.ref.out test.%.yx.out $(Verb) diff $^ > $@ || true .PRECIOUS: test.%.yy.diff test.%.yy.diff: test.%.ref.out test.%.yy.out $(Verb) diff $^ > $@ || true .PRECIOUS: test.%.defs.diff test.%.defs.diff: test.%.x.defs test.%.y.defs $(Verb) zipdifflines \ --replace "%struct.T[0-9]+" "%struct.s" \ --replace "byval align [0-9]+" "byval" \ $^ > $@ .PRECIOUS: test.%.out test.%.out: test.% $(Verb) -RunSafely.sh $(TIMEOUT) 1 /dev/null $@ ./$< .PRECIOUS: test.%.ref test.%.ref: test.%.driver.ref.o test.%.a.ref.o test.%.b.ref.o $(Verb) $(CC) $(CFLAGS) $(CC_CFLAGS) -o $@ $^ .PRECIOUS: test.%.xx test.%.xx: test.%.driver.ref.o test.%.a.x.o test.%.b.x.o $(Verb) $(CC) $(CFLAGS) $(CC_CFLAGS) -o $@ $^ .PRECIOUS: test.%.xy test.%.xy: test.%.driver.ref.o test.%.a.x.o test.%.b.y.o $(Verb) $(CC) $(CFLAGS) $(CC_CFLAGS) -o $@ $^ .PRECIOUS: test.%.yx test.%.yx: test.%.driver.ref.o test.%.a.y.o test.%.b.x.o $(Verb) $(CC) $(CFLAGS) $(CC_CFLAGS) -o $@ $^ .PRECIOUS: test.%.yy test.%.yy: test.%.driver.ref.o test.%.a.y.o test.%.b.y.o $(Verb) $(CC) $(CFLAGS) $(CC_CFLAGS) -o $@ $^ .PRECIOUS: test.%.ref.o test.%.ref.o: test.%.c $(Verb) $(CC) -c $(CFLAGS) $(CC_CFLAGS) -o $@ $< .PRECIOUS: test.%.x.o test.%.x.o: test.%.c $(Verb) $(X_COMPILER) -c $(CFLAGS) $(X_CFLAGS) -o $@ $< .PRECIOUS: test.%.y.o test.%.y.o: test.%.c $(Verb) $(Y_COMPILER) -c $(CFLAGS) $(Y_CFLAGS) -o $@ $< .PRECIOUS: test.%.x.defs test.%.x.defs: test.%.a.x.ll -$(Verb) -grep '^define ' $< > $@ .PRECIOUS: test.%.y.defs test.%.y.defs: test.%.a.y.ll -$(Verb) -grep '^define ' $< > $@ .PRECIOUS: test.%.a.x.ll test.%.a.x.ll: test.%.a.c $(Verb) $(X_COMPILER) $(CFLAGS) $(X_LL_CFLAGS) $(X_CFLAGS) -o $@ $< .PRECIOUS: test.%.b.x.ll test.%.b.x.ll: test.%.b.c $(Verb) $(X_COMPILER) $(CFLAGS) $(X_LL_CFLAGS) $(X_CFLAGS) -o $@ $< .PRECIOUS: test.%.a.y.ll test.%.a.y.ll: test.%.a.c $(Verb) $(Y_COMPILER) $(CFLAGS) $(Y_LL_CFLAGS) $(Y_CFLAGS) -o $@ $< .PRECIOUS: test.%.b.y.ll test.%.b.y.ll: test.%.b.c $(Verb) $(Y_COMPILER) $(CFLAGS) $(Y_LL_CFLAGS) $(Y_CFLAGS) -o $@ $< .PHONY: test.%.top test.%.top: test.%.a.c test.%.b.c test.%.driver.c @true .PRECIOUS: test.%.a.c test.%.b.c test.%.driver.c test.%.a.c: test.%.generate @true test.%.b.c: test.%.generate @true test.%.driver.c: test.%.generate @true .PHONY: test.%.generate test.%.generate: $(ABITESTGEN) $(ABITESTGEN) $(TESTARGS) -o test.$*.a.c -T test.$*.b.c -D test.$*.driver.c --min=$(shell expr $* '*' $(COUNT)) --count=$(COUNT) clean: rm -f test.* *~ <file_sep>/test/SemaCXX/access-base-class.cpp // RUN: clang-cc -fsyntax-only -verify %s namespace T1 { class A { }; class B : private A { }; // expected-note {{'private' inheritance specifier here}} void f(B* b) { A *a = b; // expected-error{{conversion from 'class T1::B' to inaccessible base class 'class T1::A'}} \ expected-error{{incompatible type initializing 'class T1::B *', expected 'class T1::A *'}} } } namespace T2 { class A { }; class B : A { }; // expected-note {{inheritance is implicitly 'private'}} void f(B* b) { A *a = b; // expected-error {{conversion from 'class T2::B' to inaccessible base class 'class T2::A'}} \ expected-error {{incompatible type initializing 'class T2::B *', expected 'class T2::A *'}} } } namespace T3 { class A { }; class B : public A { }; void f(B* b) { A *a = b; } } namespace T4 { class A {}; class B : private virtual A {}; class C : public virtual A {}; class D : public B, public C {}; void f(D *d) { // This takes the D->C->B->A path. A *a = d; } } namespace T5 { class A {}; class B : private A { void f(B *b) { A *a = b; } }; } namespace T6 { class C; class A {}; class B : private A { // expected-note {{'private' inheritance specifier here}} void f(C* c); }; class C : public B { void f(C *c) { A* a = c; // expected-error {{conversion from 'class T6::C' to inaccessible base class 'class T6::A'}} \ expected-error {{incompatible type initializing 'class T6::C *', expected 'class T6::A *'}} } }; void B::f(C *c) { A *a = c; } } <file_sep>/include/clang/AST/Type.h //===--- Type.h - C Language Family Type Representation ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Type interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_TYPE_H #define LLVM_CLANG_AST_TYPE_H #include "clang/Basic/Diagnostic.h" #include "clang/Basic/IdentifierTable.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/TemplateName.h" #include "llvm/Support/Casting.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/Bitcode/SerializationFwd.h" using llvm::isa; using llvm::cast; using llvm::cast_or_null; using llvm::dyn_cast; using llvm::dyn_cast_or_null; namespace llvm { template <typename T> class PointerLikeTypeTraits; } namespace clang { class ASTContext; class Type; class TypedefDecl; class TemplateDecl; class TemplateTypeParmDecl; class NonTypeTemplateParmDecl; class TemplateTemplateParmDecl; class TagDecl; class RecordDecl; class CXXRecordDecl; class EnumDecl; class FieldDecl; class ObjCInterfaceDecl; class ObjCProtocolDecl; class ObjCMethodDecl; class Expr; class Stmt; class SourceLocation; class StmtIteratorBase; class TemplateArgument; class QualifiedNameType; // Provide forward declarations for all of the *Type classes #define TYPE(Class, Base) class Class##Type; #include "clang/AST/TypeNodes.def" /// QualType - For efficiency, we don't store CVR-qualified types as nodes on /// their own: instead each reference to a type stores the qualifiers. This /// greatly reduces the number of nodes we need to allocate for types (for /// example we only need one for 'int', 'const int', 'volatile int', /// 'const volatile int', etc). /// /// As an added efficiency bonus, instead of making this a pair, we just store /// the three bits we care about in the low bits of the pointer. To handle the /// packing/unpacking, we make QualType be a simple wrapper class that acts like /// a smart pointer. class QualType { llvm::PointerIntPair<Type*, 3> Value; public: enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. Const = 0x1, Restrict = 0x2, Volatile = 0x4, CVRFlags = Const|Restrict|Volatile }; enum GCAttrTypes { GCNone = 0, Weak, Strong }; QualType() {} QualType(const Type *Ptr, unsigned Quals) : Value(const_cast<Type*>(Ptr), Quals) {} unsigned getCVRQualifiers() const { return Value.getInt(); } void setCVRQualifiers(unsigned Quals) { Value.setInt(Quals); } Type *getTypePtr() const { return Value.getPointer(); } void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } static QualType getFromOpaquePtr(void *Ptr) { QualType T; T.Value.setFromOpaqueValue(Ptr); return T; } Type &operator*() const { return *getTypePtr(); } Type *operator->() const { return getTypePtr(); } /// isNull - Return true if this QualType doesn't point to a type yet. bool isNull() const { return getTypePtr() == 0; } bool isConstQualified() const { return (getCVRQualifiers() & Const) ? true : false; } bool isVolatileQualified() const { return (getCVRQualifiers() & Volatile) ? true : false; } bool isRestrictQualified() const { return (getCVRQualifiers() & Restrict) ? true : false; } bool isConstant(ASTContext& Ctx) const; /// addConst/addVolatile/addRestrict - add the specified type qual to this /// QualType. void addConst() { Value.setInt(Value.getInt() | Const); } void addVolatile() { Value.setInt(Value.getInt() | Volatile); } void addRestrict() { Value.setInt(Value.getInt() | Restrict); } void removeConst() { Value.setInt(Value.getInt() & ~Const); } void removeVolatile() { Value.setInt(Value.getInt() & ~Volatile); } void removeRestrict() { Value.setInt(Value.getInt() & ~Restrict); } QualType getQualifiedType(unsigned TQs) const { return QualType(getTypePtr(), TQs); } QualType getWithAdditionalQualifiers(unsigned TQs) const { return QualType(getTypePtr(), TQs|getCVRQualifiers()); } QualType withConst() const { return getWithAdditionalQualifiers(Const); } QualType withVolatile() const { return getWithAdditionalQualifiers(Volatile);} QualType withRestrict() const { return getWithAdditionalQualifiers(Restrict);} QualType getUnqualifiedType() const; bool isMoreQualifiedThan(QualType Other) const; bool isAtLeastAsQualifiedAs(QualType Other) const; QualType getNonReferenceType() const; /// getDesugaredType - Return the specified type with any "sugar" removed from /// the type. This takes off typedefs, typeof's etc. If the outer level of /// the type is already concrete, it returns it unmodified. This is similar /// to getting the canonical type, but it doesn't remove *all* typedefs. For /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is /// concrete. QualType getDesugaredType(bool ForDisplay = false) const; /// operator==/!= - Indicate whether the specified types and qualifiers are /// identical. bool operator==(const QualType &RHS) const { return Value == RHS.Value; } bool operator!=(const QualType &RHS) const { return Value != RHS.Value; } std::string getAsString() const { std::string S; getAsStringInternal(S); return S; } void getAsStringInternal(std::string &Str) const; void dump(const char *s) const; void dump() const; void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddPointer(getAsOpaquePtr()); } public: /// getAddressSpace - Return the address space of this type. inline unsigned getAddressSpace() const; /// GCAttrTypesAttr - Returns gc attribute of this type. inline QualType::GCAttrTypes getObjCGCAttr() const; /// isObjCGCWeak true when Type is objc's weak. bool isObjCGCWeak() const { return getObjCGCAttr() == Weak; } /// isObjCGCStrong true when Type is objc's strong. bool isObjCGCStrong() const { return getObjCGCAttr() == Strong; } /// Emit - Serialize a QualType to Bitcode. void Emit(llvm::Serializer& S) const; /// Read - Deserialize a QualType from Bitcode. static QualType ReadVal(llvm::Deserializer& D); void ReadBackpatch(llvm::Deserializer& D); }; } // end clang. namespace llvm { /// Implement simplify_type for QualType, so that we can dyn_cast from QualType /// to a specific Type class. template<> struct simplify_type<const ::clang::QualType> { typedef ::clang::Type* SimpleType; static SimpleType getSimplifiedValue(const ::clang::QualType &Val) { return Val.getTypePtr(); } }; template<> struct simplify_type< ::clang::QualType> : public simplify_type<const ::clang::QualType> {}; // Teach SmallPtrSet that QualType is "basically a pointer". template<> class PointerLikeTypeTraits<clang::QualType> { public: static inline void *getAsVoidPointer(clang::QualType P) { return P.getAsOpaquePtr(); } static inline clang::QualType getFromVoidPointer(void *P) { return clang::QualType::getFromOpaquePtr(P); } // CVR qualifiers go in low bits. enum { NumLowBitsAvailable = 0 }; }; } // end namespace llvm namespace clang { /// Type - This is the base class of the type hierarchy. A central concept /// with types is that each type always has a canonical type. A canonical type /// is the type with any typedef names stripped out of it or the types it /// references. For example, consider: /// /// typedef int foo; /// typedef foo* bar; /// 'int *' 'foo *' 'bar' /// /// There will be a Type object created for 'int'. Since int is canonical, its /// canonicaltype pointer points to itself. There is also a Type for 'foo' (a /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next /// there is a PointerType that represents 'int*', which, like 'int', is /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type /// is also 'int*'. /// /// Non-canonical types are useful for emitting diagnostics, without losing /// information about typedefs being used. Canonical types are useful for type /// comparisons (they allow by-pointer equality tests) and useful for reasoning /// about whether something has a particular form (e.g. is a function type), /// because they implicitly, recursively, strip all typedefs out of a type. /// /// Types, once created, are immutable. /// class Type { public: enum TypeClass { #define TYPE(Class, Base) Class, #define ABSTRACT_TYPE(Class, Base) #include "clang/AST/TypeNodes.def" TagFirst = Record, TagLast = Enum }; private: QualType CanonicalType; /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]). bool Dependent : 1; /// TypeClass bitfield - Enum that specifies what subclass this belongs to. /// Note that this should stay at the end of the ivars for Type so that /// subclasses can pack their bitfields into the same word. unsigned TC : 5; Type(const Type&); // DO NOT IMPLEMENT. void operator=(const Type&); // DO NOT IMPLEMENT. protected: // silence VC++ warning C4355: 'this' : used in base member initializer list Type *this_() { return this; } Type(TypeClass tc, QualType Canonical, bool dependent) : CanonicalType(Canonical.isNull() ? QualType(this_(), 0) : Canonical), Dependent(dependent), TC(tc) {} virtual ~Type() {} virtual void Destroy(ASTContext& C); friend class ASTContext; void EmitTypeInternal(llvm::Serializer& S) const; void ReadTypeInternal(llvm::Deserializer& D); public: TypeClass getTypeClass() const { return static_cast<TypeClass>(TC); } bool isCanonical() const { return CanonicalType.getTypePtr() == this; } /// Types are partitioned into 3 broad categories (C99 6.2.5p1): /// object types, function types, and incomplete types. /// \brief Determines whether the type describes an object in memory. /// /// Note that this definition of object type corresponds to the C++ /// definition of object type, which includes incomplete types, as /// opposed to the C definition (which does not include incomplete /// types). bool isObjectType() const; /// isIncompleteType - Return true if this is an incomplete type. /// A type that can describe objects, but which lacks information needed to /// determine its size (e.g. void, or a fwd declared struct). Clients of this /// routine will need to determine if the size is actually required. bool isIncompleteType() const; /// isIncompleteOrObjectType - Return true if this is an incomplete or object /// type, in other words, not a function type. bool isIncompleteOrObjectType() const { return !isFunctionType(); } /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10). bool isPODType() const; /// isVariablyModifiedType (C99 6.7.5.2p2) - Return true for variable array /// types that have a non-constant expression. This does not include "[]". bool isVariablyModifiedType() const; /// Helper methods to distinguish type categories. All type predicates /// operate on the canonical type, ignoring typedefs and qualifiers. /// isSpecificBuiltinType - Test for a particular builtin type. bool isSpecificBuiltinType(unsigned K) const; /// isIntegerType() does *not* include complex integers (a GCC extension). /// isComplexIntegerType() can be used to test for complex integers. bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) bool isEnumeralType() const; bool isBooleanType() const; bool isCharType() const; bool isWideCharType() const; bool isIntegralType() const; /// Floating point categories. bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) /// isComplexType() does *not* include complex integers (a GCC extension). /// isComplexIntegerType() can be used to test for complex integers. bool isComplexType() const; // C99 6.2.5p11 (complex) bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) bool isRealType() const; // C99 6.2.5p17 (real floating + integer) bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) bool isVoidType() const; // C99 6.2.5p19 bool isDerivedType() const; // C99 6.2.5p20 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) bool isAggregateType() const; // Type Predicates: Check to see if this type is structurally the specified // type, ignoring typedefs and qualifiers. bool isFunctionType() const; bool isFunctionNoProtoType() const { return getAsFunctionNoProtoType() != 0; } bool isFunctionProtoType() const { return getAsFunctionProtoType() != 0; } bool isPointerType() const; bool isBlockPointerType() const; bool isReferenceType() const; bool isLValueReferenceType() const; bool isRValueReferenceType() const; bool isFunctionPointerType() const; bool isMemberPointerType() const; bool isMemberFunctionPointerType() const; bool isArrayType() const; bool isConstantArrayType() const; bool isIncompleteArrayType() const; bool isVariableArrayType() const; bool isDependentSizedArrayType() const; bool isRecordType() const; bool isClassType() const; bool isStructureType() const; bool isUnionType() const; bool isComplexIntegerType() const; // GCC _Complex integer type. bool isVectorType() const; // GCC vector type. bool isExtVectorType() const; // Extended vector type. bool isObjCInterfaceType() const; // NSString or NSString<foo> bool isObjCQualifiedInterfaceType() const; // NSString<foo> bool isObjCQualifiedIdType() const; // id<foo> bool isTemplateTypeParmType() const; // C++ template type parameter /// isDependentType - Whether this type is a dependent type, meaning /// that its definition somehow depends on a template parameter /// (C++ [temp.dep.type]). bool isDependentType() const { return Dependent; } bool isOverloadableType() const; /// hasPointerRepresentation - Whether this type is represented /// natively as a pointer; this includes pointers, references, block /// pointers, and Objective-C interface, qualified id, and qualified /// interface types. bool hasPointerRepresentation() const; /// hasObjCPointerRepresentation - Whether this type can represent /// an objective pointer type for the purpose of GC'ability bool hasObjCPointerRepresentation() const; // Type Checking Functions: Check to see if this type is structurally the // specified type, ignoring typedefs and qualifiers, and return a pointer to // the best type we can. const BuiltinType *getAsBuiltinType() const; const FunctionType *getAsFunctionType() const; const FunctionNoProtoType *getAsFunctionNoProtoType() const; const FunctionProtoType *getAsFunctionProtoType() const; const PointerType *getAsPointerType() const; const BlockPointerType *getAsBlockPointerType() const; const ReferenceType *getAsReferenceType() const; const LValueReferenceType *getAsLValueReferenceType() const; const RValueReferenceType *getAsRValueReferenceType() const; const MemberPointerType *getAsMemberPointerType() const; const TagType *getAsTagType() const; const RecordType *getAsRecordType() const; const RecordType *getAsStructureType() const; /// NOTE: getAs*ArrayType are methods on ASTContext. const TypedefType *getAsTypedefType() const; const RecordType *getAsUnionType() const; const EnumType *getAsEnumType() const; const VectorType *getAsVectorType() const; // GCC vector type. const ComplexType *getAsComplexType() const; const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. const ExtVectorType *getAsExtVectorType() const; // Extended vector type. const ObjCInterfaceType *getAsObjCInterfaceType() const; const ObjCQualifiedInterfaceType *getAsObjCQualifiedInterfaceType() const; const ObjCQualifiedIdType *getAsObjCQualifiedIdType() const; const TemplateTypeParmType *getAsTemplateTypeParmType() const; const TemplateSpecializationType * getAsTemplateSpecializationType() const; /// getAsPointerToObjCInterfaceType - If this is a pointer to an ObjC /// interface, return the interface type, otherwise return null. const ObjCInterfaceType *getAsPointerToObjCInterfaceType() const; /// getArrayElementTypeNoTypeQual - If this is an array type, return the /// element type of the array, potentially with type qualifiers missing. /// This method should never be used when type qualifiers are meaningful. const Type *getArrayElementTypeNoTypeQual() const; /// getDesugaredType - Return the specified type with any "sugar" removed from /// the type. This takes off typedefs, typeof's etc. If the outer level of /// the type is already concrete, it returns it unmodified. This is similar /// to getting the canonical type, but it doesn't remove *all* typedefs. For /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is /// concrete. QualType getDesugaredType(bool ForDisplay = false) const; /// More type predicates useful for type checking/promotion bool isPromotableIntegerType() const; // C99 6.3.1.1p2 /// isSignedIntegerType - Return true if this is an integer type that is /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], /// an enum decl which has a signed representation, or a vector of signed /// integer element type. bool isSignedIntegerType() const; /// isUnsignedIntegerType - Return true if this is an integer type that is /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum /// decl which has an unsigned representation, or a vector of unsigned integer /// element type. bool isUnsignedIntegerType() const; /// isConstantSizeType - Return true if this is not a variable sized type, /// according to the rules of C99 6.7.5p3. It is not legal to call this on /// incomplete types. bool isConstantSizeType() const; QualType getCanonicalTypeInternal() const { return CanonicalType; } void dump() const; virtual void getAsStringInternal(std::string &InnerString) const = 0; static bool classof(const Type *) { return true; } protected: /// Emit - Emit a Type to bitcode. Used by ASTContext. void Emit(llvm::Serializer& S) const; /// Create - Construct a Type from bitcode. Used by ASTContext. static void Create(ASTContext& Context, unsigned i, llvm::Deserializer& S); /// EmitImpl - Subclasses must implement this method in order to /// be serialized. // FIXME: Make this abstract once implemented. virtual void EmitImpl(llvm::Serializer& S) const { assert(false && "Serialization for type not supported."); } }; /// ExtQualType - TR18037 (C embedded extensions) 6.2.5p26 /// This supports all kinds of type attributes; including, /// address space qualified types, objective-c's __weak and /// __strong attributes. /// class ExtQualType : public Type, public llvm::FoldingSetNode { /// BaseType - This is the underlying type that this qualifies. All CVR /// qualifiers are stored on the QualType that references this type, so we /// can't have any here. Type *BaseType; /// Address Space ID - The address space ID this type is qualified with. unsigned AddressSpace; /// GC __weak/__strong attributes QualType::GCAttrTypes GCAttrType; ExtQualType(Type *Base, QualType CanonicalPtr, unsigned AddrSpace, QualType::GCAttrTypes gcAttr) : Type(ExtQual, CanonicalPtr, Base->isDependentType()), BaseType(Base), AddressSpace(AddrSpace), GCAttrType(gcAttr) { assert(!isa<ExtQualType>(BaseType) && "Cannot have ExtQualType of ExtQualType"); } friend class ASTContext; // ASTContext creates these. public: Type *getBaseType() const { return BaseType; } QualType::GCAttrTypes getObjCGCAttr() const { return GCAttrType; } unsigned getAddressSpace() const { return AddressSpace; } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getBaseType(), AddressSpace, GCAttrType); } static void Profile(llvm::FoldingSetNodeID &ID, Type *Base, unsigned AddrSpace, QualType::GCAttrTypes gcAttr) { ID.AddPointer(Base); ID.AddInteger(AddrSpace); ID.AddInteger(gcAttr); } static bool classof(const Type *T) { return T->getTypeClass() == ExtQual; } static bool classof(const ExtQualType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// BuiltinType - This class is used for builtin types like 'int'. Builtin /// types are always canonical and have a literal name field. class BuiltinType : public Type { public: enum Kind { Void, Bool, // This is bool and/or _Bool. Char_U, // This is 'char' for targets where char is unsigned. UChar, // This is explicitly qualified unsigned char. UShort, UInt, ULong, ULongLong, Char_S, // This is 'char' for targets where char is signed. SChar, // This is explicitly qualified signed char. WChar, // This is 'wchar_t' for C++. Short, Int, Long, LongLong, Float, Double, LongDouble, Overload, // This represents the type of an overloaded function declaration. Dependent // This represents the type of a type-dependent expression. }; private: Kind TypeKind; public: BuiltinType(Kind K) : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent)), TypeKind(K) {} Kind getKind() const { return TypeKind; } const char *getName() const; virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } static bool classof(const BuiltinType *) { return true; } }; /// FixedWidthIntType - Used for arbitrary width types that we either don't /// want to or can't map to named integer types. These always have a lower /// integer rank than builtin types of the same width. class FixedWidthIntType : public Type { private: unsigned Width; bool Signed; public: FixedWidthIntType(unsigned W, bool S) : Type(FixedWidthInt, QualType(), false), Width(W), Signed(S) {} unsigned getWidth() const { return Width; } bool isSigned() const { return Signed; } const char *getName() const; virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == FixedWidthInt; } static bool classof(const FixedWidthIntType *) { return true; } }; /// ComplexType - C99 6.2.5p11 - Complex values. This supports the C99 complex /// types (_Complex float etc) as well as the GCC integer complex extensions. /// class ComplexType : public Type, public llvm::FoldingSetNode { QualType ElementType; ComplexType(QualType Element, QualType CanonicalPtr) : Type(Complex, CanonicalPtr, Element->isDependentType()), ElementType(Element) { } friend class ASTContext; // ASTContext creates these. public: QualType getElementType() const { return ElementType; } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getElementType()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { ID.AddPointer(Element.getAsOpaquePtr()); } static bool classof(const Type *T) { return T->getTypeClass() == Complex; } static bool classof(const ComplexType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// PointerType - C99 6.7.5.1 - Pointer Declarators. /// class PointerType : public Type, public llvm::FoldingSetNode { QualType PointeeType; PointerType(QualType Pointee, QualType CanonicalPtr) : Type(Pointer, CanonicalPtr, Pointee->isDependentType()), PointeeType(Pointee) { } friend class ASTContext; // ASTContext creates these. public: virtual void getAsStringInternal(std::string &InnerString) const; QualType getPointeeType() const { return PointeeType; } void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getPointeeType()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { ID.AddPointer(Pointee.getAsOpaquePtr()); } static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } static bool classof(const PointerType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// BlockPointerType - pointer to a block type. /// This type is to represent types syntactically represented as /// "void (^)(int)", etc. Pointee is required to always be a function type. /// class BlockPointerType : public Type, public llvm::FoldingSetNode { QualType PointeeType; // Block is some kind of pointer type BlockPointerType(QualType Pointee, QualType CanonicalCls) : Type(BlockPointer, CanonicalCls, Pointee->isDependentType()), PointeeType(Pointee) { } friend class ASTContext; // ASTContext creates these. public: // Get the pointee type. Pointee is required to always be a function type. QualType getPointeeType() const { return PointeeType; } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getPointeeType()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { ID.AddPointer(Pointee.getAsOpaquePtr()); } static bool classof(const Type *T) { return T->getTypeClass() == BlockPointer; } static bool classof(const BlockPointerType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// ReferenceType - Base for LValueReferenceType and RValueReferenceType /// class ReferenceType : public Type, public llvm::FoldingSetNode { QualType PointeeType; protected: ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef) : Type(tc, CanonicalRef, Referencee->isDependentType()), PointeeType(Referencee) { } public: QualType getPointeeType() const { return PointeeType; } void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getPointeeType()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType Referencee) { ID.AddPointer(Referencee.getAsOpaquePtr()); } static bool classof(const Type *T) { return T->getTypeClass() == LValueReference || T->getTypeClass() == RValueReference; } static bool classof(const ReferenceType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; }; /// LValueReferenceType - C++ [dcl.ref] - Lvalue reference /// class LValueReferenceType : public ReferenceType { LValueReferenceType(QualType Referencee, QualType CanonicalRef) : ReferenceType(LValueReference, Referencee, CanonicalRef) { } friend class ASTContext; // ASTContext creates these public: virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == LValueReference; } static bool classof(const LValueReferenceType *) { return true; } protected: static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference /// class RValueReferenceType : public ReferenceType { RValueReferenceType(QualType Referencee, QualType CanonicalRef) : ReferenceType(RValueReference, Referencee, CanonicalRef) { } friend class ASTContext; // ASTContext creates these public: virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == RValueReference; } static bool classof(const RValueReferenceType *) { return true; } protected: static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// MemberPointerType - C++ 8.3.3 - Pointers to members /// class MemberPointerType : public Type, public llvm::FoldingSetNode { QualType PointeeType; /// The class of which the pointee is a member. Must ultimately be a /// RecordType, but could be a typedef or a template parameter too. const Type *Class; MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) : Type(MemberPointer, CanonicalPtr, Cls->isDependentType() || Pointee->isDependentType()), PointeeType(Pointee), Class(Cls) { } friend class ASTContext; // ASTContext creates these. public: QualType getPointeeType() const { return PointeeType; } const Type *getClass() const { return Class; } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getPointeeType(), getClass()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, const Type *Class) { ID.AddPointer(Pointee.getAsOpaquePtr()); ID.AddPointer(Class); } static bool classof(const Type *T) { return T->getTypeClass() == MemberPointer; } static bool classof(const MemberPointerType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// ArrayType - C99 6.7.5.2 - Array Declarators. /// class ArrayType : public Type, public llvm::FoldingSetNode { public: /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4]) /// an array with a static size (e.g. int X[static 4]), or an array /// with a star size (e.g. int X[*]). /// 'static' is only allowed on function parameters. enum ArraySizeModifier { Normal, Static, Star }; private: /// ElementType - The element type of the array. QualType ElementType; // NOTE: VC++ treats enums as signed, avoid using the ArraySizeModifier enum /// NOTE: These fields are packed into the bitfields space in the Type class. unsigned SizeModifier : 2; /// IndexTypeQuals - Capture qualifiers in declarations like: /// 'int X[static restrict 4]'. For function parameters only. unsigned IndexTypeQuals : 3; protected: // C++ [temp.dep.type]p1: // A type is dependent if it is... // - an array type constructed from any dependent type or whose // size is specified by a constant expression that is // value-dependent, ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, unsigned tq) : Type(tc, can, et->isDependentType() || tc == DependentSizedArray), ElementType(et), SizeModifier(sm), IndexTypeQuals(tq) {} friend class ASTContext; // ASTContext creates these. public: QualType getElementType() const { return ElementType; } ArraySizeModifier getSizeModifier() const { return ArraySizeModifier(SizeModifier); } unsigned getIndexTypeQualifier() const { return IndexTypeQuals; } static bool classof(const Type *T) { return T->getTypeClass() == ConstantArray || T->getTypeClass() == VariableArray || T->getTypeClass() == IncompleteArray || T->getTypeClass() == DependentSizedArray; } static bool classof(const ArrayType *) { return true; } }; /// ConstantArrayType - This class represents C arrays with a specified constant /// size. For example 'int A[100]' has ConstantArrayType where the element type /// is 'int' and the size is 100. class ConstantArrayType : public ArrayType { llvm::APInt Size; // Allows us to unique the type. ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, ArraySizeModifier sm, unsigned tq) : ArrayType(ConstantArray, et, can, sm, tq), Size(size) {} friend class ASTContext; // ASTContext creates these. public: const llvm::APInt &getSize() const { return Size; } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getElementType(), getSize(), getSizeModifier(), getIndexTypeQualifier()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, const llvm::APInt &ArraySize, ArraySizeModifier SizeMod, unsigned TypeQuals) { ID.AddPointer(ET.getAsOpaquePtr()); ID.AddInteger(ArraySize.getZExtValue()); ID.AddInteger(SizeMod); ID.AddInteger(TypeQuals); } static bool classof(const Type *T) { return T->getTypeClass() == ConstantArray; } static bool classof(const ConstantArrayType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// IncompleteArrayType - This class represents C arrays with an unspecified /// size. For example 'int A[]' has an IncompleteArrayType where the element /// type is 'int' and the size is unspecified. class IncompleteArrayType : public ArrayType { IncompleteArrayType(QualType et, QualType can, ArraySizeModifier sm, unsigned tq) : ArrayType(IncompleteArray, et, can, sm, tq) {} friend class ASTContext; // ASTContext creates these. public: virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == IncompleteArray; } static bool classof(const IncompleteArrayType *) { return true; } friend class StmtIteratorBase; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getElementType(), getSizeModifier(), getIndexTypeQualifier()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, ArraySizeModifier SizeMod, unsigned TypeQuals) { ID.AddPointer(ET.getAsOpaquePtr()); ID.AddInteger(SizeMod); ID.AddInteger(TypeQuals); } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// VariableArrayType - This class represents C arrays with a specified size /// which is not an integer-constant-expression. For example, 'int s[x+foo()]'. /// Since the size expression is an arbitrary expression, we store it as such. /// /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and /// should not be: two lexically equivalent variable array types could mean /// different things, for example, these variables do not have the same type /// dynamically: /// /// void foo(int x) { /// int Y[x]; /// ++x; /// int Z[x]; /// } /// class VariableArrayType : public ArrayType { /// SizeExpr - An assignment expression. VLA's are only permitted within /// a function block. Stmt *SizeExpr; VariableArrayType(QualType et, QualType can, Expr *e, ArraySizeModifier sm, unsigned tq) : ArrayType(VariableArray, et, can, sm, tq), SizeExpr((Stmt*) e) {} friend class ASTContext; // ASTContext creates these. virtual void Destroy(ASTContext& C); public: Expr *getSizeExpr() const { // We use C-style casts instead of cast<> here because we do not wish // to have a dependency of Type.h on Stmt.h/Expr.h. return (Expr*) SizeExpr; } virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == VariableArray; } static bool classof(const VariableArrayType *) { return true; } friend class StmtIteratorBase; void Profile(llvm::FoldingSetNodeID &ID) { assert(0 && "Cannnot unique VariableArrayTypes."); } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// DependentSizedArrayType - This type represents an array type in /// C++ whose size is a value-dependent expression. For example: /// @code /// template<typename T, int Size> /// class array { /// T data[Size]; /// }; /// @endcode /// For these types, we won't actually know what the array bound is /// until template instantiation occurs, at which point this will /// become either a ConstantArrayType or a VariableArrayType. class DependentSizedArrayType : public ArrayType { /// SizeExpr - An assignment expression that will instantiate to the /// size of the array. Stmt *SizeExpr; DependentSizedArrayType(QualType et, QualType can, Expr *e, ArraySizeModifier sm, unsigned tq) : ArrayType(DependentSizedArray, et, can, sm, tq), SizeExpr((Stmt*) e) {} friend class ASTContext; // ASTContext creates these. virtual void Destroy(ASTContext& C); public: Expr *getSizeExpr() const { // We use C-style casts instead of cast<> here because we do not wish // to have a dependency of Type.h on Stmt.h/Expr.h. return (Expr*) SizeExpr; } virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == DependentSizedArray; } static bool classof(const DependentSizedArrayType *) { return true; } friend class StmtIteratorBase; void Profile(llvm::FoldingSetNodeID &ID) { assert(0 && "Cannnot unique DependentSizedArrayTypes."); } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// VectorType - GCC generic vector type. This type is created using /// __attribute__((vector_size(n)), where "n" specifies the vector size in /// bytes. Since the constructor takes the number of vector elements, the /// client is responsible for converting the size into the number of elements. class VectorType : public Type, public llvm::FoldingSetNode { protected: /// ElementType - The element type of the vector. QualType ElementType; /// NumElements - The number of elements in the vector. unsigned NumElements; VectorType(QualType vecType, unsigned nElements, QualType canonType) : Type(Vector, canonType, vecType->isDependentType()), ElementType(vecType), NumElements(nElements) {} VectorType(TypeClass tc, QualType vecType, unsigned nElements, QualType canonType) : Type(tc, canonType, vecType->isDependentType()), ElementType(vecType), NumElements(nElements) {} friend class ASTContext; // ASTContext creates these. public: QualType getElementType() const { return ElementType; } unsigned getNumElements() const { return NumElements; } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getElementType(), getNumElements(), getTypeClass()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, unsigned NumElements, TypeClass TypeClass) { ID.AddPointer(ElementType.getAsOpaquePtr()); ID.AddInteger(NumElements); ID.AddInteger(TypeClass); } static bool classof(const Type *T) { return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; } static bool classof(const VectorType *) { return true; } }; /// ExtVectorType - Extended vector type. This type is created using /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This /// class enables syntactic extensions, like Vector Components for accessing /// points, colors, and textures (modeled after OpenGL Shading Language). class ExtVectorType : public VectorType { ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) : VectorType(ExtVector, vecType, nElements, canonType) {} friend class ASTContext; // ASTContext creates these. public: static int getPointAccessorIdx(char c) { switch (c) { default: return -1; case 'x': return 0; case 'y': return 1; case 'z': return 2; case 'w': return 3; } } static int getNumericAccessorIdx(char c) { switch (c) { default: return -1; case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': return 10; case 'b': return 11; case 'c': return 12; case 'd': return 13; case 'e': return 14; case 'f': return 15; } } static int getAccessorIdx(char c) { if (int idx = getPointAccessorIdx(c)+1) return idx-1; return getNumericAccessorIdx(c); } bool isAccessorWithinNumElements(char c) const { if (int idx = getAccessorIdx(c)+1) return unsigned(idx-1) < NumElements; return false; } virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == ExtVector; } static bool classof(const ExtVectorType *) { return true; } }; /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base /// class of FunctionNoProtoType and FunctionProtoType. /// class FunctionType : public Type { /// SubClassData - This field is owned by the subclass, put here to pack /// tightly with the ivars in Type. bool SubClassData : 1; /// TypeQuals - Used only by FunctionProtoType, put here to pack with the /// other bitfields. /// The qualifiers are part of FunctionProtoType because... /// /// C++ 8.3.5p4: The return type, the parameter type list and the /// cv-qualifier-seq, [...], are part of the function type. /// unsigned TypeQuals : 3; // The type returned by the function. QualType ResultType; protected: FunctionType(TypeClass tc, QualType res, bool SubclassInfo, unsigned typeQuals, QualType Canonical, bool Dependent) : Type(tc, Canonical, Dependent), SubClassData(SubclassInfo), TypeQuals(typeQuals), ResultType(res) {} bool getSubClassData() const { return SubClassData; } unsigned getTypeQuals() const { return TypeQuals; } public: QualType getResultType() const { return ResultType; } static bool classof(const Type *T) { return T->getTypeClass() == FunctionNoProto || T->getTypeClass() == FunctionProto; } static bool classof(const FunctionType *) { return true; } }; /// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has /// no information available about its arguments. class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { FunctionNoProtoType(QualType Result, QualType Canonical) : FunctionType(FunctionNoProto, Result, false, 0, Canonical, /*Dependent=*/false) {} friend class ASTContext; // ASTContext creates these. public: // No additional state past what FunctionType provides. virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, getResultType()); } static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType) { ID.AddPointer(ResultType.getAsOpaquePtr()); } static bool classof(const Type *T) { return T->getTypeClass() == FunctionNoProto; } static bool classof(const FunctionNoProtoType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// FunctionProtoType - Represents a prototype with argument type info, e.g. /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no /// arguments, not as having a single void argument. class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode { /// hasAnyDependentType - Determine whether there are any dependent /// types within the arguments passed in. static bool hasAnyDependentType(const QualType *ArgArray, unsigned numArgs) { for (unsigned Idx = 0; Idx < numArgs; ++Idx) if (ArgArray[Idx]->isDependentType()) return true; return false; } FunctionProtoType(QualType Result, const QualType *ArgArray, unsigned numArgs, bool isVariadic, unsigned typeQuals, QualType Canonical) : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical, (Result->isDependentType() || hasAnyDependentType(ArgArray, numArgs))), NumArgs(numArgs) { // Fill in the trailing argument array. QualType *ArgInfo = reinterpret_cast<QualType *>(this+1);; for (unsigned i = 0; i != numArgs; ++i) ArgInfo[i] = ArgArray[i]; } /// NumArgs - The number of arguments this function has, not counting '...'. unsigned NumArgs; /// ArgInfo - There is an variable size array after the class in memory that /// holds the argument types. friend class ASTContext; // ASTContext creates these. public: unsigned getNumArgs() const { return NumArgs; } QualType getArgType(unsigned i) const { assert(i < NumArgs && "Invalid argument number!"); return arg_type_begin()[i]; } bool isVariadic() const { return getSubClassData(); } unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); } typedef const QualType *arg_type_iterator; arg_type_iterator arg_type_begin() const { return reinterpret_cast<const QualType *>(this+1); } arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; } virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == FunctionProto; } static bool classof(const FunctionProtoType *) { return true; } void Profile(llvm::FoldingSetNodeID &ID); static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, arg_type_iterator ArgTys, unsigned NumArgs, bool isVariadic, unsigned TypeQuals); protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; class TypedefType : public Type { TypedefDecl *Decl; protected: TypedefType(TypeClass tc, TypedefDecl *D, QualType can) : Type(tc, can, can->isDependentType()), Decl(D) { assert(!isa<TypedefType>(can) && "Invalid canonical type"); } friend class ASTContext; // ASTContext creates these. public: TypedefDecl *getDecl() const { return Decl; } /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to /// potentially looking through *all* consecutive typedefs. This returns the /// sum of the type qualifiers, so if you have: /// typedef const int A; /// typedef volatile A B; /// looking through the typedefs for B will give you "const volatile A". QualType LookThroughTypedefs() const; virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } static bool classof(const TypedefType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context,llvm::Deserializer& D); friend class Type; }; /// TypeOfExprType (GCC extension). class TypeOfExprType : public Type { Expr *TOExpr; TypeOfExprType(Expr *E, QualType can); friend class ASTContext; // ASTContext creates these. public: Expr *getUnderlyingExpr() const { return TOExpr; } virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } static bool classof(const TypeOfExprType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// TypeOfType (GCC extension). class TypeOfType : public Type { QualType TOType; TypeOfType(QualType T, QualType can) : Type(TypeOf, can, T->isDependentType()), TOType(T) { assert(!isa<TypedefType>(can) && "Invalid canonical type"); } friend class ASTContext; // ASTContext creates these. public: QualType getUnderlyingType() const { return TOType; } virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } static bool classof(const TypeOfType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; class TagType : public Type { /// Stores the TagDecl associated with this type. The decl will /// point to the TagDecl that actually defines the entity (or is a /// definition in progress), if there is such a definition. The /// single-bit value will be non-zero when this tag is in the /// process of being defined. mutable llvm::PointerIntPair<TagDecl *, 1> decl; friend class ASTContext; friend class TagDecl; protected: // FIXME: We'll need the user to pass in information about whether // this type is dependent or not, because we don't have enough // information to compute it here. TagType(TypeClass TC, TagDecl *D, QualType can) : Type(TC, can, /*Dependent=*/false), decl(D, 0) {} public: TagDecl *getDecl() const { return decl.getPointer(); } /// @brief Determines whether this type is in the process of being /// defined. bool isBeingDefined() const { return decl.getInt(); } void setBeingDefined(bool Def) { decl.setInt(Def? 1 : 0); } virtual void getAsStringInternal(std::string &InnerString) const; void getAsStringInternal(std::string &InnerString, bool SuppressTagKind) const; static bool classof(const Type *T) { return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast; } static bool classof(const TagType *) { return true; } static bool classof(const RecordType *) { return true; } static bool classof(const EnumType *) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// RecordType - This is a helper class that allows the use of isa/cast/dyncast /// to detect TagType objects of structs/unions/classes. class RecordType : public TagType { protected: explicit RecordType(RecordDecl *D) : TagType(Record, reinterpret_cast<TagDecl*>(D), QualType()) { } explicit RecordType(TypeClass TC, RecordDecl *D) : TagType(TC, reinterpret_cast<TagDecl*>(D), QualType()) { } friend class ASTContext; // ASTContext creates these. public: RecordDecl *getDecl() const { return reinterpret_cast<RecordDecl*>(TagType::getDecl()); } // FIXME: This predicate is a helper to QualType/Type. It needs to // recursively check all fields for const-ness. If any field is declared // const, it needs to return false. bool hasConstFields() const { return false; } // FIXME: RecordType needs to check when it is created that all fields are in // the same address space, and return that. unsigned getAddressSpace() const { return 0; } static bool classof(const TagType *T); static bool classof(const Type *T) { return isa<TagType>(T) && classof(cast<TagType>(T)); } static bool classof(const RecordType *) { return true; } }; /// EnumType - This is a helper class that allows the use of isa/cast/dyncast /// to detect TagType objects of enums. class EnumType : public TagType { explicit EnumType(EnumDecl *D) : TagType(Enum, reinterpret_cast<TagDecl*>(D), QualType()) { } friend class ASTContext; // ASTContext creates these. public: EnumDecl *getDecl() const { return reinterpret_cast<EnumDecl*>(TagType::getDecl()); } static bool classof(const TagType *T); static bool classof(const Type *T) { return isa<TagType>(T) && classof(cast<TagType>(T)); } static bool classof(const EnumType *) { return true; } }; class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { unsigned Depth : 16; unsigned Index : 16; IdentifierInfo *Name; TemplateTypeParmType(unsigned D, unsigned I, IdentifierInfo *N, QualType Canon) : Type(TemplateTypeParm, Canon, /*Dependent=*/true), Depth(D), Index(I), Name(N) { } TemplateTypeParmType(unsigned D, unsigned I) : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true), Depth(D), Index(I), Name(0) { } friend class ASTContext; // ASTContext creates these public: unsigned getDepth() const { return Depth; } unsigned getIndex() const { return Index; } IdentifierInfo *getName() const { return Name; } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Depth, Index, Name); } static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, unsigned Index, IdentifierInfo *Name) { ID.AddInteger(Depth); ID.AddInteger(Index); ID.AddPointer(Name); } static bool classof(const Type *T) { return T->getTypeClass() == TemplateTypeParm; } static bool classof(const TemplateTypeParmType *T) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// \brief Represents the type of a template specialization as written /// in the source code. /// /// Template specialization types represent the syntactic form of a /// template-id that refers to a type, e.g., @c vector<int>. Some /// template specialization types are syntactic sugar, whose canonical /// type will point to some other type node that represents the /// instantiation or class template specialization. For example, a /// class template specialization type of @c vector<int> will refer to /// a tag type for the instantiation /// @c std::vector<int, std::allocator<int>>. /// /// Other template specialization types, for which the template name /// is dependent, may be canonical types. These types are always /// dependent. class TemplateSpecializationType : public Type, public llvm::FoldingSetNode { /// \brief The name of the template being specialized. TemplateName Template; /// \brief - The number of template arguments named in this class /// template specialization. unsigned NumArgs; TemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon); virtual void Destroy(ASTContext& C); friend class ASTContext; // ASTContext creates these public: /// \brief Determine whether any of the given template arguments are /// dependent. static bool anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs); /// \brief Print a template argument list, including the '<' and '>' /// enclosing the template arguments. static std::string PrintTemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs); typedef const TemplateArgument * iterator; iterator begin() const { return getArgs(); } iterator end() const; /// \brief Retrieve the name of the template that we are specializing. TemplateName getTemplateName() const { return Template; } /// \brief Retrieve the template arguments. const TemplateArgument *getArgs() const { return reinterpret_cast<const TemplateArgument *>(this + 1); } /// \brief Retrieve the number of template arguments. unsigned getNumArgs() const { return NumArgs; } /// \brief Retrieve a specific template argument as a type. /// \precondition @c isArgType(Arg) const TemplateArgument &getArg(unsigned Idx) const; virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Template, getArgs(), NumArgs); } static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, const TemplateArgument *Args, unsigned NumArgs); static bool classof(const Type *T) { return T->getTypeClass() == TemplateSpecialization; } static bool classof(const TemplateSpecializationType *T) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// \brief Represents a type that was referred to via a qualified /// name, e.g., N::M::type. /// /// This type is used to keep track of a type name as written in the /// source code, including any nested-name-specifiers. The type itself /// is always "sugar", used to express what was written in the source /// code but containing no additional semantic information. class QualifiedNameType : public Type, public llvm::FoldingSetNode { /// \brief The nested name specifier containing the qualifier. NestedNameSpecifier *NNS; /// \brief The type that this qualified name refers to. QualType NamedType; QualifiedNameType(NestedNameSpecifier *NNS, QualType NamedType, QualType CanonType) : Type(QualifiedName, CanonType, NamedType->isDependentType()), NNS(NNS), NamedType(NamedType) { } friend class ASTContext; // ASTContext creates these public: /// \brief Retrieve the qualification on this type. NestedNameSpecifier *getQualifier() const { return NNS; } /// \brief Retrieve the type named by the qualified-id. QualType getNamedType() const { return NamedType; } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, NNS, NamedType); } static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS, QualType NamedType) { ID.AddPointer(NNS); NamedType.Profile(ID); } static bool classof(const Type *T) { return T->getTypeClass() == QualifiedName; } static bool classof(const QualifiedNameType *T) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// \brief Represents a 'typename' specifier that names a type within /// a dependent type, e.g., "typename T::type". /// /// TypenameType has a very similar structure to QualifiedNameType, /// which also involves a nested-name-specifier following by a type, /// and (FIXME!) both can even be prefixed by the 'typename' /// keyword. However, the two types serve very different roles: /// QualifiedNameType is a non-semantic type that serves only as sugar /// to show how a particular type was written in the source /// code. TypenameType, on the other hand, only occurs when the /// nested-name-specifier is dependent, such that we cannot resolve /// the actual type until after instantiation. class TypenameType : public Type, public llvm::FoldingSetNode { /// \brief The nested name specifier containing the qualifier. NestedNameSpecifier *NNS; typedef llvm::PointerUnion<const IdentifierInfo *, const TemplateSpecializationType *> NameType; /// \brief The type that this typename specifier refers to. NameType Name; TypenameType(NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType CanonType) : Type(Typename, CanonType, true), NNS(NNS), Name(Name) { assert(NNS->isDependent() && "TypenameType requires a dependent nested-name-specifier"); } TypenameType(NestedNameSpecifier *NNS, const TemplateSpecializationType *Ty, QualType CanonType) : Type(Typename, CanonType, true), NNS(NNS), Name(Ty) { assert(NNS->isDependent() && "TypenameType requires a dependent nested-name-specifier"); } friend class ASTContext; // ASTContext creates these public: /// \brief Retrieve the qualification on this type. NestedNameSpecifier *getQualifier() const { return NNS; } /// \brief Retrieve the type named by the typename specifier as an /// identifier. /// /// This routine will return a non-NULL identifier pointer when the /// form of the original typename was terminated by an identifier, /// e.g., "typename T::type". const IdentifierInfo *getIdentifier() const { return Name.dyn_cast<const IdentifierInfo *>(); } /// \brief Retrieve the type named by the typename specifier as a /// type specialization. const TemplateSpecializationType *getTemplateId() const { return Name.dyn_cast<const TemplateSpecializationType *>(); } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, NNS, Name); } static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS, NameType Name) { ID.AddPointer(NNS); ID.AddPointer(Name.getOpaqueValue()); } static bool classof(const Type *T) { return T->getTypeClass() == Typename; } static bool classof(const TypenameType *T) { return true; } protected: virtual void EmitImpl(llvm::Serializer& S) const; static Type* CreateImpl(ASTContext& Context, llvm::Deserializer& D); friend class Type; }; /// ObjCInterfaceType - Interfaces are the core concept in Objective-C for /// object oriented design. They basically correspond to C++ classes. There /// are two kinds of interface types, normal interfaces like "NSString" and /// qualified interfaces, which are qualified with a protocol list like /// "NSString<NSCopyable, NSAmazing>". Qualified interface types are instances /// of ObjCQualifiedInterfaceType, which is a subclass of ObjCInterfaceType. class ObjCInterfaceType : public Type { ObjCInterfaceDecl *Decl; protected: ObjCInterfaceType(TypeClass tc, ObjCInterfaceDecl *D) : Type(tc, QualType(), /*Dependent=*/false), Decl(D) { } friend class ASTContext; // ASTContext creates these. public: ObjCInterfaceDecl *getDecl() const { return Decl; } /// qual_iterator and friends: this provides access to the (potentially empty) /// list of protocols qualifying this interface. If this is an instance of /// ObjCQualifiedInterfaceType it returns the list, otherwise it returns an /// empty list if there are no qualifying protocols. typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator; inline qual_iterator qual_begin() const; inline qual_iterator qual_end() const; bool qual_empty() const { return getTypeClass() != ObjCQualifiedInterface; } /// getNumProtocols - Return the number of qualifying protocols in this /// interface type, or 0 if there are none. inline unsigned getNumProtocols() const; /// getProtocol - Return the specified qualifying protocol. inline ObjCProtocolDecl *getProtocol(unsigned i) const; virtual void getAsStringInternal(std::string &InnerString) const; static bool classof(const Type *T) { return T->getTypeClass() == ObjCInterface || T->getTypeClass() == ObjCQualifiedInterface; } static bool classof(const ObjCInterfaceType *) { return true; } }; /// ObjCQualifiedInterfaceType - This class represents interface types /// conforming to a list of protocols, such as INTF<Proto1, Proto2, Proto1>. /// /// Duplicate protocols are removed and protocol list is canonicalized to be in /// alphabetical order. class ObjCQualifiedInterfaceType : public ObjCInterfaceType, public llvm::FoldingSetNode { // List of protocols for this protocol conforming object type // List is sorted on protocol name. No protocol is enterred more than once. llvm::SmallVector<ObjCProtocolDecl*, 4> Protocols; ObjCQualifiedInterfaceType(ObjCInterfaceDecl *D, ObjCProtocolDecl **Protos, unsigned NumP) : ObjCInterfaceType(ObjCQualifiedInterface, D), Protocols(Protos, Protos+NumP) { } friend class ASTContext; // ASTContext creates these. public: ObjCProtocolDecl *getProtocol(unsigned i) const { return Protocols[i]; } unsigned getNumProtocols() const { return Protocols.size(); } qual_iterator qual_begin() const { return Protocols.begin(); } qual_iterator qual_end() const { return Protocols.end(); } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID); static void Profile(llvm::FoldingSetNodeID &ID, const ObjCInterfaceDecl *Decl, ObjCProtocolDecl **protocols, unsigned NumProtocols); static bool classof(const Type *T) { return T->getTypeClass() == ObjCQualifiedInterface; } static bool classof(const ObjCQualifiedInterfaceType *) { return true; } }; inline ObjCInterfaceType::qual_iterator ObjCInterfaceType::qual_begin() const { if (const ObjCQualifiedInterfaceType *QIT = dyn_cast<ObjCQualifiedInterfaceType>(this)) return QIT->qual_begin(); return 0; } inline ObjCInterfaceType::qual_iterator ObjCInterfaceType::qual_end() const { if (const ObjCQualifiedInterfaceType *QIT = dyn_cast<ObjCQualifiedInterfaceType>(this)) return QIT->qual_end(); return 0; } /// getNumProtocols - Return the number of qualifying protocols in this /// interface type, or 0 if there are none. inline unsigned ObjCInterfaceType::getNumProtocols() const { if (const ObjCQualifiedInterfaceType *QIT = dyn_cast<ObjCQualifiedInterfaceType>(this)) return QIT->getNumProtocols(); return 0; } /// getProtocol - Return the specified qualifying protocol. inline ObjCProtocolDecl *ObjCInterfaceType::getProtocol(unsigned i) const { return cast<ObjCQualifiedInterfaceType>(this)->getProtocol(i); } /// ObjCQualifiedIdType - to represent id<protocol-list>. /// /// Duplicate protocols are removed and protocol list is canonicalized to be in /// alphabetical order. class ObjCQualifiedIdType : public Type, public llvm::FoldingSetNode { // List of protocols for this protocol conforming 'id' type // List is sorted on protocol name. No protocol is enterred more than once. llvm::SmallVector<ObjCProtocolDecl*, 8> Protocols; ObjCQualifiedIdType(ObjCProtocolDecl **Protos, unsigned NumP) : Type(ObjCQualifiedId, QualType()/*these are always canonical*/, /*Dependent=*/false), Protocols(Protos, Protos+NumP) { } friend class ASTContext; // ASTContext creates these. public: ObjCProtocolDecl *getProtocols(unsigned i) const { return Protocols[i]; } unsigned getNumProtocols() const { return Protocols.size(); } ObjCProtocolDecl **getReferencedProtocols() { return &Protocols[0]; } typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator; qual_iterator qual_begin() const { return Protocols.begin(); } qual_iterator qual_end() const { return Protocols.end(); } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID); static void Profile(llvm::FoldingSetNodeID &ID, ObjCProtocolDecl **protocols, unsigned NumProtocols); static bool classof(const Type *T) { return T->getTypeClass() == ObjCQualifiedId; } static bool classof(const ObjCQualifiedIdType *) { return true; } }; /// ObjCQualifiedClassType - to represent Class<protocol-list>. /// /// Duplicate protocols are removed and protocol list is canonicalized to be in /// alphabetical order. class ObjCQualifiedClassType : public Type, public llvm::FoldingSetNode { // List of protocols for this protocol conforming 'id' type // List is sorted on protocol name. No protocol is enterred more than once. llvm::SmallVector<ObjCProtocolDecl*, 8> Protocols; ObjCQualifiedClassType(ObjCProtocolDecl **Protos, unsigned NumP) : Type(ObjCQualifiedClass, QualType()/*these are always canonical*/, /*Dependent=*/false), Protocols(Protos, Protos+NumP) { } friend class ASTContext; // ASTContext creates these. public: ObjCProtocolDecl *getProtocols(unsigned i) const { return Protocols[i]; } unsigned getNumProtocols() const { return Protocols.size(); } ObjCProtocolDecl **getReferencedProtocols() { return &Protocols[0]; } typedef llvm::SmallVector<ObjCProtocolDecl*, 8>::const_iterator qual_iterator; qual_iterator qual_begin() const { return Protocols.begin(); } qual_iterator qual_end() const { return Protocols.end(); } virtual void getAsStringInternal(std::string &InnerString) const; void Profile(llvm::FoldingSetNodeID &ID); static void Profile(llvm::FoldingSetNodeID &ID, ObjCProtocolDecl **protocols, unsigned NumProtocols); static bool classof(const Type *T) { return T->getTypeClass() == ObjCQualifiedClass; } static bool classof(const ObjCQualifiedClassType *) { return true; } }; // Inline function definitions. /// getUnqualifiedType - Return the type without any qualifiers. inline QualType QualType::getUnqualifiedType() const { Type *TP = getTypePtr(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(TP)) TP = EXTQT->getBaseType(); return QualType(TP, 0); } /// getAddressSpace - Return the address space of this type. inline unsigned QualType::getAddressSpace() const { QualType CT = getTypePtr()->getCanonicalTypeInternal(); if (const ArrayType *AT = dyn_cast<ArrayType>(CT)) return AT->getElementType().getAddressSpace(); if (const RecordType *RT = dyn_cast<RecordType>(CT)) return RT->getAddressSpace(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CT)) return EXTQT->getAddressSpace(); return 0; } /// getObjCGCAttr - Return the gc attribute of this type. inline QualType::GCAttrTypes QualType::getObjCGCAttr() const { QualType CT = getTypePtr()->getCanonicalTypeInternal(); if (const ArrayType *AT = dyn_cast<ArrayType>(CT)) return AT->getElementType().getObjCGCAttr(); if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CT)) return EXTQT->getObjCGCAttr(); if (const PointerType *PT = CT->getAsPointerType()) return PT->getPointeeType().getObjCGCAttr(); return GCNone; } /// isMoreQualifiedThan - Determine whether this type is more /// qualified than the Other type. For example, "const volatile int" /// is more qualified than "const int", "volatile int", and /// "int". However, it is not more qualified than "const volatile /// int". inline bool QualType::isMoreQualifiedThan(QualType Other) const { unsigned MyQuals = this->getCVRQualifiers(); unsigned OtherQuals = Other.getCVRQualifiers(); if (getAddressSpace() != Other.getAddressSpace()) return false; return MyQuals != OtherQuals && (MyQuals | OtherQuals) == MyQuals; } /// isAtLeastAsQualifiedAs - Determine whether this type is at last /// as qualified as the Other type. For example, "const volatile /// int" is at least as qualified as "const int", "volatile int", /// "int", and "const volatile int". inline bool QualType::isAtLeastAsQualifiedAs(QualType Other) const { unsigned MyQuals = this->getCVRQualifiers(); unsigned OtherQuals = Other.getCVRQualifiers(); if (getAddressSpace() != Other.getAddressSpace()) return false; return (MyQuals | OtherQuals) == MyQuals; } /// getNonReferenceType - If Type is a reference type (e.g., const /// int&), returns the type that the reference refers to ("const /// int"). Otherwise, returns the type itself. This routine is used /// throughout Sema to implement C++ 5p6: /// /// If an expression initially has the type "reference to T" (8.3.2, /// 8.5.3), the type is adjusted to "T" prior to any further /// analysis, the expression designates the object or function /// denoted by the reference, and the expression is an lvalue. inline QualType QualType::getNonReferenceType() const { if (const ReferenceType *RefType = (*this)->getAsReferenceType()) return RefType->getPointeeType(); else return *this; } inline const TypedefType* Type::getAsTypedefType() const { return dyn_cast<TypedefType>(this); } inline const ObjCInterfaceType *Type::getAsPointerToObjCInterfaceType() const { if (const PointerType *PT = getAsPointerType()) return PT->getPointeeType()->getAsObjCInterfaceType(); return 0; } // NOTE: All of these methods use "getUnqualifiedType" to strip off address // space qualifiers if present. inline bool Type::isFunctionType() const { return isa<FunctionType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isPointerType() const { return isa<PointerType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isBlockPointerType() const { return isa<BlockPointerType>(CanonicalType); } inline bool Type::isReferenceType() const { return isa<ReferenceType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isLValueReferenceType() const { return isa<LValueReferenceType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isRValueReferenceType() const { return isa<RValueReferenceType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isFunctionPointerType() const { if (const PointerType* T = getAsPointerType()) return T->getPointeeType()->isFunctionType(); else return false; } inline bool Type::isMemberPointerType() const { return isa<MemberPointerType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isMemberFunctionPointerType() const { if (const MemberPointerType* T = getAsMemberPointerType()) return T->getPointeeType()->isFunctionType(); else return false; } inline bool Type::isArrayType() const { return isa<ArrayType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isConstantArrayType() const { return isa<ConstantArrayType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isIncompleteArrayType() const { return isa<IncompleteArrayType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isVariableArrayType() const { return isa<VariableArrayType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isDependentSizedArrayType() const { return isa<DependentSizedArrayType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isRecordType() const { return isa<RecordType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isAnyComplexType() const { return isa<ComplexType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isVectorType() const { return isa<VectorType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isExtVectorType() const { return isa<ExtVectorType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isObjCInterfaceType() const { return isa<ObjCInterfaceType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isObjCQualifiedInterfaceType() const { return isa<ObjCQualifiedInterfaceType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isObjCQualifiedIdType() const { return isa<ObjCQualifiedIdType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isTemplateTypeParmType() const { return isa<TemplateTypeParmType>(CanonicalType.getUnqualifiedType()); } inline bool Type::isSpecificBuiltinType(unsigned K) const { if (const BuiltinType *BT = getAsBuiltinType()) if (BT->getKind() == (BuiltinType::Kind) K) return true; return false; } /// \brief Determines whether this is a type for which one can define /// an overloaded operator. inline bool Type::isOverloadableType() const { return isDependentType() || isRecordType() || isEnumeralType(); } inline bool Type::hasPointerRepresentation() const { return (isPointerType() || isReferenceType() || isBlockPointerType() || isObjCInterfaceType() || isObjCQualifiedIdType() || isObjCQualifiedInterfaceType()); } inline bool Type::hasObjCPointerRepresentation() const { return (isObjCInterfaceType() || isObjCQualifiedIdType() || isObjCQualifiedInterfaceType()); } /// Insertion operator for diagnostics. This allows sending QualType's into a /// diagnostic with <<. inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, QualType T) { DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), Diagnostic::ak_qualtype); return DB; } } // end namespace clang #endif <file_sep>/test/SemaCXX/dependent-types.cpp // RUN: clang-cc -fsyntax-only -pedantic -verify %s template<typename T, int Size> void f() { T x1; T* x2; T& x3; // expected-error{{declaration of reference variable 'x3' requires an initializer}} T x4[]; // expected-error{{variable has incomplete type 'T []'}} T x5[Size]; int x6[Size]; } <file_sep>/lib/Analysis/ExplodedGraph.cpp //=-- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -*- C++ -*------=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the template classes ExplodedNode and ExplodedGraph, // which represent a path-sensitive, intra-procedural "exploded graph." // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/ExplodedGraph.h" #include "clang/AST/Stmt.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include <vector> using namespace clang; //===----------------------------------------------------------------------===// // Node auditing. //===----------------------------------------------------------------------===// // An out of line virtual method to provide a home for the class vtable. ExplodedNodeImpl::Auditor::~Auditor() {} #ifndef NDEBUG static ExplodedNodeImpl::Auditor* NodeAuditor = 0; #endif void ExplodedNodeImpl::SetAuditor(ExplodedNodeImpl::Auditor* A) { #ifndef NDEBUG NodeAuditor = A; #endif } //===----------------------------------------------------------------------===// // ExplodedNodeImpl. //===----------------------------------------------------------------------===// static inline std::vector<ExplodedNodeImpl*>& getVector(void* P) { return *reinterpret_cast<std::vector<ExplodedNodeImpl*>*>(P); } void ExplodedNodeImpl::addPredecessor(ExplodedNodeImpl* V) { assert (!V->isSink()); Preds.addNode(V); V->Succs.addNode(this); #ifndef NDEBUG if (NodeAuditor) NodeAuditor->AddEdge(V, this); #endif } void ExplodedNodeImpl::NodeGroup::addNode(ExplodedNodeImpl* N) { assert ((reinterpret_cast<uintptr_t>(N) & Mask) == 0x0); assert (!getFlag()); if (getKind() == Size1) { if (ExplodedNodeImpl* NOld = getNode()) { std::vector<ExplodedNodeImpl*>* V = new std::vector<ExplodedNodeImpl*>(); assert ((reinterpret_cast<uintptr_t>(V) & Mask) == 0x0); V->push_back(NOld); V->push_back(N); P = reinterpret_cast<uintptr_t>(V) | SizeOther; assert (getPtr() == (void*) V); assert (getKind() == SizeOther); } else { P = reinterpret_cast<uintptr_t>(N); assert (getKind() == Size1); } } else { assert (getKind() == SizeOther); getVector(getPtr()).push_back(N); } } unsigned ExplodedNodeImpl::NodeGroup::size() const { if (getFlag()) return 0; if (getKind() == Size1) return getNode() ? 1 : 0; else return getVector(getPtr()).size(); } ExplodedNodeImpl** ExplodedNodeImpl::NodeGroup::begin() const { if (getFlag()) return NULL; if (getKind() == Size1) return (ExplodedNodeImpl**) (getPtr() ? &P : NULL); else return const_cast<ExplodedNodeImpl**>(&*(getVector(getPtr()).begin())); } ExplodedNodeImpl** ExplodedNodeImpl::NodeGroup::end() const { if (getFlag()) return NULL; if (getKind() == Size1) return (ExplodedNodeImpl**) (getPtr() ? &P+1 : NULL); else { // Dereferencing end() is undefined behaviour. The vector is not empty, so // we can dereference the last elem and then add 1 to the result. return const_cast<ExplodedNodeImpl**>(&getVector(getPtr()).back()) + 1; } } ExplodedNodeImpl::NodeGroup::~NodeGroup() { if (getKind() == SizeOther) delete &getVector(getPtr()); } ExplodedGraphImpl* ExplodedGraphImpl::Trim(const ExplodedNodeImpl* const* BeginSources, const ExplodedNodeImpl* const* EndSources, InterExplodedGraphMapImpl* M, llvm::DenseMap<const void*, const void*> *InverseMap) const { typedef llvm::DenseSet<const ExplodedNodeImpl*> Pass1Ty; Pass1Ty Pass1; typedef llvm::DenseMap<const ExplodedNodeImpl*, ExplodedNodeImpl*> Pass2Ty; Pass2Ty& Pass2 = M->M; llvm::SmallVector<const ExplodedNodeImpl*, 10> WL1, WL2; // ===- Pass 1 (reverse DFS) -=== for (const ExplodedNodeImpl* const* I = BeginSources; I != EndSources; ++I) { assert(*I); WL1.push_back(*I); } // Process the first worklist until it is empty. Because it is a std::list // it acts like a FIFO queue. while (!WL1.empty()) { const ExplodedNodeImpl *N = WL1.back(); WL1.pop_back(); // Have we already visited this node? If so, continue to the next one. if (Pass1.count(N)) continue; // Otherwise, mark this node as visited. Pass1.insert(N); // If this is a root enqueue it to the second worklist. if (N->Preds.empty()) { WL2.push_back(N); continue; } // Visit our predecessors and enqueue them. for (ExplodedNodeImpl** I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) WL1.push_back(*I); } // We didn't hit a root? Return with a null pointer for the new graph. if (WL2.empty()) return 0; // Create an empty graph. ExplodedGraphImpl* G = MakeEmptyGraph(); // ===- Pass 2 (forward DFS to construct the new graph) -=== while (!WL2.empty()) { const ExplodedNodeImpl* N = WL2.back(); WL2.pop_back(); // Skip this node if we have already processed it. if (Pass2.find(N) != Pass2.end()) continue; // Create the corresponding node in the new graph and record the mapping // from the old node to the new node. ExplodedNodeImpl* NewN = G->getNodeImpl(N->getLocation(), N->State, NULL); Pass2[N] = NewN; // Also record the reverse mapping from the new node to the old node. if (InverseMap) (*InverseMap)[NewN] = N; // If this node is a root, designate it as such in the graph. if (N->Preds.empty()) G->addRoot(NewN); // In the case that some of the intended predecessors of NewN have already // been created, we should hook them up as predecessors. // Walk through the predecessors of 'N' and hook up their corresponding // nodes in the new graph (if any) to the freshly created node. for (ExplodedNodeImpl **I=N->Preds.begin(), **E=N->Preds.end(); I!=E; ++I) { Pass2Ty::iterator PI = Pass2.find(*I); if (PI == Pass2.end()) continue; NewN->addPredecessor(PI->second); } // In the case that some of the intended successors of NewN have already // been created, we should hook them up as successors. Otherwise, enqueue // the new nodes from the original graph that should have nodes created // in the new graph. for (ExplodedNodeImpl **I=N->Succs.begin(), **E=N->Succs.end(); I!=E; ++I) { Pass2Ty::iterator PI = Pass2.find(*I); if (PI != Pass2.end()) { PI->second->addPredecessor(NewN); continue; } // Enqueue nodes to the worklist that were marked during pass 1. if (Pass1.count(*I)) WL2.push_back(*I); } // Finally, explictly mark all nodes without any successors as sinks. if (N->isSink()) NewN->markAsSink(); } return G; } ExplodedNodeImpl* InterExplodedGraphMapImpl::getMappedImplNode(const ExplodedNodeImpl* N) const { llvm::DenseMap<const ExplodedNodeImpl*, ExplodedNodeImpl*>::iterator I = M.find(N); return I == M.end() ? 0 : I->second; } InterExplodedGraphMapImpl::InterExplodedGraphMapImpl() {} <file_sep>/include/clang/Analysis/Support/BlkExprDeclBitVector.h // BlkExprDeclBitVector.h - Dataflow types for Bitvector Analysis --*- C++ --*-- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides definition of dataflow types used by analyses such // as LiveVariables and UninitializedValues. The underlying dataflow values // are implemented as bitvectors, but the definitions in this file include // the necessary boilerplate to use with our dataflow framework. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STMTDECLBVDVAL_H #define LLVM_CLANG_STMTDECLBVDVAL_H #include "clang/AST/CFG.h" #include "clang/AST/Decl.h" // for Decl* -> NamedDecl* conversion #include "llvm/ADT/BitVector.h" #include "llvm/ADT/DenseMap.h" namespace clang { class Stmt; class ASTContext; struct DeclBitVector_Types { class Idx { unsigned I; public: explicit Idx(unsigned i) : I(i) {} Idx() : I(~0U) {} bool isValid() const { return I != ~0U; } operator unsigned() const { assert (isValid()); return I; } }; //===--------------------------------------------------------------------===// // AnalysisDataTy - Whole-function meta data. //===--------------------------------------------------------------------===// class AnalysisDataTy { public: typedef llvm::DenseMap<const NamedDecl*, unsigned > DMapTy; typedef DMapTy::const_iterator decl_iterator; protected: DMapTy DMap; unsigned NDecls; public: AnalysisDataTy() : NDecls(0) {} virtual ~AnalysisDataTy() {} bool isTracked(const NamedDecl* SD) { return DMap.find(SD) != DMap.end(); } Idx getIdx(const NamedDecl* SD) const { DMapTy::const_iterator I = DMap.find(SD); return I == DMap.end() ? Idx() : Idx(I->second); } unsigned getNumDecls() const { return NDecls; } void Register(const NamedDecl* SD) { if (!isTracked(SD)) DMap[SD] = NDecls++; } decl_iterator begin_decl() const { return DMap.begin(); } decl_iterator end_decl() const { return DMap.end(); } }; //===--------------------------------------------------------------------===// // ValTy - Dataflow value. //===--------------------------------------------------------------------===// class ValTy { llvm::BitVector DeclBV; public: void resetDeclValues(AnalysisDataTy& AD) { DeclBV.resize(AD.getNumDecls()); DeclBV.reset(); } void setDeclValues(AnalysisDataTy& AD) { DeclBV.resize(AD.getNumDecls()); DeclBV.set(); } void resetValues(AnalysisDataTy& AD) { resetDeclValues(AD); } bool operator==(const ValTy& RHS) const { assert (sizesEqual(RHS)); return DeclBV == RHS.DeclBV; } void copyValues(const ValTy& RHS) { DeclBV = RHS.DeclBV; } llvm::BitVector::reference getBit(unsigned i) { return DeclBV[i]; } bool getBit(unsigned i) const { return DeclBV[i]; } llvm::BitVector::reference operator()(const NamedDecl* ND, const AnalysisDataTy& AD) { return getBit(AD.getIdx(ND)); } bool operator()(const NamedDecl* ND, const AnalysisDataTy& AD) const { return getBit(AD.getIdx(ND)); } llvm::BitVector::reference getDeclBit(unsigned i) { return DeclBV[i]; } const llvm::BitVector::reference getDeclBit(unsigned i) const { return const_cast<llvm::BitVector&>(DeclBV)[i]; } ValTy& operator|=(const ValTy& RHS) { assert (sizesEqual(RHS)); DeclBV |= RHS.DeclBV; return *this; } ValTy& operator&=(const ValTy& RHS) { assert (sizesEqual(RHS)); DeclBV &= RHS.DeclBV; return *this; } ValTy& OrDeclBits(const ValTy& RHS) { return operator|=(RHS); } ValTy& AndDeclBits(const ValTy& RHS) { return operator&=(RHS); } bool sizesEqual(const ValTy& RHS) const { return DeclBV.size() == RHS.DeclBV.size(); } }; //===--------------------------------------------------------------------===// // Some useful merge operations. //===--------------------------------------------------------------------===// struct Union { void operator()(ValTy& Dst, ValTy& Src) { Dst |= Src; } }; struct Intersect { void operator()(ValTy& Dst, ValTy& Src) { Dst &= Src; } }; }; struct StmtDeclBitVector_Types { //===--------------------------------------------------------------------===// // AnalysisDataTy - Whole-function meta data. //===--------------------------------------------------------------------===// class AnalysisDataTy : public DeclBitVector_Types::AnalysisDataTy { ASTContext* ctx; CFG* cfg; public: AnalysisDataTy() : ctx(0), cfg(0) {} virtual ~AnalysisDataTy() {} void setContext(ASTContext& c) { ctx = &c; } ASTContext& getContext() { assert(ctx && "ASTContext should not be NULL."); return *ctx; } void setCFG(CFG& c) { cfg = &c; } CFG& getCFG() { assert(cfg && "CFG should not be NULL."); return *cfg; } bool isTracked(const Stmt* S) { return cfg->isBlkExpr(S); } using DeclBitVector_Types::AnalysisDataTy::isTracked; unsigned getIdx(const Stmt* S) const { CFG::BlkExprNumTy I = cfg->getBlkExprNum(S); assert(I && "Stmtession not tracked for bitvector."); return I; } using DeclBitVector_Types::AnalysisDataTy::getIdx; unsigned getNumBlkExprs() const { return cfg->getNumBlkExprs(); } }; //===--------------------------------------------------------------------===// // ValTy - Dataflow value. //===--------------------------------------------------------------------===// class ValTy : public DeclBitVector_Types::ValTy { llvm::BitVector BlkExprBV; typedef DeclBitVector_Types::ValTy ParentTy; static inline ParentTy& ParentRef(ValTy& X) { return static_cast<ParentTy&>(X); } static inline const ParentTy& ParentRef(const ValTy& X) { return static_cast<const ParentTy&>(X); } public: void resetBlkExprValues(AnalysisDataTy& AD) { BlkExprBV.resize(AD.getNumBlkExprs()); BlkExprBV.reset(); } void setBlkExprValues(AnalysisDataTy& AD) { BlkExprBV.resize(AD.getNumBlkExprs()); BlkExprBV.set(); } void resetValues(AnalysisDataTy& AD) { resetDeclValues(AD); resetBlkExprValues(AD); } void setValues(AnalysisDataTy& AD) { setDeclValues(AD); setBlkExprValues(AD); } bool operator==(const ValTy& RHS) const { return ParentRef(*this) == ParentRef(RHS) && BlkExprBV == RHS.BlkExprBV; } void copyValues(const ValTy& RHS) { ParentRef(*this).copyValues(ParentRef(RHS)); BlkExprBV = RHS.BlkExprBV; } llvm::BitVector::reference operator()(const Stmt* S, const AnalysisDataTy& AD) { return BlkExprBV[AD.getIdx(S)]; } const llvm::BitVector::reference operator()(const Stmt* S, const AnalysisDataTy& AD) const { return const_cast<ValTy&>(*this)(S,AD); } using DeclBitVector_Types::ValTy::operator(); llvm::BitVector::reference getStmtBit(unsigned i) { return BlkExprBV[i]; } const llvm::BitVector::reference getStmtBit(unsigned i) const { return const_cast<llvm::BitVector&>(BlkExprBV)[i]; } ValTy& OrBlkExprBits(const ValTy& RHS) { BlkExprBV |= RHS.BlkExprBV; return *this; } ValTy& AndBlkExprBits(const ValTy& RHS) { BlkExprBV &= RHS.BlkExprBV; return *this; } ValTy& operator|=(const ValTy& RHS) { assert (sizesEqual(RHS)); ParentRef(*this) |= ParentRef(RHS); BlkExprBV |= RHS.BlkExprBV; return *this; } ValTy& operator&=(const ValTy& RHS) { assert (sizesEqual(RHS)); ParentRef(*this) &= ParentRef(RHS); BlkExprBV &= RHS.BlkExprBV; return *this; } bool sizesEqual(const ValTy& RHS) const { return ParentRef(*this).sizesEqual(ParentRef(RHS)) && BlkExprBV.size() == RHS.BlkExprBV.size(); } }; //===--------------------------------------------------------------------===// // Some useful merge operations. //===--------------------------------------------------------------------===// struct Union { void operator()(ValTy& Dst, ValTy& Src) { Dst |= Src; } }; struct Intersect { void operator()(ValTy& Dst, ValTy& Src) { Dst &= Src; } }; }; } // end namespace clang #endif <file_sep>/test/Analysis/no-exit-cfg.c // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify %s // This is a test case for the issue reported in PR 2819: // http://llvm.org/bugs/show_bug.cgi?id=2819 // The flow-sensitive dataflow solver should work even when no block in // the CFG reaches the exit block. int g(int x); void h(int x); int f(int x) { out_err: if (g(x)) { h(x); } goto out_err; } <file_sep>/tools/ccc/ccclib/Driver.py import os import platform import subprocess import sys import tempfile from pprint import pprint ### import Arguments import Jobs import HostInfo import Phases import Tools import Types import Util # FIXME: Clean up naming of options and arguments. Decide whether to # rename Option and be consistent about use of Option/Arg. #### class Driver(object): def __init__(self, driverName, driverDir): self.driverName = driverName self.driverDir = driverDir self.hostInfo = None self.parser = Arguments.OptionParser() self.cccHostBits = self.cccHostMachine = None self.cccHostSystem = self.cccHostRelease = None self.cccCXX = False self.cccEcho = False self.cccNoClang = self.cccNoClangCXX = self.cccNoClangPreprocessor = False self.cccClangArchs = None # Certain options suppress the 'no input files' warning. self.suppressMissingInputWarning = False # Temporary files used in compilation, removed on exit. self.tempFiles = [] # Result files produced by compilation, removed on error. self.resultFiles = [] # Host queries which can be forcibly over-riden by the user for # testing purposes. # # FIXME: We should make sure these are drawn from a fixed set so # that nothing downstream ever plays a guessing game. def getHostBits(self): if self.cccHostBits: return self.cccHostBits return platform.architecture()[0].replace('bit','') def getHostMachine(self): if self.cccHostMachine: return self.cccHostMachine machine = platform.machine() # Normalize names. if machine == 'Power Macintosh': return 'ppc' if machine == 'x86_64': return 'i386' return machine def getHostSystemName(self): if self.cccHostSystem: return self.cccHostSystem return platform.system().lower() def getHostReleaseName(self): if self.cccHostRelease: return self.cccHostRelease return platform.release() def getenvBool(self, name): var = os.getenv(name) if not var: return False try: return bool(int(var)) except: return False ### def getFilePath(self, name, toolChain=None): tc = toolChain or self.toolChain for p in tc.filePathPrefixes: path = os.path.join(p, name) if os.path.exists(path): return path return name def getProgramPath(self, name, toolChain=None): tc = toolChain or self.toolChain for p in tc.programPathPrefixes: path = os.path.join(p, name) if os.path.exists(path): return path return name ### def run(self, argv): # FIXME: Things to support from environment: GCC_EXEC_PREFIX, # COMPILER_PATH, LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, # QA_OVERRIDE_GCC3_OPTIONS, ...? # FIXME: -V and -b processing # Handle some special -ccc- options used for testing which are # only allowed at the beginning of the command line. cccPrintOptions = False cccPrintPhases = False # FIXME: How to handle override of host? ccc specific options? # Abuse -b? arg = os.getenv('CCC_ADD_ARGS') if arg: args = filter(None, map(str.strip, arg.split(','))) argv = args + argv while argv and argv[0].startswith('-ccc-'): fullOpt,argv = argv[0],argv[1:] opt = fullOpt[5:] if opt == 'print-options': cccPrintOptions = True elif opt == 'print-phases': cccPrintPhases = True elif opt == 'cxx': self.cccCXX = True elif opt == 'echo': self.cccEcho = True elif opt == 'no-clang': self.cccNoClang = True elif opt == 'no-clang-cxx': self.cccNoClangCXX = True elif opt == 'no-clang-cpp': self.cccNoClangPreprocessor = True elif opt == 'clang-archs': self.cccClangArchs,argv = argv[0].split(','),argv[1:] elif opt == 'host-bits': self.cccHostBits,argv = argv[0],argv[1:] elif opt == 'host-machine': self.cccHostMachine,argv = argv[0],argv[1:] elif opt == 'host-system': self.cccHostSystem,argv = argv[0],argv[1:] elif opt == 'host-release': self.cccHostRelease,argv = argv[0],argv[1:] elif opt == 'host-triple': # This is a complete hack, but only exists for testing # compatibility with the new driver. We will be six # feet under soon enough. triple,argv = argv[0],argv[1:] self.cccHostMachine,_,self.cccHostSystem = triple.split('-', 2) if self.cccHostSystem.startswith('darwin'): self.cccHostSystem = 'darwin' self.cccHostRelease = '10.5.0' if self.cccHostMachine == 'x86_64': self.cccHostMachine = 'i386' self.cccHostBits = '64' elif self.cccHostMachine == 'i386': self.cccHostBits = '32' else: raise Arguments.InvalidArgumentsError("invalid option: %r" % fullOpt) self.hostInfo = HostInfo.getHostInfo(self) self.toolChain = self.hostInfo.getToolChain() args = self.parser.parseArgs(argv) # FIXME: Ho hum I have just realized -Xarch_ is broken. We really # need to reparse the Arguments after they have been expanded by # -Xarch. How is this going to work? # # Scratch that, we aren't going to do that; it really disrupts the # organization, doesn't consistently work with gcc-dd, and is # confusing. Instead we are going to enforce that -Xarch_ is only # used with options which do not alter the driver behavior. Let's # hope this is ok, because the current architecture is a little # tied to it. if cccPrintOptions: self.printOptions(args) sys.exit(0) self.handleImmediateOptions(args) if self.hostInfo.useDriverDriver(): phases = self.buildPipeline(args) else: phases = self.buildNormalPipeline(args) if cccPrintPhases: self.printPhases(phases, args) sys.exit(0) if 0: print Util.pprint(phases) jobs = self.bindPhases(phases, args) # FIXME: We should provide some basic sanity checking of the # pipeline as a "verification" sort of stage. For example, the # pipeline should never end up writing to an output file in two # places (I think). The pipeline should also never end up writing # to an output file that is an input. # # This is intended to just be a "verify" step, not a functionality # step. It should catch things like the driver driver not # preventing -save-temps, but it shouldn't change behavior (so we # can turn it off in Release-Asserts builds). # Print in -### syntax. hasHashHashHash = args.getLastArg(self.parser.hashHashHashOption) if hasHashHashHash: self.claim(hasHashHashHash) for j in jobs.iterjobs(): if isinstance(j, Jobs.Command): print >>sys.stderr, ' "%s"' % '" "'.join(j.getArgv()) elif isinstance(j, Jobs.PipedJob): for c in j.commands: print >>sys.stderr, ' "%s" %c' % ('" "'.join(c.getArgv()), "| "[c is j.commands[-1]]) elif not isinstance(j, JobList): raise ValueError,'Encountered unknown job.' sys.exit(0) try: try: self.executeJobs(args, jobs) except: if not args.getLastArg(self.parser.saveTempsOption): # Fail if removing a result fails. self.removeFiles(self.resultFiles, failOnError=True) raise finally: # Ignore failures in removing temporary files self.removeFiles(self.tempFiles, failOnError=False) def removeFiles(self, fileList, failOnError=False): for f in fileList: try: os.remove(f) except OSError,e: if failOnError: import errno if e.errno != errno.ENOENT: raise except: if failOnError: raise def executeJobs(self, args, jobs): vArg = args.getLastArg(self.parser.vOption) for j in jobs.iterjobs(): if isinstance(j, Jobs.Command): if vArg or self.cccEcho: print >>sys.stderr, ' '.join(map(str,j.getArgv())) sys.stderr.flush() p = self.startSubprocess(j.getArgv(), j.executable) res = p.wait() if res: sys.exit(res) elif isinstance(j, Jobs.PipedJob): procs = [] for sj in j.commands: if vArg or self.cccEcho: print >> sys.stderr, ' '.join(map(str,sj.getArgv())) sys.stdout.flush() if not procs: stdin = None else: stdin = procs[-1].stdout if sj is j.commands[-1]: stdout = None else: stdout = subprocess.PIPE procs.append(self.startSubprocess(sj.getArgv(), sj.executable, stdin=stdin, stdout=stdout)) for proc in procs: res = proc.wait() if res: sys.exit(res) else: raise ValueError,'Encountered unknown job.' def startSubprocess(self, argv, executable, **kwargs): try: return subprocess.Popen(argv, executable=executable, **kwargs) except OSError, e: self.warning("error trying to exec '%s': %s" % (executable, e.args[1])) sys.exit(1) def claim(self, option): # FIXME: Move to OptionList once introduced and implement. pass def warning(self, message): print >>sys.stderr,'%s: %s' % (self.driverName, message) def printOptions(self, args): for i,arg in enumerate(args): if isinstance(arg, Arguments.MultipleValuesArg): values = list(args.getValues(arg)) elif isinstance(arg, Arguments.ValueArg): values = [args.getValue(arg)] elif isinstance(arg, Arguments.JoinedAndSeparateValuesArg): values = [args.getJoinedValue(arg), args.getSeparateValue(arg)] else: values = [] print 'Option %d - Name: "%s", Values: {%s}' % (i, arg.opt.name, ', '.join(['"%s"' % v for v in values])) def printPhases(self, phases, args): def printPhase(p, f, steps): if p in steps: return steps[p] if isinstance(p, Phases.InputAction): phaseName = 'input' inputStr = '"%s"' % args.getValue(p.filename) elif isinstance(p, Phases.BindArchAction): phaseName = 'bind-arch' inputs = [printPhase(i, f, steps) for i in p.inputs] inputStr = '"%s", {%s}' % (args.getValue(p.arch), ', '.join(map(str, inputs))) else: phaseName = p.phase.name inputs = [printPhase(i, f, steps) for i in p.inputs] inputStr = '{%s}' % ', '.join(map(str, inputs)) steps[p] = index = len(steps) print "%d: %s, %s, %s" % (index,phaseName,inputStr,p.type.name) return index steps = {} for phase in phases: printPhase(phase, sys.stdout, steps) def printVersion(self): # FIXME: Print default target triple. vers = '$HeadURL$' vers = vers.split('/tools/ccc')[0] vers = vers.split('/clang/tools/clang')[0] vers = ' (' + vers[10:] + ')' print >>sys.stderr,'ccc version 1.0' + vers def handleImmediateOptions(self, args): # FIXME: Some driver Arguments are consumed right off the bat, # like -dumpversion. Currently the gcc-dd handles these # poorly, so we should be ok handling them upfront instead of # after driver-driver level dispatching. # # FIXME: The actual order of these options in gcc is all over the # place. The -dump ones seem to be first and in specification # order, but there are other levels of precedence. For example, # -print-search-dirs is evaluated before -print-prog-name=, # regardless of order (and the last instance of -print-prog-name= # wins verse itself). # # FIXME: Do we want to report "argument unused" type errors in the # presence of things like -dumpmachine and -print-search-dirs? # Probably not. if (args.getLastArg(self.parser.vOption) or args.getLastArg(self.parser.hashHashHashOption)): self.printVersion() self.suppressMissingInputWarning = True arg = args.getLastArg(self.parser.printFileNameOption) if arg: print self.getFilePath(args.getValue(arg)) sys.exit(0) arg = args.getLastArg(self.parser.printProgNameOption) if arg: print self.getProgramPath(args.getValue(arg)) sys.exit(0) arg = args.getLastArg(self.parser.printLibgccFileNameOption) if arg: print self.getFilePath('libgcc.a') sys.exit(0) def buildNormalPipeline(self, args): hasAnalyze = args.getLastArg(self.parser.analyzeOption) hasCombine = args.getLastArg(self.parser.combineOption) hasEmitLLVM = args.getLastArg(self.parser.emitLLVMOption) hasSyntaxOnly = args.getLastArg(self.parser.syntaxOnlyOption) hasDashC = args.getLastArg(self.parser.cOption) hasDashE = args.getLastArg(self.parser.EOption) hasDashS = args.getLastArg(self.parser.SOption) hasDashM = args.getLastArg(self.parser.MOption) hasDashMM = args.getLastArg(self.parser.MMOption) inputType = None inputTypeOpt = None inputs = [] for a in args: if a.opt is self.parser.inputOption: inputValue = args.getValue(a) if inputType is None: base,ext = os.path.splitext(inputValue) # stdin is handled specially. if inputValue == '-': if args.getLastArg(self.parser.EOption): # Treat as a C input needing preprocessing # (or Obj-C if over-ridden below). klass = Types.CType else: raise Arguments.InvalidArgumentsError("-E or -x required when input is from standard input") elif ext and ext in Types.kTypeSuffixMap: klass = self.hostInfo.lookupTypeForExtension(ext) else: # FIXME: Its not clear why we shouldn't just # revert to unknown. I think this is more likely a # bug / unintended behavior in gcc. Not very # important though. klass = Types.ObjectType # -ObjC and -ObjC++ over-ride the default # language, but only for "source files". We # just treat everything that isn't a linker # input as a source file. # # FIXME: Clean this up if we move the phase # sequence into the type. if klass is not Types.ObjectType: if args.getLastArg(self.parser.ObjCOption): klass = Types.ObjCType elif args.getLastArg(self.parser.ObjCXXOption): klass = Types.ObjCType else: assert inputTypeOpt is not None self.claim(inputTypeOpt) klass = inputType # Check that the file exists. It isn't clear this is # worth doing, since the tool presumably does this # anyway, and this just adds an extra stat to the # equation, but this is gcc compatible. if inputValue != '-' and not os.path.exists(inputValue): self.warning("%s: No such file or directory" % inputValue) else: inputs.append((klass, a)) elif a.opt.isLinkerInput: # Treat as a linker input. # # FIXME: This might not be good enough. We may # need to introduce another type for this case, so # that other code which needs to know the inputs # handles this properly. Best not to try and lipo # this, for example. inputs.append((Types.ObjectType, a)) elif a.opt is self.parser.xOption: inputTypeOpt = a value = args.getValue(a) if value in Types.kTypeSpecifierMap: inputType = Types.kTypeSpecifierMap[value] else: # FIXME: How are we going to handle diagnostics. self.warning("language %s not recognized" % value) # FIXME: Its not clear why we shouldn't just # revert to unknown. I think this is more likely a # bug / unintended behavior in gcc. Not very # important though. inputType = Types.ObjectType # We claim things here so that options for which we silently allow # override only ever claim the used option. if hasCombine: self.claim(hasCombine) finalPhase = Phases.Phase.eOrderPostAssemble finalPhaseOpt = None # Determine what compilation mode we are in. if hasDashE or hasDashM or hasDashMM: finalPhase = Phases.Phase.eOrderPreprocess finalPhaseOpt = hasDashE elif (hasAnalyze or hasSyntaxOnly or hasEmitLLVM or hasDashS): finalPhase = Phases.Phase.eOrderCompile finalPhaseOpt = (hasAnalyze or hasSyntaxOnly or hasEmitLLVM or hasDashS) elif hasDashC: finalPhase = Phases.Phase.eOrderAssemble finalPhaseOpt = hasDashC if finalPhaseOpt: self.claim(finalPhaseOpt) # Reject -Z* at the top level for now. arg = args.getLastArg(self.parser.ZOption) if arg: raise Arguments.InvalidArgumentsError("%s: unsupported use of internal gcc option" % ' '.join(args.render(arg))) if not inputs and not self.suppressMissingInputWarning: raise Arguments.InvalidArgumentsError("no input files") actions = [] linkerInputs = [] # FIXME: This is gross. linkPhase = Phases.LinkPhase() for klass,input in inputs: # Figure out what step to start at. # FIXME: This should be part of the input class probably? # Altough it doesn't quite fit there either, things like # asm-with-preprocess don't easily fit into a linear scheme. # FIXME: I think we are going to end up wanting to just build # a simple FSA which we run the inputs down. sequence = [] if klass.preprocess: sequence.append(Phases.PreprocessPhase()) if klass == Types.ObjectType: sequence.append(linkPhase) elif klass.onlyAssemble: sequence.extend([Phases.AssemblePhase(), linkPhase]) elif klass.onlyPrecompile: sequence.append(Phases.PrecompilePhase()) elif hasAnalyze: sequence.append(Phases.AnalyzePhase()) elif hasSyntaxOnly: sequence.append(Phases.SyntaxOnlyPhase()) elif hasEmitLLVM: sequence.append(Phases.EmitLLVMPhase()) else: sequence.extend([Phases.CompilePhase(), Phases.AssemblePhase(), linkPhase]) if sequence[0].order > finalPhase: assert finalPhaseOpt and finalPhaseOpt.opt # FIXME: Explain what type of input file is. Or just match # gcc warning. self.warning("%s: %s input file unused when %s is present" % (args.getValue(input), sequence[0].name, finalPhaseOpt.opt.name)) else: # Build the pipeline for this file. current = Phases.InputAction(input, klass) for transition in sequence: # If the current action produces no output, or we are # past what the user requested, we are done. if (current.type is Types.NothingType or transition.order > finalPhase): break else: if isinstance(transition, Phases.PreprocessPhase): assert isinstance(klass.preprocess, Types.InputType) current = Phases.JobAction(transition, [current], klass.preprocess) elif isinstance(transition, Phases.PrecompilePhase): current = Phases.JobAction(transition, [current], Types.PCHType) elif isinstance(transition, Phases.AnalyzePhase): output = Types.PlistType current = Phases.JobAction(transition, [current], output) elif isinstance(transition, Phases.SyntaxOnlyPhase): output = Types.NothingType current = Phases.JobAction(transition, [current], output) elif isinstance(transition, Phases.EmitLLVMPhase): if hasDashS: output = Types.LLVMAsmType else: output = Types.LLVMBCType current = Phases.JobAction(transition, [current], output) elif isinstance(transition, Phases.CompilePhase): output = Types.AsmTypeNoPP current = Phases.JobAction(transition, [current], output) elif isinstance(transition, Phases.AssemblePhase): current = Phases.JobAction(transition, [current], Types.ObjectType) elif transition is linkPhase: linkerInputs.append(current) current = None break else: raise RuntimeError,'Unrecognized transition: %s.' % transition pass if current is not None: assert not isinstance(current, Phases.InputAction) actions.append(current) if linkerInputs: actions.append(Phases.JobAction(linkPhase, linkerInputs, Types.ImageType)) return actions def buildPipeline(self, args): # FIXME: We need to handle canonicalization of the specified arch. archs = {} hasDashM = args.getLastArg(self.parser.MGroup) hasSaveTemps = args.getLastArg(self.parser.saveTempsOption) for arg in args: if arg.opt is self.parser.archOption: # FIXME: Canonicalize this. archName = args.getValue(arg) archs[archName] = arg archs = archs.values() if not archs: archs.append(args.makeSeparateArg(self.hostInfo.getArchName(args), self.parser.archOption)) actions = self.buildNormalPipeline(args) # FIXME: Use custom exception for this. # # FIXME: We killed off some others but these aren't yet detected in # a functional manner. If we added information to jobs about which # "auxiliary" files they wrote then we could detect the conflict # these cause downstream. if len(archs) > 1: if hasDashM: raise Arguments.InvalidArgumentsError("Cannot use -M options with multiple arch flags.") elif hasSaveTemps: raise Arguments.InvalidArgumentsError("Cannot use -save-temps with multiple arch flags.") # Execute once per arch. finalActions = [] for p in actions: # Make sure we can lipo this kind of output. If not (and it # is an actual output) then we disallow, since we can't # create an output file with the right name without # overwriting it. We could remove this oddity by just # changing the output names to include the arch, which would # also fix -save-temps. Compatibility wins for now. # # FIXME: Is this error substantially less useful than # gcc-dd's? The main problem is that "Cannot use compiler # output with multiple arch flags" won't make sense to most # developers. if (len(archs) > 1 and p.type not in (Types.NothingType,Types.ObjectType,Types.ImageType)): raise Arguments.InvalidArgumentsError('Cannot use %s output with multiple arch flags.' % p.type.name) inputs = [] for arch in archs: inputs.append(Phases.BindArchAction(p, arch)) # Lipo if necessary. We do it this way because we need to set # the arch flag so that -Xarch_ gets rewritten. if len(inputs) == 1 or p.type == Types.NothingType: finalActions.extend(inputs) else: finalActions.append(Phases.JobAction(Phases.LipoPhase(), inputs, p.type)) return finalActions def bindPhases(self, phases, args): jobs = Jobs.JobList() finalOutput = args.getLastArg(self.parser.oOption) hasSaveTemps = args.getLastArg(self.parser.saveTempsOption) hasNoIntegratedCPP = args.getLastArg(self.parser.noIntegratedCPPOption) hasTraditionalCPP = args.getLastArg(self.parser.traditionalCPPOption) hasPipe = args.getLastArg(self.parser.pipeOption) # We claim things here so that options for which we silently allow # override only ever claim the used option. if hasPipe: self.claim(hasPipe) # FIXME: Hack, override -pipe till we support it. if hasSaveTemps: self.warning('-pipe ignored because -save-temps specified') hasPipe = None # Claim these here. Its not completely accurate but any warnings # about these being unused are likely to be noise anyway. if hasSaveTemps: self.claim(hasSaveTemps) if hasTraditionalCPP: self.claim(hasTraditionalCPP) elif hasNoIntegratedCPP: self.claim(hasNoIntegratedCPP) # FIXME: Move to... somewhere else. class InputInfo: def __init__(self, source, type, baseInput): self.source = source self.type = type self.baseInput = baseInput def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.source, self.type, self.baseInput) def isOriginalInput(self): return self.source is self.baseInput def createJobs(tc, phase, canAcceptPipe=False, atTopLevel=False, arch=None, tcArgs=None, linkingOutput=None): if isinstance(phase, Phases.InputAction): return InputInfo(phase.filename, phase.type, phase.filename) elif isinstance(phase, Phases.BindArchAction): archName = args.getValue(phase.arch) tc = self.hostInfo.getToolChainForArch(archName) return createJobs(tc, phase.inputs[0], canAcceptPipe, atTopLevel, phase.arch, None, linkingOutput) if tcArgs is None: tcArgs = tc.translateArgs(args, arch) assert isinstance(phase, Phases.JobAction) tool = tc.selectTool(phase) # See if we should use an integrated CPP. We only use an # integrated cpp when we have exactly one input, since this is # the only use case we care about. useIntegratedCPP = False inputList = phase.inputs if (not hasNoIntegratedCPP and not hasTraditionalCPP and not hasSaveTemps and tool.hasIntegratedCPP()): if (len(phase.inputs) == 1 and isinstance(phase.inputs[0], Phases.JobAction) and isinstance(phase.inputs[0].phase, Phases.PreprocessPhase)): useIntegratedCPP = True inputList = phase.inputs[0].inputs # Only try to use pipes when exactly one input. attemptToPipeInput = len(inputList) == 1 and tool.acceptsPipedInput() inputs = [createJobs(tc, p, attemptToPipeInput, False, arch, tcArgs, linkingOutput) for p in inputList] # Determine if we should output to a pipe. canOutputToPipe = canAcceptPipe and tool.canPipeOutput() outputToPipe = False if canOutputToPipe: # Some things default to writing to a pipe if the final # phase and there was no user override. # # FIXME: What is the best way to handle this? if atTopLevel: if (isinstance(phase.phase, Phases.PreprocessPhase) and not finalOutput): outputToPipe = True elif hasPipe: outputToPipe = True # Figure out where to put the job (pipes). jobList = jobs if isinstance(inputs[0].source, Jobs.PipedJob): jobList = inputs[0].source baseInput = inputs[0].baseInput output,jobList = self.getOutputName(phase, outputToPipe, jobs, jobList, baseInput, args, atTopLevel, hasSaveTemps, finalOutput) tool.constructJob(phase, arch, jobList, inputs, output, phase.type, tcArgs, linkingOutput) return InputInfo(output, phase.type, baseInput) # It is an error to provide a -o option if we are making multiple # output files. if finalOutput and len([a for a in phases if a.type is not Types.NothingType]) > 1: raise Arguments.InvalidArgumentsError("cannot specify -o when generating multiple files") for phase in phases: # If we are linking an image for multiple archs then the # linker wants -arch_multiple and -final_output <final image # name>. Unfortunately this requires some gross contortions. # # FIXME: This is a hack; find a cleaner way to integrate this # into the process. linkingOutput = None if (isinstance(phase, Phases.JobAction) and isinstance(phase.phase, Phases.LipoPhase)): finalOutput = args.getLastArg(self.parser.oOption) if finalOutput: linkingOutput = finalOutput else: linkingOutput = args.makeSeparateArg('a.out', self.parser.oOption) createJobs(self.toolChain, phase, canAcceptPipe=True, atTopLevel=True, linkingOutput=linkingOutput) return jobs def getOutputName(self, phase, outputToPipe, jobs, jobList, baseInput, args, atTopLevel, hasSaveTemps, finalOutput): # Figure out where to put the output. if phase.type == Types.NothingType: output = None elif outputToPipe: if isinstance(jobList, Jobs.PipedJob): output = jobList else: jobList = output = Jobs.PipedJob([]) jobs.addJob(output) else: # Figure out what the derived output location would be. if phase.type is Types.ImageType: namedOutput = "a.out" else: assert phase.type.tempSuffix is not None inputName = args.getValue(baseInput) if phase.type.appendSuffix: namedOutput = inputName + '.' + phase.type.tempSuffix else: base,_ = os.path.splitext(inputName) namedOutput = base + '.' + phase.type.tempSuffix isTemp = False # Output to user requested destination? if atTopLevel and finalOutput: output = finalOutput self.resultFiles.append(args.getValue(finalOutput)) # Contruct a named destination? elif atTopLevel or hasSaveTemps: # As an annoying special case, pch generation # doesn't strip the pathname. if phase.type is Types.PCHType: outputName = namedOutput else: outputName = os.path.basename(namedOutput) output = args.makeSeparateArg(outputName, self.parser.oOption) self.resultFiles.append(outputName) else: # Output to temp file... fd,filename = tempfile.mkstemp(suffix='.'+phase.type.tempSuffix) output = args.makeSeparateArg(filename, self.parser.oOption) self.tempFiles.append(filename) return output,jobList <file_sep>/test/Analysis/dead-stores.c // RUN: clang-cc -analyze -warn-dead-stores -verify %s && // RUN: clang-cc -analyze -checker-simple -analyzer-store=basic -analyzer-constraints=basic -warn-dead-stores -verify %s && // RUN: clang-cc -analyze -checker-simple -analyzer-store=basic -analyzer-constraints=range -warn-dead-stores -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -analyzer-constraints=basic -warn-dead-stores -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -analyzer-constraints=range -warn-dead-stores -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -analyzer-constraints=basic -warn-dead-stores -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -analyzer-constraints=range -warn-dead-stores -verify %s void f1() { int k, y; int abc=1; long idx=abc+3*5; // expected-warning {{never read}} } void f2(void *b) { char *c = (char*)b; // no-warning char *d = b+1; // expected-warning {{never read}} printf("%s", c); // expected-warning{{implicitly declaring C library function 'printf' with type 'int (char const *, ...)'}} \ // expected-note{{please include the header <stdio.h> or explicitly provide a declaration for 'printf'}} } void f3() { int r; if ((r = f()) != 0) { // no-warning int y = r; // no-warning printf("the error is: %d\n", y); } } void f4(int k) { k = 1; if (k) f1(); k = 2; // expected-warning {{never read}} } void f5() { int x = 4; // no-warning int *p = &x; // expected-warning{{never read}} } int f6() { int x = 4; ++x; // expected-warning{{never read}} return 1; } int f7(int *p) { // This is allowed for defensive programming. p = 0; // no-warning return 1; } int f8(int *p) { extern int *baz(); if (p = baz()) // expected-warning{{Although the value}} return 1; return 0; } int f9() { int x = 4; x = x + 10; // expected-warning{{never read}} return 1; } int f10() { int x = 4; x = 10 + x; // expected-warning{{never read}} return 1; } int f11() { int x = 4; return x++; // expected-warning{{never read}} } int f11b() { int x = 4; return ((((++x)))); // no-warning } int f12a(int y) { int x = y; // expected-warning{{never read}} return 1; } int f12b(int y) { int x __attribute__((unused)) = y; // no-warning return 1; } // Filed with PR 2630. This code should produce no warnings. int f13(void) { int a = 1; int b, c = b = a + a; if (b > 0) return (0); return (a + b + c); } // Filed with PR 2763. int f14(int count) { int index, nextLineIndex; for (index = 0; index < count; index = nextLineIndex+1) { nextLineIndex = index+1; // no-warning continue; } return index; } // Test case for <rdar://problem/6248086> void f15(unsigned x, unsigned y) { int count = x * y; // no-warning int z[count]; } int f16(int x) { x = x * 2; x = sizeof(int [x = (x || x + 1) * 2]) // expected-warning{{Although the value stored to 'x' is used}} ? 5 : 8; return x; } // Self-assignments should not be flagged as dead stores. int f17() { int x = 1; x = x; // no-warning } // <rdar://problem/6506065> // The values of dead stores are only "consumed" in an enclosing expression // what that value is actually used. In other words, don't say "Although the value stored to 'x' is used...". int f18() { int x = 0; // no-warning if (1) x = 10; // expected-warning{{Value stored to 'x' is never read}} while (1) x = 10; // expected-warning{{Value stored to 'x' is never read}} do x = 10; // expected-warning{{Value stored to 'x' is never read}} while (1); return (x = 10); // expected-warning{{Although the value stored to 'x' is used in the enclosing expression, the value is never actually read from 'x'}} } // PR 3514: false positive `dead initialization` warning for init to global // http://llvm.org/bugs/show_bug.cgi?id=3514 extern const int MyConstant; int f19(void) { int x = MyConstant; // no-warning x = 1; return x; } int f19b(void) { // This case is the same as f19. const int MyConstant = 0; int x = MyConstant; // no-warning x = 1; return x; } void f20(void) { int x = 1; // no-warning #pragma unused(x) } <file_sep>/test/PCH/enum.c // Test this without pch. // RUN: clang-cc -include %S/enum.h -fsyntax-only -verify %s // Test with pch. // RUN: clang-cc -emit-pch -o %t %S/enum.h && // RUN: clang-cc -include-pch %t -fsyntax-only -verify %s int i = Red; int return_enum_constant() { int result = aRoundShape; return result; } enum Shape s = Triangle; <file_sep>/test/Parser/attributes.c // RUN: clang-cc -fsyntax-only -verify %s -pedantic -std=c99 int __attribute__(()) x; // expected-warning {{extension used}} // Hide __attribute__ behind a macro, to silence extension warnings about // "__attribute__ being an extension". #define attribute __attribute__ __inline void attribute((__always_inline__, __nodebug__)) foo(void) { } attribute(()) y; // expected-warning {{defaults to 'int'}} // PR2796 int (attribute(()) *z)(long y); void f1(attribute(()) int x); int f2(y, attribute(()) x); // expected-error {{expected identifier}} // This is parsed as a normal argument list (with two args that are implicit // int) because the attribute is a declspec. void f3(attribute(()) x, // expected-warning {{defaults to 'int'}} y); // expected-warning {{defaults to 'int'}} void f4(attribute(())); // expected-error {{expected parameter declarator}} // This is ok, the attribute applies to the pointer. int baz(int (attribute(()) *x)(long y)); void g1(void (*f1)(attribute(()) int x)); void g2(int (*f2)(y, attribute(()) x)); // expected-error {{expected identifier}} void g3(void (*f3)(attribute(()) x, int y)); // expected-warning {{defaults to 'int'}} void g4(void (*f4)(attribute(()))); // expected-error {{expected parameter declarator}} void (*h1)(void (*f1)(attribute(()) int x)); void (*h2)(int (*f2)(y, attribute(()) x)); // expected-error {{expected identifier}} void (*h3)(void (*f3)(attribute(()) x)); // expected-warning {{defaults to 'int'}} void (*h4)(void (*f4)(attribute(()))); // expected-error {{expected parameter declarator}} // rdar://6131260 int foo42(void) { int x, attribute((unused)) y, z; return 0; } // rdar://6096491 void attribute((noreturn)) d0(void), attribute((noreturn)) d1(void); <file_sep>/test/FixIt/fixit-errors.c // RUN: clang-cc -fsyntax-only -pedantic -fixit %s -o - | clang-cc -pedantic -Werror -x c - /* This is a test of the various code modification hints that are provided as part of warning or extension diagnostics. All of the warnings will be fixed by -fixit, and the resulting file should compile cleanly with -Werror -pedantic. */ struct s; // expected-note{{previous use is here}} union s *s1; // expected-error{{use of 's' with tag type that does not match previous declaration}} <file_sep>/test/CodeGen/types.c // RUN: clang-cc -emit-llvm <%s struct FileName { struct FileName *next; } *fnhead; struct ieeeExternal { struct ieeeExternal *next; } *exthead; void test1() { struct ieeeExternal *exttmp = exthead; } struct MpegEncContext; typedef struct MpegEncContext {int pb;} MpegEncContext; static void test2(void) {MpegEncContext s; s.pb;} struct Village; struct List { struct Village *v; }; struct Village { struct List returned; }; void test3(struct List a) { } <file_sep>/test/Driver/clang_f_opts.c // RUN: clang -### -S -x c /dev/null -fblocks -fbuiltin -fmath-errno -fcommon -fpascal-strings -fno-blocks -fno-builtin -fno-math-errno -fno-common -fno-pascal-strings -fblocks -fbuiltin -fmath-errno -fcommon -fpascal-strings %s 2> %t && // RUN: grep -F '"-fblocks"' %t && // RUN: grep -F '"--fmath-errno=1"' %t && // RUN: grep -F '"-fpascal-strings"' %t && // RUN: clang -### -S -x c /dev/null -fblocks -fbuiltin -fmath-errno -fcommon -fpascal-strings -fno-blocks -fno-builtin -fno-math-errno -fno-common -fno-pascal-strings %s 2> %t && // RUN: grep -F '"-fblocks=0"' %t && // RUN: grep -F '"-fbuiltin=0"' %t && // RUN: grep -F '"-fno-common"' %t && // RUN: grep -F '"--fmath-errno=0"' %t && // RUN: true <file_sep>/lib/Sema/Makefile ##===- clang/lib/Sema/Makefile -----------------------------*- Makefile -*-===## # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # ##===----------------------------------------------------------------------===## # # This implements the semantic analyzer and AST builder library for the # C-Language front-end. # ##===----------------------------------------------------------------------===## LEVEL = ../../../.. LIBRARYNAME := clangSema BUILD_ARCHIVE = 1 CXXFLAGS = -fno-rtti CPPFLAGS += -I$(PROJ_SRC_DIR)/../../include -I$(PROJ_OBJ_DIR)/../../include include $(LEVEL)/Makefile.common <file_sep>/test/SemaTemplate/temp_arg_type.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T> class A; // expected-note 2 {{template parameter is declared here}} // [temp.arg.type]p1 A<0> *a1; // expected-error{{template argument for template type parameter must be a type}} A<A> *a2; // expected-error{{template argument for template type parameter must be a type}} A<int> *a3; A<int()> *a4; A<int(float)> *a5; A<A<int> > *a6; // [temp.arg.type]p2 void f() { class X { }; A<X> * a = 0; // expected-error{{template argument uses local type 'class X'}} } struct { int x; } Unnamed; // expected-note{{unnamed type used in template argument was declared here}} A<__typeof__(Unnamed)> *a7; // expected-error{{template argument uses unnamed type}} // FIXME: [temp.arg.type]p3. The check doesn't really belong here (it // belongs somewhere in the template instantiation section). <file_sep>/test/Preprocessor/cxx_true.cpp /* RUN: clang-cc -E %s -x=c++ | grep block_1 && RUN: clang-cc -E %s -x=c++ | not grep block_2 && RUN: clang-cc -E %s -x=c | not grep block */ #if true block_1 #endif #if false block_2 #endif <file_sep>/test/CodeGen/darwin-string-literals.c // RUN: clang-cc -triple i386-apple-darwin9 -emit-llvm %s -o %t && // RUN: grep -F '@"\01LC" = internal constant [8 x i8] c"string0\00"' %t && // RUN: grep -F '@"\01LC1" = internal constant [8 x i8] c"string1\00", section "__TEXT,__cstring,cstring_literals"' %t && // RUN: grep -F '@__utf16_string_ = internal global [35 x i8] c"h\00e\00l\00l\00o\00 \00\92! \00\03& \00\90! \00w\00o\00r\00l\00d\00\00", section "__TEXT,__ustring", align 2' %t && // RUN: true const char *g0 = "string0"; const void *g1 = __builtin___CFStringMakeConstantString("string1"); const void *g2 = __builtin___CFStringMakeConstantString("hello \u2192 \u2603 \u2190 world"); <file_sep>/test/Sema/bitfield.c // RUN: clang-cc %s -fsyntax-only -verify enum e0; // expected-note{{forward declaration of 'enum e0'}} struct a { int a : -1; // expected-error{{bit-field 'a' has negative width}} // rdar://6081627 int b : 33; // expected-error{{size of bit-field 'b' exceeds size of its type (32 bits)}} int c : (1 + 0.25); // expected-error{{expression is not an integer constant expression}} int d : (int)(1 + 0.25); // rdar://6138816 int e : 0; // expected-error {{bit-field 'e' has zero width}} float xx : 4; // expected-error {{bit-field 'xx' has non-integral type}} // PR3607 enum e0 f : 1; // expected-error {{field has incomplete type 'enum e0'}} int g : (_Bool)1; }; <file_sep>/test/SemaCXX/type-traits.cpp // RUN: clang-cc -fsyntax-only -verify %s #define T(b) (b) ? 1 : -1 #define F(b) (b) ? -1 : 1 struct NonPOD { NonPOD(int); }; // PODs enum Enum { EV }; struct POD { Enum e; int i; float f; NonPOD* p; }; typedef int Int; typedef Int IntAr[10]; class Statics { static int priv; static NonPOD np; }; // Not PODs struct Derives : POD {}; struct HasCons { HasCons(int); }; struct HasAssign { HasAssign operator =(const HasAssign&); }; struct HasDest { ~HasDest(); }; class HasPriv { int priv; }; class HasProt { protected: int prot; }; struct HasRef { int i; int& ref; HasRef() : i(0), ref(i) {} }; struct HasNonPOD { NonPOD np; }; struct HasVirt { virtual void Virt() {}; }; typedef Derives NonPODAr[10]; void is_pod() { int t01[T(__is_pod(int))]; int t02[T(__is_pod(Enum))]; int t03[T(__is_pod(POD))]; int t04[T(__is_pod(Int))]; int t05[T(__is_pod(IntAr))]; int t06[T(__is_pod(Statics))]; int t21[F(__is_pod(Derives))]; int t22[F(__is_pod(HasCons))]; int t23[F(__is_pod(HasAssign))]; int t24[F(__is_pod(HasDest))]; int t25[F(__is_pod(HasPriv))]; int t26[F(__is_pod(HasProt))]; int t27[F(__is_pod(HasRef))]; int t28[F(__is_pod(HasNonPOD))]; int t29[F(__is_pod(HasVirt))]; int t30[F(__is_pod(NonPODAr))]; } union Union { int i; float f; }; typedef Derives ClassType; void is_class() { int t01[T(__is_class(Derives))]; int t02[T(__is_class(HasPriv))]; int t03[T(__is_class(ClassType))]; int t11[F(__is_class(int))]; int t12[F(__is_class(Enum))]; int t13[F(__is_class(Int))]; int t14[F(__is_class(IntAr))]; int t15[F(__is_class(NonPODAr))]; int t16[F(__is_class(Union))]; } typedef Union UnionAr[10]; typedef Union UnionType; void is_union() { int t01[T(__is_union(Union))]; int t02[T(__is_union(UnionType))]; int t11[F(__is_union(int))]; int t12[F(__is_union(Enum))]; int t13[F(__is_union(Int))]; int t14[F(__is_union(IntAr))]; int t15[F(__is_union(UnionAr))]; } typedef Enum EnumType; void is_enum() { int t01[T(__is_enum(Enum))]; int t02[T(__is_enum(EnumType))]; int t11[F(__is_enum(int))]; int t12[F(__is_enum(Union))]; int t13[F(__is_enum(Int))]; int t14[F(__is_enum(IntAr))]; int t15[F(__is_enum(UnionAr))]; int t16[F(__is_enum(Derives))]; int t17[F(__is_enum(ClassType))]; } struct Polymorph { virtual void f(); }; struct InheritPolymorph : Polymorph {}; void is_polymorphic() { int t01[T(__is_polymorphic(Polymorph))]; int t02[T(__is_polymorphic(InheritPolymorph))]; int t11[F(__is_polymorphic(int))]; int t12[F(__is_polymorphic(Union))]; int t13[F(__is_polymorphic(Int))]; int t14[F(__is_polymorphic(IntAr))]; int t15[F(__is_polymorphic(UnionAr))]; int t16[F(__is_polymorphic(Derives))]; int t17[F(__is_polymorphic(ClassType))]; int t18[F(__is_polymorphic(Enum))]; } <file_sep>/test/CodeGen/alias.c // RUN: clang-cc -triple i386-pc-linux-gnu -emit-llvm -o %t %s && // RUN: grep '@g0 = common global i32 0' %t && // RUN: grep '@f1 = alias void ()\* @f0' %t && // RUN: grep '@g1 = alias i32\* @g0' %t && // RUN: grep 'define void @f0() nounwind {' %t && void f0(void) { } extern void f1(void); extern void f1(void) __attribute((alias("f0"))); int g0; extern int g1; extern int g1 __attribute((alias("g0"))); // Make sure that aliases cause referenced values to be emitted. // PR3200 // RUN: grep 'define internal i32 @foo1()' %t && static inline int foo1() { return 0; } int foo() __attribute__((alias("foo1"))); // RUN: grep '@bar1 = internal global i32 42' %t static int bar1 = 42; int bar() __attribute__((alias("bar1"))); extern int test6(); void test7() { test6(); } // test6 is emitted as extern. // test6 changes to alias. int test6() __attribute__((alias("test7"))); <file_sep>/utils/test/MultiTestRunner.py #!/usr/bin/python """ MultiTestRunner - Harness for running multiple tests in the simple clang style. TODO -- - Fix Ctrl-c issues - Use a timeout - Detect signalled failures (abort) - Better support for finding tests """ # TOD import os, sys, re, random, time import threading import ProgressBar import TestRunner from TestRunner import TestStatus from Queue import Queue kTestFileExtensions = set(['.mi','.i','.c','.cpp','.m','.mm','.ll']) kClangErrorRE = re.compile('(.*):([0-9]+):([0-9]+): error: (.*)') kClangWarningRE = re.compile('(.*):([0-9]+):([0-9]+): warning: (.*)') kAssertionRE = re.compile('Assertion failed: (.*, function .*, file .*, line [0-9]+\\.)') def getTests(inputs): for path in inputs: if not os.path.exists(path): print >>sys.stderr,"WARNING: Invalid test \"%s\""%(path,) continue if os.path.isdir(path): for dirpath,dirnames,filenames in os.walk(path): dotTests = os.path.join(dirpath,'.tests') if os.path.exists(dotTests): for ln in open(dotTests): if ln.strip(): yield os.path.join(dirpath,ln.strip()) else: # FIXME: This doesn't belong here if 'Output' in dirnames: dirnames.remove('Output') for f in filenames: base,ext = os.path.splitext(f) if ext in kTestFileExtensions: yield os.path.join(dirpath,f) else: yield path class TestingProgressDisplay: def __init__(self, opts, numTests, progressBar=None): self.opts = opts self.numTests = numTests self.digits = len(str(self.numTests)) self.current = None self.lock = threading.Lock() self.progressBar = progressBar self.progress = 0. def update(self, index, tr): # Avoid locking overhead in quiet mode if self.opts.quiet and not tr.failed(): return # Output lock self.lock.acquire() try: self.handleUpdate(index, tr) finally: self.lock.release() def finish(self): if self.progressBar: self.progressBar.clear() elif self.opts.succinct: sys.stdout.write('\n') def handleUpdate(self, index, tr): if self.progressBar: if tr.failed(): self.progressBar.clear() else: # Force monotonicity self.progress = max(self.progress, float(index)/self.numTests) self.progressBar.update(self.progress, tr.path) return elif self.opts.succinct: if not tr.failed(): sys.stdout.write('.') sys.stdout.flush() return else: sys.stdout.write('\n') extra = '' if tr.code==TestStatus.Invalid: extra = ' - (Invalid test)' elif tr.code==TestStatus.NoRunLine: extra = ' - (No RUN line)' elif tr.failed(): extra = ' - %s'%(TestStatus.getName(tr.code).upper(),) print '%*d/%*d - %s%s'%(self.digits, index+1, self.digits, self.numTests, tr.path, extra) if tr.failed(): msgs = [] if tr.warnings: msgs.append('%d warnings'%(len(tr.warnings),)) if tr.errors: msgs.append('%d errors'%(len(tr.errors),)) if tr.assertions: msgs.append('%d assertions'%(len(tr.assertions),)) if msgs: print '\tFAIL (%s)'%(', '.join(msgs)) for i,error in enumerate(set([e for (_,_,_,e) in tr.errors])): print '\t\tERROR: %s'%(error,) if i>20: print '\t\t\t(too many errors, skipping)' break for assertion in set(tr.assertions): print '\t\tASSERTION: %s'%(assertion,) if self.opts.showOutput: TestRunner.cat(tr.testResults, sys.stdout) class TestResult: def __init__(self, path, code, testResults): self.path = path self.code = code self.testResults = testResults self.warnings = [] self.errors = [] self.assertions = [] if self.failed(): f = open(self.testResults) data = f.read() f.close() self.warnings = [m.groups() for m in kClangWarningRE.finditer(data)] self.errors = [m.groups() for m in kClangErrorRE.finditer(data)] self.assertions = [m.group(1) for m in kAssertionRE.finditer(data)] def failed(self): return self.code in (TestStatus.Fail,TestStatus.XPass) class TestProvider: def __init__(self, opts, tests, display): self.opts = opts self.tests = tests self.index = 0 self.lock = threading.Lock() self.results = [None]*len(self.tests) self.startTime = time.time() self.progress = display def get(self): self.lock.acquire() try: if self.opts.maxTime is not None: if time.time() - self.startTime > self.opts.maxTime: return None if self.index >= len(self.tests): return None item = self.tests[self.index],self.index self.index += 1 return item finally: self.lock.release() def setResult(self, index, result): self.results[index] = result self.progress.update(index, result) class Tester(threading.Thread): def __init__(self, provider): threading.Thread.__init__(self) self.provider = provider def run(self): while 1: item = self.provider.get() if item is None: break self.runTest(item) def runTest(self, (path,index)): command = path # Use hand concatentation here because we want to override # absolute paths. output = 'Output/' + path + '.out' testname = path testresults = 'Output/' + path + '.testresults' TestRunner.mkdir_p(os.path.dirname(testresults)) numTests = len(self.provider.tests) digits = len(str(numTests)) code = None try: opts = self.provider.opts if opts.debugDoNotTest: code = None else: code = TestRunner.runOneTest(path, command, output, testname, opts.clang, useValgrind=opts.useValgrind, useDGCompat=opts.useDGCompat, useScript=opts.testScript, output=open(testresults,'w')) except KeyboardInterrupt: # This is a sad hack. Unfortunately subprocess goes # bonkers with ctrl-c and we start forking merrily. print 'Ctrl-C detected, goodbye.' os.kill(0,9) self.provider.setResult(index, TestResult(path, code, testresults)) def detectCPUs(): """ Detects the number of CPUs on a system. Cribbed from pp. """ # Linux, Unix and MacOS: if hasattr(os, "sysconf"): if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"): # Linux & Unix: ncpus = os.sysconf("SC_NPROCESSORS_ONLN") if isinstance(ncpus, int) and ncpus > 0: return ncpus else: # OSX: return int(os.popen2("sysctl -n hw.ncpu")[1].read()) # Windows: if os.environ.has_key("NUMBER_OF_PROCESSORS"): ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]); if ncpus > 0: return ncpus return 1 # Default def main(): global options from optparse import OptionParser parser = OptionParser("usage: %prog [options] {inputs}") parser.add_option("-j", "--threads", dest="numThreads", help="Number of testing threads", type=int, action="store", default=detectCPUs()) parser.add_option("", "--clang", dest="clang", help="Program to use as \"clang\"", action="store", default="clang") parser.add_option("", "--vg", dest="useValgrind", help="Run tests under valgrind", action="store_true", default=False) parser.add_option("", "--dg", dest="useDGCompat", help="Use llvm dejagnu compatibility mode", action="store_true", default=False) parser.add_option("", "--script", dest="testScript", help="Default script to use", action="store", default=None) parser.add_option("-v", "--verbose", dest="showOutput", help="Show all test output", action="store_true", default=False) parser.add_option("-q", "--quiet", dest="quiet", help="Suppress no error output", action="store_true", default=False) parser.add_option("-s", "--succinct", dest="succinct", help="Reduce amount of output", action="store_true", default=False) parser.add_option("", "--max-tests", dest="maxTests", help="Maximum number of tests to run", action="store", type=int, default=None) parser.add_option("", "--max-time", dest="maxTime", help="Maximum time to spend testing (in seconds)", action="store", type=float, default=None) parser.add_option("", "--shuffle", dest="shuffle", help="Run tests in random order", action="store_true", default=False) parser.add_option("", "--seed", dest="seed", help="Seed for random number generator (default: random).", action="store", default=None) parser.add_option("", "--no-progress-bar", dest="useProgressBar", help="Do not use curses based progress bar", action="store_false", default=True) parser.add_option("", "--debug-do-not-test", dest="debugDoNotTest", help="DEBUG: Skip running actual test script", action="store_true", default=False) (opts, args) = parser.parse_args() if not args: parser.error('No inputs specified') allTests = list(getTests(args)) allTests.sort() tests = allTests if opts.seed is not None: try: seed = int(opts.seed) except: parser.error('--seed argument should be an integer') random.seed(seed) if opts.shuffle: random.shuffle(tests) if opts.maxTests is not None: tests = tests[:opts.maxTests] extra = '' if len(tests) != len(allTests): extra = ' of %d'%(len(allTests),) header = '-- Testing: %d%s tests, %d threads --'%(len(tests),extra,opts.numThreads) progressBar = None if not opts.quiet: if opts.useProgressBar: try: tc = ProgressBar.TerminalController() progressBar = ProgressBar.ProgressBar(tc, header) except ValueError: pass if not progressBar: print header display = TestingProgressDisplay(opts, len(tests), progressBar) provider = TestProvider(opts, tests, display) testers = [Tester(provider) for i in range(opts.numThreads)] startTime = time.time() for t in testers: t.start() try: for t in testers: t.join() except KeyboardInterrupt: sys.exit(1) display.finish() if not opts.quiet: print 'Testing Time: %.2fs'%(time.time() - startTime) xfails = [i for i in provider.results if i and i.code==TestStatus.XFail] if xfails: print '*'*20 print 'Expected Failures (%d):' % len(xfails) for tr in xfails: print '\t%s'%(tr.path,) xpasses = [i for i in provider.results if i and i.code==TestStatus.XPass] if xpasses: print '*'*20 print 'Unexpected Passing Tests (%d):' % len(xpasses) for tr in xpasses: print '\t%s'%(tr.path,) failures = [i for i in provider.results if i and i.code==TestStatus.Fail] if failures: print '*'*20 print 'Failing Tests (%d):' % len(failures) for tr in failures: if tr.code != TestStatus.XPass: print '\t%s'%(tr.path,) print '\nFailures: %d'%(len(failures),) assertions = {} errors = {} errorFree = [] for tr in failures: if not tr.errors and not tr.assertions: errorFree.append(tr) for (_,_,_,error) in tr.errors: errors[error] = errors.get(error,0) + 1 for assertion in tr.assertions: assertions[assertion] = assertions.get(assertion,0) + 1 if errorFree: print 'Failures w/o Errors (%d):' % len(errorFree) for tr in errorFree: print '\t%s'%(tr.path,) if errors: print 'Error Summary (%d):' % sum(errors.values()) items = errors.items() items.sort(key = lambda (_,v): -v) for i,(error,count) in enumerate(items): print '\t%3d: %s'%(count,error) if i>100: print '\t\t(too many errors, skipping)' break if assertions: print 'Assertion Summary (%d):' % sum(assertions.values()) items = assertions.items() items.sort(key = lambda (_,v): -v) for assertion,count in items: print '\t%3d: %s'%(count,assertion) if __name__=='__main__': main() <file_sep>/test/PCH/variables.c // Test this without pch. // RUN: clang-cc -include %S/variables.h -fsyntax-only -verify %s // Test with pch. // RUN: clang-cc -emit-pch -o %t %S/variables.h && // RUN: clang-cc -include-pch %t -fsyntax-only -verify %s int *ip2 = &x; float *fp = &ip; // expected-warning{{incompatible pointer types}} // FIXME:variables.h expected-note{{previous}} double z; // expected-error{{redefinition}} // FIXME:variables.h expected-note{{previous}} int z2 = 18; // expected-error{{redefinition}} //double VeryHappy; // FIXME: xpected-error{{redefinition}} int Q = A_MACRO_IN_THE_PCH; int R = FUNCLIKE_MACRO(A_MACRO_, IN_THE_PCH); int UNIQUE(a); // a2 int *Arr[] = { &a0, &a1, &a2 }; <file_sep>/test/CodeGen/staticinit.c // RUN: clang-cc -arch i386 -emit-llvm -o %t %s && // RUN: grep "g.b = internal global i8. getelementptr" %t && struct AStruct { int i; char *s; double d; }; void f() { static int i = 42; static int is[] = { 1, 2, 3, 4 }; static char* str = "forty-two"; static char* strs[] = { "one", "two", "three", "four" }; static struct AStruct myStruct = { 1, "two", 3.0 }; } void g() { static char a[10]; static char *b = a; } struct s { void *p; }; void foo(void) { static struct s var = {((void*)&((char*)0)[0])}; } // RUN: grep "f1.l0 = internal global i32 ptrtoint (i32 ()\* @f1 to i32)" %t int f1(void) { static int l0 = (unsigned) f1; } <file_sep>/lib/CodeGen/CGCXX.h //===----- CGCXX.h - C++ related code CodeGen declarations ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // These classes wrap the information about a call or function // definition used to handle ABI compliancy. // //===----------------------------------------------------------------------===// #ifndef CLANG_CODEGEN_CGCXX_H #define CLANG_CODEGEN_CGCXX_H namespace clang { /// CXXCtorType - C++ constructor types enum CXXCtorType { Ctor_Complete, // Complete object ctor Ctor_Base, // Base object ctor Ctor_CompleteAllocating // Complete object allocating ctor }; /// CXXDtorType - C++ destructor types enum CXXDtorType { Dtor_Deleting, // Deleting dtor Dtor_Complete, // Complete object dtor Dtor_Base // Base object dtor }; } // end namespace clang #endif // CLANG_CODEGEN_CGCXX_H <file_sep>/test/CodeGen/const-label-addr.c // RUN: clang-cc %s -emit-llvm -o %t int a() { A:;static void* a = &&A; } <file_sep>/tools/ccc/test/ccc/x86-target-features.c // RUN: xcc -ccc-host-machine i386 -### -S %s -mno-red-zone -mno-sse -msse4a -msoft-float &> %t && // RUN: grep '"--mattr=-sse,+sse4a"' %t && // RUN: grep '"--disable-red-zone"' %t && // RUN: grep '"--soft-float"' %t <file_sep>/test/SemaTemplate/nested-template.cpp // RUN: clang-cc -fsyntax-only %s class A; class S { public: template<typename T> struct A { struct Nested { typedef T type; }; }; }; int i; S::A<int>::Nested::type *ip = &i; <file_sep>/lib/Sema/SemaTemplate.cpp //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/ // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. //===----------------------------------------------------------------------===/ // // This file implements semantic analysis for C++ templates. //===----------------------------------------------------------------------===/ #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/DeclTemplate.h" #include "clang/Parse/DeclSpec.h" #include "clang/Basic/LangOptions.h" using namespace clang; /// isTemplateName - Determines whether the identifier II is a /// template name in the current scope, and returns the template /// declaration if II names a template. An optional CXXScope can be /// passed to indicate the C++ scope in which the identifier will be /// found. TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S, TemplateTy &TemplateResult, const CXXScopeSpec *SS) { NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName); TemplateNameKind TNK = TNK_Non_template; TemplateDecl *Template = 0; if (IIDecl) { if ((Template = dyn_cast<TemplateDecl>(IIDecl))) { if (isa<FunctionTemplateDecl>(IIDecl)) TNK = TNK_Function_template; else if (isa<ClassTemplateDecl>(IIDecl) || isa<TemplateTemplateParmDecl>(IIDecl)) TNK = TNK_Type_template; else assert(false && "Unknown template declaration kind"); } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) { // C++ [temp.local]p1: // Like normal (non-template) classes, class templates have an // injected-class-name (Clause 9). The injected-class-name // can be used with or without a template-argument-list. When // it is used without a template-argument-list, it is // equivalent to the injected-class-name followed by the // template-parameters of the class template enclosed in // <>. When it is used with a template-argument-list, it // refers to the specified class template specialization, // which could be the current specialization or another // specialization. if (Record->isInjectedClassName()) { Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record)); if ((Template = Record->getDescribedClassTemplate())) TNK = TNK_Type_template; else if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { Template = Spec->getSpecializedTemplate(); TNK = TNK_Type_template; } } } // FIXME: What follows is a gross hack. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) { if (FD->getType()->isDependentType()) { TemplateResult = TemplateTy::make(FD); return TNK_Function_template; } } else if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(IIDecl)) { for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), FEnd = Ovl->function_end(); F != FEnd; ++F) { if ((*F)->getType()->isDependentType()) { TemplateResult = TemplateTy::make(Ovl); return TNK_Function_template; } } } if (TNK != TNK_Non_template) { if (SS && SS->isSet() && !SS->isInvalid()) { NestedNameSpecifier *Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep()); TemplateResult = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false, Template)); } else TemplateResult = TemplateTy::make(TemplateName(Template)); } } return TNK; } /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining /// that the template parameter 'PrevDecl' is being shadowed by a new /// declaration at location Loc. Returns true to indicate that this is /// an error, and false otherwise. bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); // Microsoft Visual C++ permits template parameters to be shadowed. if (getLangOptions().Microsoft) return false; // C++ [temp.local]p4: // A template-parameter shall not be redeclared within its // scope (including nested scopes). Diag(Loc, diag::err_template_param_shadow) << cast<NamedDecl>(PrevDecl)->getDeclName(); Diag(PrevDecl->getLocation(), diag::note_template_param_here); return true; } /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset /// the parameter D to reference the templated declaration and return a pointer /// to the template declaration. Otherwise, do nothing to D and return null. TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) { if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) { D = DeclPtrTy::make(Temp->getTemplatedDecl()); return Temp; } return 0; } /// ActOnTypeParameter - Called when a C++ template type parameter /// (e.g., "typename T") has been parsed. Typename specifies whether /// the keyword "typename" was used to declare the type parameter /// (otherwise, "class" was used), and KeyLoc is the location of the /// "class" or "typename" keyword. ParamName is the name of the /// parameter (NULL indicates an unnamed template parameter) and /// ParamName is the location of the parameter name (if any). /// If the type parameter has a default argument, it will be added /// later via ActOnTypeParameterDefault. Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position) { assert(S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"); bool Invalid = false; if (ParamName) { NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName); if (PrevDecl && PrevDecl->isTemplateParameter()) Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl); } SourceLocation Loc = ParamNameLoc; if (!ParamName) Loc = KeyLoc; TemplateTypeParmDecl *Param = TemplateTypeParmDecl::Create(Context, CurContext, Loc, Depth, Position, ParamName, Typename); if (Invalid) Param->setInvalidDecl(); if (ParamName) { // Add the template parameter into the current scope. S->AddDecl(DeclPtrTy::make(Param)); IdResolver.AddDecl(Param); } return DeclPtrTy::make(Param); } /// ActOnTypeParameterDefault - Adds a default argument (the type /// Default) to the given template type parameter (TypeParam). void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam, SourceLocation EqualLoc, SourceLocation DefaultLoc, TypeTy *DefaultT) { TemplateTypeParmDecl *Parm = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>()); QualType Default = QualType::getFromOpaquePtr(DefaultT); // C++ [temp.param]p14: // A template-parameter shall not be used in its own default argument. // FIXME: Implement this check! Needs a recursive walk over the types. // Check the template argument itself. if (CheckTemplateArgument(Parm, Default, DefaultLoc)) { Parm->setInvalidDecl(); return; } Parm->setDefaultArgument(Default, DefaultLoc, false); } /// \brief Check that the type of a non-type template parameter is /// well-formed. /// /// \returns the (possibly-promoted) parameter type if valid; /// otherwise, produces a diagnostic and returns a NULL type. QualType Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { // C++ [temp.param]p4: // // A non-type template-parameter shall have one of the following // (optionally cv-qualified) types: // // -- integral or enumeration type, if (T->isIntegralType() || T->isEnumeralType() || // -- pointer to object or pointer to function, (T->isPointerType() && (T->getAsPointerType()->getPointeeType()->isObjectType() || T->getAsPointerType()->getPointeeType()->isFunctionType())) || // -- reference to object or reference to function, T->isReferenceType() || // -- pointer to member. T->isMemberPointerType() || // If T is a dependent type, we can't do the check now, so we // assume that it is well-formed. T->isDependentType()) return T; // C++ [temp.param]p8: // // A non-type template-parameter of type "array of T" or // "function returning T" is adjusted to be of type "pointer to // T" or "pointer to function returning T", respectively. else if (T->isArrayType()) // FIXME: Keep the type prior to promotion? return Context.getArrayDecayedType(T); else if (T->isFunctionType()) // FIXME: Keep the type prior to promotion? return Context.getPointerType(T); Diag(Loc, diag::err_template_nontype_parm_bad_type) << T; return QualType(); } /// ActOnNonTypeTemplateParameter - Called when a C++ non-type /// template parameter (e.g., "int Size" in "template<int Size> /// class Array") has been parsed. S is the current scope and D is /// the parsed declarator. Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position) { QualType T = GetTypeForDeclarator(D, S); assert(S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"); bool Invalid = false; IdentifierInfo *ParamName = D.getIdentifier(); if (ParamName) { NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName); if (PrevDecl && PrevDecl->isTemplateParameter()) Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); } T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); if (T.isNull()) { T = Context.IntTy; // Recover with an 'int' type. Invalid = true; } NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(), Depth, Position, ParamName, T); if (Invalid) Param->setInvalidDecl(); if (D.getIdentifier()) { // Add the template parameter into the current scope. S->AddDecl(DeclPtrTy::make(Param)); IdResolver.AddDecl(Param); } return DeclPtrTy::make(Param); } /// \brief Adds a default argument to the given non-type template /// parameter. void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD, SourceLocation EqualLoc, ExprArg DefaultE) { NonTypeTemplateParmDecl *TemplateParm = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>()); Expr *Default = static_cast<Expr *>(DefaultE.get()); // C++ [temp.param]p14: // A template-parameter shall not be used in its own default argument. // FIXME: Implement this check! Needs a recursive walk over the types. // Check the well-formedness of the default template argument. if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) { TemplateParm->setInvalidDecl(); return; } TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release())); } /// ActOnTemplateTemplateParameter - Called when a C++ template template /// parameter (e.g. T in template <template <typename> class T> class array) /// has been parsed. S is the current scope. Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S, SourceLocation TmpLoc, TemplateParamsTy *Params, IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth, unsigned Position) { assert(S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"); // Construct the parameter object. TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth, Position, Name, (TemplateParameterList*)Params); // Make sure the parameter is valid. // FIXME: Decl object is not currently invalidated anywhere so this doesn't // do anything yet. However, if the template parameter list or (eventual) // default value is ever invalidated, that will propagate here. bool Invalid = false; if (Invalid) { Param->setInvalidDecl(); } // If the tt-param has a name, then link the identifier into the scope // and lookup mechanisms. if (Name) { S->AddDecl(DeclPtrTy::make(Param)); IdResolver.AddDecl(Param); } return DeclPtrTy::make(Param); } /// \brief Adds a default argument to the given template template /// parameter. void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD, SourceLocation EqualLoc, ExprArg DefaultE) { TemplateTemplateParmDecl *TemplateParm = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>()); // Since a template-template parameter's default argument is an // id-expression, it must be a DeclRefExpr. DeclRefExpr *Default = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get())); // C++ [temp.param]p14: // A template-parameter shall not be used in its own default argument. // FIXME: Implement this check! Needs a recursive walk over the types. // Check the well-formedness of the template argument. if (!isa<TemplateDecl>(Default->getDecl())) { Diag(Default->getSourceRange().getBegin(), diag::err_template_arg_must_be_template) << Default->getSourceRange(); TemplateParm->setInvalidDecl(); return; } if (CheckTemplateArgument(TemplateParm, Default)) { TemplateParm->setInvalidDecl(); return; } DefaultE.release(); TemplateParm->setDefaultArgument(Default); } /// ActOnTemplateParameterList - Builds a TemplateParameterList that /// contains the template parameters in Params/NumParams. Sema::TemplateParamsTy * Sema::ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, DeclPtrTy *Params, unsigned NumParams, SourceLocation RAngleLoc) { if (ExportLoc.isValid()) Diag(ExportLoc, diag::note_template_export_unsupported); return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, (Decl**)Params, NumParams, RAngleLoc); } Sema::DeclResult Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK, SourceLocation KWLoc, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, MultiTemplateParamsArg TemplateParameterLists, AccessSpecifier AS) { assert(TemplateParameterLists.size() > 0 && "No template parameter lists?"); assert(TK != TK_Reference && "Can only declare or define class templates"); bool Invalid = false; // Check that we can declare a template here. if (CheckTemplateDeclScope(S, TemplateParameterLists)) return true; TagDecl::TagKind Kind; switch (TagSpec) { default: assert(0 && "Unknown tag type!"); case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; } // There is no such thing as an unnamed class template. if (!Name) { Diag(KWLoc, diag::err_template_unnamed_class); return true; } // Find any previous declaration with this name. LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName, true); assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?"); NamedDecl *PrevDecl = 0; if (Previous.begin() != Previous.end()) PrevDecl = *Previous.begin(); DeclContext *SemanticContext = CurContext; if (SS.isNotEmpty() && !SS.isInvalid()) { SemanticContext = computeDeclContext(SS); // FIXME: need to match up several levels of template parameter // lists here. } // FIXME: member templates! TemplateParameterList *TemplateParams = static_cast<TemplateParameterList *>(*TemplateParameterLists.release()); // If there is a previous declaration with the same name, check // whether this is a valid redeclaration. ClassTemplateDecl *PrevClassTemplate = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); if (PrevClassTemplate) { // Ensure that the template parameter lists are compatible. if (!TemplateParameterListsAreEqual(TemplateParams, PrevClassTemplate->getTemplateParameters(), /*Complain=*/true)) return true; // C++ [temp.class]p4: // In a redeclaration, partial specialization, explicit // specialization or explicit instantiation of a class template, // the class-key shall agree in kind with the original class // template declaration (7.1.5.3). RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); if (PrevRecordDecl->getTagKind() != Kind) { Diag(KWLoc, diag::err_use_with_wrong_tag) << Name << CodeModificationHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); Kind = PrevRecordDecl->getTagKind(); } // Check for redefinition of this class template. if (TK == TK_Definition) { if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) { Diag(NameLoc, diag::err_redefinition) << Name; Diag(Def->getLocation(), diag::note_previous_definition); // FIXME: Would it make sense to try to "forget" the previous // definition, as part of error recovery? return true; } } } else if (PrevDecl && PrevDecl->isTemplateParameter()) { // Maybe we will complain about the shadowed template parameter. DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); // Just pretend that we didn't see the previous declaration. PrevDecl = 0; } else if (PrevDecl) { // C++ [temp]p5: // A class template shall not have the same name as any other // template, class, function, object, enumeration, enumerator, // namespace, or type in the same scope (3.3), except as specified // in (14.5.4). Diag(NameLoc, diag::err_redefinition_different_kind) << Name; Diag(PrevDecl->getLocation(), diag::note_previous_definition); return true; } // Check the template parameter list of this declaration, possibly // merging in the template parameter list from the previous class // template declaration. if (CheckTemplateParameterList(TemplateParams, PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0)) Invalid = true; // If we had a scope specifier, we better have a previous template // declaration! CXXRecordDecl *NewClass = CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, PrevClassTemplate? PrevClassTemplate->getTemplatedDecl() : 0); ClassTemplateDecl *NewTemplate = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, DeclarationName(Name), TemplateParams, NewClass, PrevClassTemplate); NewClass->setDescribedClassTemplate(NewTemplate); // Set the access specifier. SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); // Set the lexical context of these templates NewClass->setLexicalDeclContext(CurContext); NewTemplate->setLexicalDeclContext(CurContext); if (TK == TK_Definition) NewClass->startDefinition(); if (Attr) ProcessDeclAttributeList(NewClass, Attr); PushOnScopeChains(NewTemplate, S); if (Invalid) { NewTemplate->setInvalidDecl(); NewClass->setInvalidDecl(); } return DeclPtrTy::make(NewTemplate); } /// \brief Checks the validity of a template parameter list, possibly /// considering the template parameter list from a previous /// declaration. /// /// If an "old" template parameter list is provided, it must be /// equivalent (per TemplateParameterListsAreEqual) to the "new" /// template parameter list. /// /// \param NewParams Template parameter list for a new template /// declaration. This template parameter list will be updated with any /// default arguments that are carried through from the previous /// template parameter list. /// /// \param OldParams If provided, template parameter list from a /// previous declaration of the same template. Default template /// arguments will be merged from the old template parameter list to /// the new template parameter list. /// /// \returns true if an error occurred, false otherwise. bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams) { bool Invalid = false; // C++ [temp.param]p10: // The set of default template-arguments available for use with a // template declaration or definition is obtained by merging the // default arguments from the definition (if in scope) and all // declarations in scope in the same way default function // arguments are (8.3.6). bool SawDefaultArgument = false; SourceLocation PreviousDefaultArgLoc; // Dummy initialization to avoid warnings. TemplateParameterList::iterator OldParam = NewParams->end(); if (OldParams) OldParam = OldParams->begin(); for (TemplateParameterList::iterator NewParam = NewParams->begin(), NewParamEnd = NewParams->end(); NewParam != NewParamEnd; ++NewParam) { // Variables used to diagnose redundant default arguments bool RedundantDefaultArg = false; SourceLocation OldDefaultLoc; SourceLocation NewDefaultLoc; // Variables used to diagnose missing default arguments bool MissingDefaultArg = false; // Merge default arguments for template type parameters. if (TemplateTypeParmDecl *NewTypeParm = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { TemplateTypeParmDecl *OldTypeParm = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0; if (OldTypeParm && OldTypeParm->hasDefaultArgument() && NewTypeParm->hasDefaultArgument()) { OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); SawDefaultArgument = true; RedundantDefaultArg = true; PreviousDefaultArgLoc = NewDefaultLoc; } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { // Merge the default argument from the old declaration to the // new declaration. SawDefaultArgument = true; NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(), OldTypeParm->getDefaultArgumentLoc(), true); PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); } else if (NewTypeParm->hasDefaultArgument()) { SawDefaultArgument = true; PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); } else if (SawDefaultArgument) MissingDefaultArg = true; } // Merge default arguments for non-type template parameters else if (NonTypeTemplateParmDecl *NewNonTypeParm = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { NonTypeTemplateParmDecl *OldNonTypeParm = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0; if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && NewNonTypeParm->hasDefaultArgument()) { OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); SawDefaultArgument = true; RedundantDefaultArg = true; PreviousDefaultArgLoc = NewDefaultLoc; } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { // Merge the default argument from the old declaration to the // new declaration. SawDefaultArgument = true; // FIXME: We need to create a new kind of "default argument" // expression that points to a previous template template // parameter. NewNonTypeParm->setDefaultArgument( OldNonTypeParm->getDefaultArgument()); PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); } else if (NewNonTypeParm->hasDefaultArgument()) { SawDefaultArgument = true; PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); } else if (SawDefaultArgument) MissingDefaultArg = true; } // Merge default arguments for template template parameters else { TemplateTemplateParmDecl *NewTemplateParm = cast<TemplateTemplateParmDecl>(*NewParam); TemplateTemplateParmDecl *OldTemplateParm = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0; if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && NewTemplateParm->hasDefaultArgument()) { OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc(); NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc(); SawDefaultArgument = true; RedundantDefaultArg = true; PreviousDefaultArgLoc = NewDefaultLoc; } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { // Merge the default argument from the old declaration to the // new declaration. SawDefaultArgument = true; // FIXME: We need to create a new kind of "default argument" // expression that points to a previous template template // parameter. NewTemplateParm->setDefaultArgument( OldTemplateParm->getDefaultArgument()); PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc(); } else if (NewTemplateParm->hasDefaultArgument()) { SawDefaultArgument = true; PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc(); } else if (SawDefaultArgument) MissingDefaultArg = true; } if (RedundantDefaultArg) { // C++ [temp.param]p12: // A template-parameter shall not be given default arguments // by two different declarations in the same scope. Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); Invalid = true; } else if (MissingDefaultArg) { // C++ [temp.param]p11: // If a template-parameter has a default template-argument, // all subsequent template-parameters shall have a default // template-argument supplied. Diag((*NewParam)->getLocation(), diag::err_template_param_default_arg_missing); Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); Invalid = true; } // If we have an old template parameter list that we're merging // in, move on to the next parameter. if (OldParams) ++OldParam; } return Invalid; } /// \brief Translates template arguments as provided by the parser /// into template arguments used by semantic analysis. static void translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn, SourceLocation *TemplateArgLocs, llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) { TemplateArgs.reserve(TemplateArgsIn.size()); void **Args = TemplateArgsIn.getArgs(); bool *ArgIsType = TemplateArgsIn.getArgIsType(); for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) { TemplateArgs.push_back( ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg], QualType::getFromOpaquePtr(Args[Arg])) : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg]))); } } /// \brief Build a canonical version of a template argument list. /// /// This function builds a canonical version of the given template /// argument list, where each of the template arguments has been /// converted into its canonical form. This routine is typically used /// to canonicalize a template argument list when the template name /// itself is dependent. When the template name refers to an actual /// template declaration, Sema::CheckTemplateArgumentList should be /// used to check and canonicalize the template arguments. /// /// \param TemplateArgs The incoming template arguments. /// /// \param NumTemplateArgs The number of template arguments in \p /// TemplateArgs. /// /// \param Canonical A vector to be filled with the canonical versions /// of the template arguments. /// /// \param Context The ASTContext in which the template arguments live. static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, llvm::SmallVectorImpl<TemplateArgument> &Canonical, ASTContext &Context) { Canonical.reserve(NumTemplateArgs); for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) { switch (TemplateArgs[Idx].getKind()) { case TemplateArgument::Expression: // FIXME: Build canonical expression (!) Canonical.push_back(TemplateArgs[Idx]); break; case TemplateArgument::Declaration: Canonical.push_back(TemplateArgument(SourceLocation(), TemplateArgs[Idx].getAsDecl())); break; case TemplateArgument::Integral: Canonical.push_back(TemplateArgument(SourceLocation(), *TemplateArgs[Idx].getAsIntegral(), TemplateArgs[Idx].getIntegralType())); case TemplateArgument::Type: { QualType CanonType = Context.getCanonicalType(TemplateArgs[Idx].getAsType()); Canonical.push_back(TemplateArgument(SourceLocation(), CanonType)); } } } } QualType Sema::CheckTemplateIdType(TemplateName Name, SourceLocation TemplateLoc, SourceLocation LAngleLoc, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc) { TemplateDecl *Template = Name.getAsTemplateDecl(); if (!Template) { // The template name does not resolve to a template, so we just // build a dependent template-id type. // Canonicalize the template arguments to build the canonical // template-id type. llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs; CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs, CanonicalTemplateArgs, Context); // FIXME: Get the canonical template-name QualType CanonType = Context.getTemplateSpecializationType(Name, &CanonicalTemplateArgs[0], CanonicalTemplateArgs.size()); // Build the dependent template-id type. return Context.getTemplateSpecializationType(Name, TemplateArgs, NumTemplateArgs, CanonType); } // Check that the template argument list is well-formed for this // template. llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs; if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc, TemplateArgs, NumTemplateArgs, RAngleLoc, ConvertedTemplateArgs)) return QualType(); assert((ConvertedTemplateArgs.size() == Template->getTemplateParameters()->size()) && "Converted template argument list is too short!"); QualType CanonType; if (TemplateSpecializationType::anyDependentTemplateArguments( TemplateArgs, NumTemplateArgs)) { // This class template specialization is a dependent // type. Therefore, its canonical type is another class template // specialization type that contains all of the converted // arguments in canonical form. This ensures that, e.g., A<T> and // A<T, T> have identical types when A is declared as: // // template<typename T, typename U = T> struct A; CanonType = Context.getTemplateSpecializationType(Name, &ConvertedTemplateArgs[0], ConvertedTemplateArgs.size()); } else if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Template)) { // Find the class template specialization declaration that // corresponds to these arguments. llvm::FoldingSetNodeID ID; ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0], ConvertedTemplateArgs.size()); void *InsertPos = 0; ClassTemplateSpecializationDecl *Decl = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); if (!Decl) { // This is the first time we have referenced this class template // specialization. Create the canonical declaration and add it to // the set of specializations. Decl = ClassTemplateSpecializationDecl::Create(Context, ClassTemplate->getDeclContext(), TemplateLoc, ClassTemplate, &ConvertedTemplateArgs[0], ConvertedTemplateArgs.size(), 0); ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos); Decl->setLexicalDeclContext(CurContext); } CanonType = Context.getTypeDeclType(Decl); } // Build the fully-sugared type for this class template // specialization, which refers back to the class template // specialization we created or found. return Context.getTemplateSpecializationType(Name, TemplateArgs, NumTemplateArgs, CanonType); } Action::TypeResult Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation *TemplateArgLocs, SourceLocation RAngleLoc) { TemplateName Template = TemplateD.getAsVal<TemplateName>(); // Translate the parser's template argument list in our AST format. llvm::SmallVector<TemplateArgument, 16> TemplateArgs; translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc, &TemplateArgs[0], TemplateArgs.size(), RAngleLoc); TemplateArgsIn.release(); if (Result.isNull()) return true; return Result.getAsOpaquePtr(); } /// \brief Form a dependent template name. /// /// This action forms a dependent template name given the template /// name and its (presumably dependent) scope specifier. For /// example, given "MetaFun::template apply", the scope specifier \p /// SS will be "MetaFun::", \p TemplateKWLoc contains the location /// of the "template" keyword, and "apply" is the \p Name. Sema::TemplateTy Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc, const IdentifierInfo &Name, SourceLocation NameLoc, const CXXScopeSpec &SS) { if (!SS.isSet() || SS.isInvalid()) return TemplateTy(); NestedNameSpecifier *Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); // FIXME: member of the current instantiation if (!Qualifier->isDependent()) { // C++0x [temp.names]p5: // If a name prefixed by the keyword template is not the name of // a template, the program is ill-formed. [Note: the keyword // template may not be applied to non-template members of class // templates. -end note ] [ Note: as is the case with the // typename prefix, the template prefix is allowed in cases // where it is not strictly necessary; i.e., when the // nested-name-specifier or the expression on the left of the -> // or . is not dependent on a template-parameter, or the use // does not appear in the scope of a template. -end note] // // Note: C++03 was more strict here, because it banned the use of // the "template" keyword prior to a template-name that was not a // dependent name. C++ DR468 relaxed this requirement (the // "template" keyword is now permitted). We follow the C++0x // rules, even in C++03 mode, retroactively applying the DR. TemplateTy Template; TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS); if (TNK == TNK_Non_template) { Diag(NameLoc, diag::err_template_kw_refers_to_non_template) << &Name; return TemplateTy(); } return Template; } return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name)); } /// \brief Check that the given template argument list is well-formed /// for specializing the given template. bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation LAngleLoc, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation RAngleLoc, llvm::SmallVectorImpl<TemplateArgument> &Converted) { TemplateParameterList *Params = Template->getTemplateParameters(); unsigned NumParams = Params->size(); unsigned NumArgs = NumTemplateArgs; bool Invalid = false; if (NumArgs > NumParams || NumArgs < Params->getMinRequiredArguments()) { // FIXME: point at either the first arg beyond what we can handle, // or the '>', depending on whether we have too many or too few // arguments. SourceRange Range; if (NumArgs > NumParams) Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); Diag(TemplateLoc, diag::err_template_arg_list_different_arity) << (NumArgs > NumParams) << (isa<ClassTemplateDecl>(Template)? 0 : isa<FunctionTemplateDecl>(Template)? 1 : isa<TemplateTemplateParmDecl>(Template)? 2 : 3) << Template << Range; Diag(Template->getLocation(), diag::note_template_decl_here) << Params->getSourceRange(); Invalid = true; } // C++ [temp.arg]p1: // [...] The type and form of each template-argument specified in // a template-id shall match the type and form specified for the // corresponding parameter declared by the template in its // template-parameter-list. unsigned ArgIdx = 0; for (TemplateParameterList::iterator Param = Params->begin(), ParamEnd = Params->end(); Param != ParamEnd; ++Param, ++ArgIdx) { // Decode the template argument TemplateArgument Arg; if (ArgIdx >= NumArgs) { // Retrieve the default template argument from the template // parameter. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { if (!TTP->hasDefaultArgument()) break; QualType ArgType = TTP->getDefaultArgument(); // If the argument type is dependent, instantiate it now based // on the previously-computed template arguments. if (ArgType->isDependentType()) { InstantiatingTemplate Inst(*this, TemplateLoc, Template, &Converted[0], Converted.size(), SourceRange(TemplateLoc, RAngleLoc)); ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(), TTP->getDefaultArgumentLoc(), TTP->getDeclName()); } if (ArgType.isNull()) return true; Arg = TemplateArgument(TTP->getLocation(), ArgType); } else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { if (!NTTP->hasDefaultArgument()) break; // FIXME: Instantiate default argument Arg = TemplateArgument(NTTP->getDefaultArgument()); } else { TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(*Param); if (!TempParm->hasDefaultArgument()) break; // FIXME: Instantiate default argument Arg = TemplateArgument(TempParm->getDefaultArgument()); } } else { // Retrieve the template argument produced by the user. Arg = TemplateArgs[ArgIdx]; } if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { // Check template type parameters. if (Arg.getKind() == TemplateArgument::Type) { if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation())) Invalid = true; // Add the converted template type argument. Converted.push_back( TemplateArgument(Arg.getLocation(), Context.getCanonicalType(Arg.getAsType()))); continue; } // C++ [temp.arg.type]p1: // A template-argument for a template-parameter which is a // type shall be a type-id. // We have a template type parameter but the template argument // is not a type. Diag(Arg.getLocation(), diag::err_template_arg_must_be_type); Diag((*Param)->getLocation(), diag::note_template_param_here); Invalid = true; } else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { // Check non-type template parameters. // Instantiate the type of the non-type template parameter with // the template arguments we've seen thus far. QualType NTTPType = NTTP->getType(); if (NTTPType->isDependentType()) { // Instantiate the type of the non-type template parameter. InstantiatingTemplate Inst(*this, TemplateLoc, Template, &Converted[0], Converted.size(), SourceRange(TemplateLoc, RAngleLoc)); NTTPType = InstantiateType(NTTPType, &Converted[0], Converted.size(), NTTP->getLocation(), NTTP->getDeclName()); // If that worked, check the non-type template parameter type // for validity. if (!NTTPType.isNull()) NTTPType = CheckNonTypeTemplateParameterType(NTTPType, NTTP->getLocation()); if (NTTPType.isNull()) { Invalid = true; break; } } switch (Arg.getKind()) { case TemplateArgument::Expression: { Expr *E = Arg.getAsExpr(); if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted)) Invalid = true; break; } case TemplateArgument::Declaration: case TemplateArgument::Integral: // We've already checked this template argument, so just copy // it to the list of converted arguments. Converted.push_back(Arg); break; case TemplateArgument::Type: // We have a non-type template parameter but the template // argument is a type. // C++ [temp.arg]p2: // In a template-argument, an ambiguity between a type-id and // an expression is resolved to a type-id, regardless of the // form of the corresponding template-parameter. // // We warn specifically about this case, since it can be rather // confusing for users. if (Arg.getAsType()->isFunctionType()) Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig) << Arg.getAsType(); else Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr); Diag((*Param)->getLocation(), diag::note_template_param_here); Invalid = true; } } else { // Check template template parameters. TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(*Param); switch (Arg.getKind()) { case TemplateArgument::Expression: { Expr *ArgExpr = Arg.getAsExpr(); if (ArgExpr && isa<DeclRefExpr>(ArgExpr) && isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) { if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr))) Invalid = true; // Add the converted template argument. // FIXME: Need the "canonical" template declaration! Converted.push_back( TemplateArgument(Arg.getLocation(), cast<DeclRefExpr>(ArgExpr)->getDecl())); continue; } } // fall through case TemplateArgument::Type: { // We have a template template parameter but the template // argument does not refer to a template. Diag(Arg.getLocation(), diag::err_template_arg_must_be_template); Invalid = true; break; } case TemplateArgument::Declaration: // We've already checked this template argument, so just copy // it to the list of converted arguments. Converted.push_back(Arg); break; case TemplateArgument::Integral: assert(false && "Integral argument with template template parameter"); break; } } } return Invalid; } /// \brief Check a template argument against its corresponding /// template type parameter. /// /// This routine implements the semantics of C++ [temp.arg.type]. It /// returns true if an error occurred, and false otherwise. bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, QualType Arg, SourceLocation ArgLoc) { // C++ [temp.arg.type]p2: // A local type, a type with no linkage, an unnamed type or a type // compounded from any of these types shall not be used as a // template-argument for a template type-parameter. // // FIXME: Perform the recursive and no-linkage type checks. const TagType *Tag = 0; if (const EnumType *EnumT = Arg->getAsEnumType()) Tag = EnumT; else if (const RecordType *RecordT = Arg->getAsRecordType()) Tag = RecordT; if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) return Diag(ArgLoc, diag::err_template_arg_local_type) << QualType(Tag, 0); else if (Tag && !Tag->getDecl()->getDeclName() && !Tag->getDecl()->getTypedefForAnonDecl()) { Diag(ArgLoc, diag::err_template_arg_unnamed_type); Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here); return true; } return false; } /// \brief Checks whether the given template argument is the address /// of an object or function according to C++ [temp.arg.nontype]p1. bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg, NamedDecl *&Entity) { bool Invalid = false; // See through any implicit casts we added to fix the type. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) Arg = Cast->getSubExpr(); // C++ [temp.arg.nontype]p1: // // A template-argument for a non-type, non-template // template-parameter shall be one of: [...] // // -- the address of an object or function with external // linkage, including function templates and function // template-ids but excluding non-static class members, // expressed as & id-expression where the & is optional if // the name refers to a function or array, or if the // corresponding template-parameter is a reference; or DeclRefExpr *DRE = 0; // Ignore (and complain about) any excess parentheses. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { if (!Invalid) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_extra_parens) << Arg->getSourceRange(); Invalid = true; } Arg = Parens->getSubExpr(); } if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { if (UnOp->getOpcode() == UnaryOperator::AddrOf) DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); } else DRE = dyn_cast<DeclRefExpr>(Arg); if (!DRE || !isa<ValueDecl>(DRE->getDecl())) return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_object_or_func_form) << Arg->getSourceRange(); // Cannot refer to non-static data members if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) << Field << Arg->getSourceRange(); // Cannot refer to non-static member functions if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) if (!Method->isStatic()) return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method) << Method << Arg->getSourceRange(); // Functions must have external linkage. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { if (Func->getStorageClass() == FunctionDecl::Static) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_function_not_extern) << Func << Arg->getSourceRange(); Diag(Func->getLocation(), diag::note_template_arg_internal_object) << true; return true; } // Okay: we've named a function with external linkage. Entity = Func; return Invalid; } if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { if (!Var->hasGlobalStorage()) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_object_not_extern) << Var << Arg->getSourceRange(); Diag(Var->getLocation(), diag::note_template_arg_internal_object) << true; return true; } // Okay: we've named an object with external linkage Entity = Var; return Invalid; } // We found something else, but we don't know specifically what it is. Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_object_or_func) << Arg->getSourceRange(); Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); return true; } /// \brief Checks whether the given template argument is a pointer to /// member constant according to C++ [temp.arg.nontype]p1. bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) { bool Invalid = false; // See through any implicit casts we added to fix the type. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) Arg = Cast->getSubExpr(); // C++ [temp.arg.nontype]p1: // // A template-argument for a non-type, non-template // template-parameter shall be one of: [...] // // -- a pointer to member expressed as described in 5.3.1. QualifiedDeclRefExpr *DRE = 0; // Ignore (and complain about) any excess parentheses. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { if (!Invalid) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_extra_parens) << Arg->getSourceRange(); Invalid = true; } Arg = Parens->getSubExpr(); } if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) if (UnOp->getOpcode() == UnaryOperator::AddrOf) DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr()); if (!DRE) return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_pointer_to_member_form) << Arg->getSourceRange(); if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { assert((isa<FieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && "Only non-static member pointers can make it here"); // Okay: this is the address of a non-static member, and therefore // a member pointer constant. Member = DRE->getDecl(); return Invalid; } // We found something else, but we don't know specifically what it is. Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_pointer_to_member_form) << Arg->getSourceRange(); Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); return true; } /// \brief Check a template argument against its corresponding /// non-type template parameter. /// /// This routine implements the semantics of C++ [temp.arg.nontype]. /// It returns true if an error occurred, and false otherwise. \p /// InstantiatedParamType is the type of the non-type template /// parameter after it has been instantiated. /// /// If Converted is non-NULL and no errors occur, the value /// of this argument will be added to the end of the Converted vector. bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *&Arg, llvm::SmallVectorImpl<TemplateArgument> *Converted) { SourceLocation StartLoc = Arg->getSourceRange().getBegin(); // If either the parameter has a dependent type or the argument is // type-dependent, there's nothing we can check now. // FIXME: Add template argument to Converted! if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { // FIXME: Produce a cloned, canonical expression? Converted->push_back(TemplateArgument(Arg)); return false; } // C++ [temp.arg.nontype]p5: // The following conversions are performed on each expression used // as a non-type template-argument. If a non-type // template-argument cannot be converted to the type of the // corresponding template-parameter then the program is // ill-formed. // // -- for a non-type template-parameter of integral or // enumeration type, integral promotions (4.5) and integral // conversions (4.7) are applied. QualType ParamType = InstantiatedParamType; QualType ArgType = Arg->getType(); if (ParamType->isIntegralType() || ParamType->isEnumeralType()) { // C++ [temp.arg.nontype]p1: // A template-argument for a non-type, non-template // template-parameter shall be one of: // // -- an integral constant-expression of integral or enumeration // type; or // -- the name of a non-type template-parameter; or SourceLocation NonConstantLoc; llvm::APSInt Value; if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_integral_or_enumeral) << ArgType << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } else if (!Arg->isValueDependent() && !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { Diag(NonConstantLoc, diag::err_template_arg_not_ice) << ArgType << Arg->getSourceRange(); return true; } // FIXME: We need some way to more easily get the unqualified form // of the types without going all the way to the // canonical type. if (Context.getCanonicalType(ParamType).getCVRQualifiers()) ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType(); if (Context.getCanonicalType(ArgType).getCVRQualifiers()) ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType(); // Try to convert the argument to the parameter's type. if (ParamType == ArgType) { // Okay: no conversion necessary } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || !ParamType->isEnumeralType()) { // This is an integral promotion or conversion. ImpCastExprToType(Arg, ParamType); } else { // We can't perform this conversion. Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_convertible) << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } QualType IntegerType = Context.getCanonicalType(ParamType); if (const EnumType *Enum = IntegerType->getAsEnumType()) IntegerType = Enum->getDecl()->getIntegerType(); if (!Arg->isValueDependent()) { // Check that an unsigned parameter does not receive a negative // value. if (IntegerType->isUnsignedIntegerType() && (Value.isSigned() && Value.isNegative())) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative) << Value.toString(10) << Param->getType() << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } // Check that we don't overflow the template parameter type. unsigned AllowedBits = Context.getTypeSize(IntegerType); if (Value.getActiveBits() > AllowedBits) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_too_large) << Value.toString(10) << Param->getType() << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } if (Value.getBitWidth() != AllowedBits) Value.extOrTrunc(AllowedBits); Value.setIsSigned(IntegerType->isSignedIntegerType()); } if (Converted) { // Add the value of this argument to the list of converted // arguments. We use the bitwidth and signedness of the template // parameter. if (Arg->isValueDependent()) { // The argument is value-dependent. Create a new // TemplateArgument with the converted expression. Converted->push_back(TemplateArgument(Arg)); return false; } Converted->push_back(TemplateArgument(StartLoc, Value, Context.getCanonicalType(IntegerType))); } return false; } // Handle pointer-to-function, reference-to-function, and // pointer-to-member-function all in (roughly) the same way. if (// -- For a non-type template-parameter of type pointer to // function, only the function-to-pointer conversion (4.3) is // applied. If the template-argument represents a set of // overloaded functions (or a pointer to such), the matching // function is selected from the set (13.4). (ParamType->isPointerType() && ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) || // -- For a non-type template-parameter of type reference to // function, no conversions apply. If the template-argument // represents a set of overloaded functions, the matching // function is selected from the set (13.4). (ParamType->isReferenceType() && ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) || // -- For a non-type template-parameter of type pointer to // member function, no conversions apply. If the // template-argument represents a set of overloaded member // functions, the matching member function is selected from // the set (13.4). (ParamType->isMemberPointerType() && ParamType->getAsMemberPointerType()->getPointeeType() ->isFunctionType())) { if (Context.hasSameUnqualifiedType(ArgType, ParamType.getNonReferenceType())) { // We don't have to do anything: the types already match. } else if (ArgType->isFunctionType() && ParamType->isPointerType()) { ArgType = Context.getPointerType(ArgType); ImpCastExprToType(Arg, ArgType); } else if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) { if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) return true; FixOverloadedFunctionReference(Arg, Fn); ArgType = Arg->getType(); if (ArgType->isFunctionType() && ParamType->isPointerType()) { ArgType = Context.getPointerType(Arg->getType()); ImpCastExprToType(Arg, ArgType); } } if (!Context.hasSameUnqualifiedType(ArgType, ParamType.getNonReferenceType())) { // We can't perform this conversion. Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_convertible) << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } if (ParamType->isMemberPointerType()) { NamedDecl *Member = 0; if (CheckTemplateArgumentPointerToMember(Arg, Member)) return true; if (Converted) Converted->push_back(TemplateArgument(StartLoc, Member)); return false; } NamedDecl *Entity = 0; if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) return true; if (Converted) Converted->push_back(TemplateArgument(StartLoc, Entity)); return false; } if (ParamType->isPointerType()) { // -- for a non-type template-parameter of type pointer to // object, qualification conversions (4.4) and the // array-to-pointer conversion (4.2) are applied. assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() && "Only object pointers allowed here"); if (ArgType->isArrayType()) { ArgType = Context.getArrayDecayedType(ArgType); ImpCastExprToType(Arg, ArgType); } if (IsQualificationConversion(ArgType, ParamType)) { ArgType = ParamType; ImpCastExprToType(Arg, ParamType); } if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) { // We can't perform this conversion. Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_convertible) << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } NamedDecl *Entity = 0; if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) return true; if (Converted) Converted->push_back(TemplateArgument(StartLoc, Entity)); return false; } if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) { // -- For a non-type template-parameter of type reference to // object, no conversions apply. The type referred to by the // reference may be more cv-qualified than the (otherwise // identical) type of the template-argument. The // template-parameter is bound directly to the // template-argument, which must be an lvalue. assert(ParamRefType->getPointeeType()->isObjectType() && "Only object references allowed here"); if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_no_ref_bind) << InstantiatedParamType << Arg->getType() << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } unsigned ParamQuals = Context.getCanonicalType(ParamType).getCVRQualifiers(); unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers(); if ((ParamQuals | ArgQuals) != ParamQuals) { Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_ref_bind_ignores_quals) << InstantiatedParamType << Arg->getType() << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } NamedDecl *Entity = 0; if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) return true; if (Converted) Converted->push_back(TemplateArgument(StartLoc, Entity)); return false; } // -- For a non-type template-parameter of type pointer to data // member, qualification conversions (4.4) are applied. assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { // Types match exactly: nothing more to do here. } else if (IsQualificationConversion(ArgType, ParamType)) { ImpCastExprToType(Arg, ParamType); } else { // We can't perform this conversion. Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_not_convertible) << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); Diag(Param->getLocation(), diag::note_template_param_here); return true; } NamedDecl *Member = 0; if (CheckTemplateArgumentPointerToMember(Arg, Member)) return true; if (Converted) Converted->push_back(TemplateArgument(StartLoc, Member)); return false; } /// \brief Check a template argument against its corresponding /// template template parameter. /// /// This routine implements the semantics of C++ [temp.arg.template]. /// It returns true if an error occurred, and false otherwise. bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, DeclRefExpr *Arg) { assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed"); TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl()); // C++ [temp.arg.template]p1: // A template-argument for a template template-parameter shall be // the name of a class template, expressed as id-expression. Only // primary class templates are considered when matching the // template template argument with the corresponding parameter; // partial specializations are not considered even if their // parameter lists match that of the template template parameter. if (!isa<ClassTemplateDecl>(Template)) { assert(isa<FunctionTemplateDecl>(Template) && "Only function templates are possible here"); Diag(Arg->getSourceRange().getBegin(), diag::note_template_arg_refers_here_func) << Template; } return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), Param->getTemplateParameters(), true, true, Arg->getSourceRange().getBegin()); } /// \brief Determine whether the given template parameter lists are /// equivalent. /// /// \param New The new template parameter list, typically written in the /// source code as part of a new template declaration. /// /// \param Old The old template parameter list, typically found via /// name lookup of the template declared with this template parameter /// list. /// /// \param Complain If true, this routine will produce a diagnostic if /// the template parameter lists are not equivalent. /// /// \param IsTemplateTemplateParm If true, this routine is being /// called to compare the template parameter lists of a template /// template parameter. /// /// \param TemplateArgLoc If this source location is valid, then we /// are actually checking the template parameter list of a template /// argument (New) against the template parameter list of its /// corresponding template template parameter (Old). We produce /// slightly different diagnostics in this scenario. /// /// \returns True if the template parameter lists are equal, false /// otherwise. bool Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, bool IsTemplateTemplateParm, SourceLocation TemplateArgLoc) { if (Old->size() != New->size()) { if (Complain) { unsigned NextDiag = diag::err_template_param_list_different_arity; if (TemplateArgLoc.isValid()) { Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); NextDiag = diag::note_template_param_list_different_arity; } Diag(New->getTemplateLoc(), NextDiag) << (New->size() > Old->size()) << IsTemplateTemplateParm << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) << IsTemplateTemplateParm << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); } return false; } for (TemplateParameterList::iterator OldParm = Old->begin(), OldParmEnd = Old->end(), NewParm = New->begin(); OldParm != OldParmEnd; ++OldParm, ++NewParm) { if ((*OldParm)->getKind() != (*NewParm)->getKind()) { unsigned NextDiag = diag::err_template_param_different_kind; if (TemplateArgLoc.isValid()) { Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); NextDiag = diag::note_template_param_different_kind; } Diag((*NewParm)->getLocation(), NextDiag) << IsTemplateTemplateParm; Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration) << IsTemplateTemplateParm; return false; } if (isa<TemplateTypeParmDecl>(*OldParm)) { // Okay; all template type parameters are equivalent (since we // know we're at the same index). #if 0 // FIXME: Enable this code in debug mode *after* we properly go // through and "instantiate" the template parameter lists of // template template parameters. It's only after this // instantiation that (1) any dependent types within the // template parameter list of the template template parameter // can be checked, and (2) the template type parameter depths // will match up. QualType OldParmType = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm)); QualType NewParmType = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm)); assert(Context.getCanonicalType(OldParmType) == Context.getCanonicalType(NewParmType) && "type parameter mismatch?"); #endif } else if (NonTypeTemplateParmDecl *OldNTTP = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) { // The types of non-type template parameters must agree. NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(*NewParm); if (Context.getCanonicalType(OldNTTP->getType()) != Context.getCanonicalType(NewNTTP->getType())) { if (Complain) { unsigned NextDiag = diag::err_template_nontype_parm_different_type; if (TemplateArgLoc.isValid()) { Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); NextDiag = diag::note_template_nontype_parm_different_type; } Diag(NewNTTP->getLocation(), NextDiag) << NewNTTP->getType() << IsTemplateTemplateParm; Diag(OldNTTP->getLocation(), diag::note_template_nontype_parm_prev_declaration) << OldNTTP->getType(); } return false; } } else { // The template parameter lists of template template // parameters must agree. // FIXME: Could we perform a faster "type" comparison here? assert(isa<TemplateTemplateParmDecl>(*OldParm) && "Only template template parameters handled here"); TemplateTemplateParmDecl *OldTTP = cast<TemplateTemplateParmDecl>(*OldParm); TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(*NewParm); if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), OldTTP->getTemplateParameters(), Complain, /*IsTemplateTemplateParm=*/true, TemplateArgLoc)) return false; } } return true; } /// \brief Check whether a template can be declared within this scope. /// /// If the template declaration is valid in this scope, returns /// false. Otherwise, issues a diagnostic and returns true. bool Sema::CheckTemplateDeclScope(Scope *S, MultiTemplateParamsArg &TemplateParameterLists) { assert(TemplateParameterLists.size() > 0 && "Not a template"); // Find the nearest enclosing declaration scope. while ((S->getFlags() & Scope::DeclScope) == 0 || (S->getFlags() & Scope::TemplateParamScope) != 0) S = S->getParent(); TemplateParameterList *TemplateParams = static_cast<TemplateParameterList*>(*TemplateParameterLists.get()); SourceLocation TemplateLoc = TemplateParams->getTemplateLoc(); SourceRange TemplateRange = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc()); // C++ [temp]p2: // A template-declaration can appear only as a namespace scope or // class scope declaration. DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); while (Ctx && isa<LinkageSpecDecl>(Ctx)) { if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) return Diag(TemplateLoc, diag::err_template_linkage) << TemplateRange; Ctx = Ctx->getParent(); } if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) return false; return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope) << TemplateRange; } /// \brief Check whether a class template specialization in the /// current context is well-formed. /// /// This routine determines whether a class template specialization /// can be declared in the current context (C++ [temp.expl.spec]p2) /// and emits appropriate diagnostics if there was an error. It /// returns true if there was an error that we cannot recover from, /// and false otherwise. bool Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate, ClassTemplateSpecializationDecl *PrevDecl, SourceLocation TemplateNameLoc, SourceRange ScopeSpecifierRange) { // C++ [temp.expl.spec]p2: // An explicit specialization shall be declared in the namespace // of which the template is a member, or, for member templates, in // the namespace of which the enclosing class or enclosing class // template is a member. An explicit specialization of a member // function, member class or static data member of a class // template shall be declared in the namespace of which the class // template is a member. Such a declaration may also be a // definition. If the declaration is not a definition, the // specialization may be defined later in the name- space in which // the explicit specialization was declared, or in a namespace // that encloses the one in which the explicit specialization was // declared. if (CurContext->getLookupContext()->isFunctionOrMethod()) { Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope) << ClassTemplate; return true; } DeclContext *DC = CurContext->getEnclosingNamespaceContext(); DeclContext *TemplateContext = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext(); if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) { // There is no prior declaration of this entity, so this // specialization must be in the same context as the template // itself. if (DC != TemplateContext) { if (isa<TranslationUnitDecl>(TemplateContext)) Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global) << ClassTemplate << ScopeSpecifierRange; else if (isa<NamespaceDecl>(TemplateContext)) Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope) << ClassTemplate << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange; Diag(ClassTemplate->getLocation(), diag::note_template_decl_here); } return false; } // We have a previous declaration of this entity. Make sure that // this redeclaration (or definition) occurs in an enclosing namespace. if (!CurContext->Encloses(TemplateContext)) { if (isa<TranslationUnitDecl>(TemplateContext)) Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope) << ClassTemplate << ScopeSpecifierRange; else if (isa<NamespaceDecl>(TemplateContext)) Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope) << ClassTemplate << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange; Diag(ClassTemplate->getLocation(), diag::note_template_decl_here); } return false; } Sema::DeclResult Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy TemplateD, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation *TemplateArgLocs, SourceLocation RAngleLoc, AttributeList *Attr, MultiTemplateParamsArg TemplateParameterLists) { // Find the class template we're specializing TemplateName Name = TemplateD.getAsVal<TemplateName>(); ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); // Check the validity of the template headers that introduce this // template. // FIXME: Once we have member templates, we'll need to check // C++ [temp.expl.spec]p17-18, where we could have multiple levels of // template<> headers. if (TemplateParameterLists.size() == 0) Diag(KWLoc, diag::err_template_spec_needs_header) << CodeModificationHint::CreateInsertion(KWLoc, "template<> "); else { TemplateParameterList *TemplateParams = static_cast<TemplateParameterList*>(*TemplateParameterLists.get()); if (TemplateParameterLists.size() > 1) { Diag(TemplateParams->getTemplateLoc(), diag::err_template_spec_extra_headers); return true; } if (TemplateParams->size() > 0) { // FIXME: No support for class template partial specialization. Diag(TemplateParams->getTemplateLoc(), diag::unsup_template_partial_spec); return true; } } // Check that the specialization uses the same tag kind as the // original template. TagDecl::TagKind Kind; switch (TagSpec) { default: assert(0 && "Unknown tag type!"); case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; } if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) { Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate << CodeModificationHint::CreateReplacement(KWLoc, ClassTemplate->getTemplatedDecl()->getKindName()); Diag(ClassTemplate->getTemplatedDecl()->getLocation(), diag::note_previous_use); Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); } // Translate the parser's template argument list in our AST format. llvm::SmallVector<TemplateArgument, 16> TemplateArgs; translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); // Check that the template argument list is well-formed for this // template. llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs; if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc, &TemplateArgs[0], TemplateArgs.size(), RAngleLoc, ConvertedTemplateArgs)) return true; assert((ConvertedTemplateArgs.size() == ClassTemplate->getTemplateParameters()->size()) && "Converted template argument list is too short!"); // Find the class template specialization declaration that // corresponds to these arguments. llvm::FoldingSetNodeID ID; ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0], ConvertedTemplateArgs.size()); void *InsertPos = 0; ClassTemplateSpecializationDecl *PrevDecl = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); ClassTemplateSpecializationDecl *Specialization = 0; // Check whether we can declare a class template specialization in // the current scope. if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl, TemplateNameLoc, SS.getRange())) return true; if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { // Since the only prior class template specialization with these // arguments was referenced but not declared, reuse that // declaration node as our own, updating its source location to // reflect our new declaration. Specialization = PrevDecl; Specialization->setLocation(TemplateNameLoc); PrevDecl = 0; } else { // Create a new class template specialization declaration node for // this explicit specialization. Specialization = ClassTemplateSpecializationDecl::Create(Context, ClassTemplate->getDeclContext(), TemplateNameLoc, ClassTemplate, &ConvertedTemplateArgs[0], ConvertedTemplateArgs.size(), PrevDecl); if (PrevDecl) { ClassTemplate->getSpecializations().RemoveNode(PrevDecl); ClassTemplate->getSpecializations().GetOrInsertNode(Specialization); } else { ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos); } } // Note that this is an explicit specialization. Specialization->setSpecializationKind(TSK_ExplicitSpecialization); // Check that this isn't a redefinition of this specialization. if (TK == TK_Definition) { if (RecordDecl *Def = Specialization->getDefinition(Context)) { // FIXME: Should also handle explicit specialization after // implicit instantiation with a special diagnostic. SourceRange Range(TemplateNameLoc, RAngleLoc); Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range; Diag(Def->getLocation(), diag::note_previous_definition); Specialization->setInvalidDecl(); return true; } } // Build the fully-sugared type for this class template // specialization as the user wrote in the specialization // itself. This means that we'll pretty-print the type retrieved // from the specialization's declaration the way that the user // actually wrote the specialization, rather than formatting the // name based on the "canonical" representation used to store the // template arguments in the specialization. QualType WrittenTy = Context.getTemplateSpecializationType(Name, &TemplateArgs[0], TemplateArgs.size(), Context.getTypeDeclType(Specialization)); Specialization->setTypeAsWritten(WrittenTy); TemplateArgsIn.release(); // C++ [temp.expl.spec]p9: // A template explicit specialization is in the scope of the // namespace in which the template was defined. // // We actually implement this paragraph where we set the semantic // context (in the creation of the ClassTemplateSpecializationDecl), // but we also maintain the lexical context where the actual // definition occurs. Specialization->setLexicalDeclContext(CurContext); // We may be starting the definition of this specialization. if (TK == TK_Definition) Specialization->startDefinition(); // Add the specialization into its lexical context, so that it can // be seen when iterating through the list of declarations in that // context. However, specializations are not found by name lookup. CurContext->addDecl(Context, Specialization); return DeclPtrTy::make(Specialization); } Sema::TypeResult Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc) { NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); if (!NNS) return true; QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc)); if (T.isNull()) return true; return T.getAsOpaquePtr(); } Sema::TypeResult Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TypeTy *Ty) { QualType T = QualType::getFromOpaquePtr(Ty); NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); const TemplateSpecializationType *TemplateId = T->getAsTemplateSpecializationType(); assert(TemplateId && "Expected a template specialization type"); if (NNS->isDependent()) return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr(); return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr(); } /// \brief Build the type that describes a C++ typename specifier, /// e.g., "typename T::type". QualType Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II, SourceRange Range) { if (NNS->isDependent()) // FIXME: member of the current instantiation! return Context.getTypenameType(NNS, &II); CXXScopeSpec SS; SS.setScopeRep(NNS); SS.setRange(Range); if (RequireCompleteDeclContext(SS)) return QualType(); DeclContext *Ctx = computeDeclContext(SS); assert(Ctx && "No declaration context?"); DeclarationName Name(&II); LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName, false); unsigned DiagID = 0; Decl *Referenced = 0; switch (Result.getKind()) { case LookupResult::NotFound: if (Ctx->isTranslationUnit()) DiagID = diag::err_typename_nested_not_found_global; else DiagID = diag::err_typename_nested_not_found; break; case LookupResult::Found: if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) { // We found a type. Build a QualifiedNameType, since the // typename-specifier was just sugar. FIXME: Tell // QualifiedNameType that it has a "typename" prefix. return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type)); } DiagID = diag::err_typename_nested_not_type; Referenced = Result.getAsDecl(); break; case LookupResult::FoundOverloaded: DiagID = diag::err_typename_nested_not_type; Referenced = *Result.begin(); break; case LookupResult::AmbiguousBaseSubobjectTypes: case LookupResult::AmbiguousBaseSubobjects: case LookupResult::AmbiguousReference: DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range); return QualType(); } // If we get here, it's because name lookup did not find a // type. Emit an appropriate diagnostic and return an error. if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx)) Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx; else Diag(Range.getEnd(), DiagID) << Range << Name; if (Referenced) Diag(Referenced->getLocation(), diag::note_typename_refers_here) << Name; return QualType(); } <file_sep>/test/CodeGen/union-init.c // RUN: clang-cc -emit-llvm < %s -o - // A nice and complicated initialization example with unions from Python typedef int Py_ssize_t; typedef union _gc_head { struct { union _gc_head *gc_next; union _gc_head *gc_prev; Py_ssize_t gc_refs; } gc; long double dummy; /* force worst-case alignment */ } PyGC_Head; struct gc_generation { PyGC_Head head; int threshold; /* collection threshold */ int count; /* count of allocations or collections of younger generations */ }; #define NUM_GENERATIONS 3 #define GEN_HEAD(n) (&generations[n].head) /* linked lists of container objects */ struct gc_generation generations[NUM_GENERATIONS] = { /* PyGC_Head, threshold, count */ {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0}, {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0}, {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0}, }; <file_sep>/test/CodeGen/switch.c // RUN: clang-cc %s -emit-llvm-bc -o - | opt -std-compile-opts -disable-output int foo(int i) { int j = 0; switch (i) { case -1: j = 1; break; case 1 : j = 2; break; case 2: j = 3; break; default: j = 42; break; } j = j + 1; return j; } int foo2(int i) { int j = 0; switch (i) { case 1 : j = 2; break; case 2 ... 10: j = 3; break; default: j = 42; break; } j = j + 1; return j; } int foo3(int i) { int j = 0; switch (i) { default: j = 42; break; case 111: j = 111; break; case 0 ... 100: j = 1; break; case 222: j = 222; break; } return j; } int foo4(int i) { int j = 0; switch (i) { case 111: j = 111; break; case 0 ... 100: j = 1; break; case 222: j = 222; break; default: j = 42; break; case 501 ... 600: j = 5; break; } return j; } void foo5(){ switch(0){ default: if (0) { } } } void foo6(){ switch(0){ } } void foo7(){ switch(0){ foo7(); } } <file_sep>/test/PCH/line-directive.c // Test this without pch. // RUN: clang-cc -include %S/line-directive.h -fsyntax-only %s 2>&1|grep "25:5" // Test with pch. // RUN: clang-cc -emit-pch -o %t %S/line-directive.h && // RUN: clang-cc -include-pch %t -fsyntax-only %s 2>&1|grep "25:5" double x; // expected-error{{redefinition of 'x' with a different type}} // expected-note{{previous definition is here}} <file_sep>/lib/Driver/Driver.cpp //===--- Driver.cpp - Clang GCC Compatible Driver -----------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/Driver.h" #include "clang/Driver/Action.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/HostInfo.h" #include "clang/Driver/Job.h" #include "clang/Driver/Option.h" #include "clang/Driver/Options.h" #include "clang/Driver/Tool.h" #include "clang/Driver/ToolChain.h" #include "clang/Driver/Types.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" #include "InputInfo.h" #include <map> using namespace clang::driver; using namespace clang; Driver::Driver(const char *_Name, const char *_Dir, const char *_DefaultHostTriple, const char *_DefaultImageName, Diagnostic &_Diags) : Opts(new OptTable()), Diags(_Diags), Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple), DefaultImageName(_DefaultImageName), Host(0), CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false), CCCGenericGCCName("gcc"), CCCUseClang(true), CCCUseClangCXX(false), CCCUseClangCPP(true), SuppressMissingInputWarning(false) { // Only use clang on i386 and x86_64 by default. CCCClangArchs.insert("i386"); CCCClangArchs.insert("x86_64"); } Driver::~Driver() { delete Opts; delete Host; } InputArgList *Driver::ParseArgStrings(const char **ArgBegin, const char **ArgEnd) { llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); InputArgList *Args = new InputArgList(ArgBegin, ArgEnd); // FIXME: Handle '@' args (or at least error on them). unsigned Index = 0, End = ArgEnd - ArgBegin; while (Index < End) { // gcc's handling of empty arguments doesn't make // sense, but this is not a common use case. :) // // We just ignore them here (note that other things may // still take them as arguments). if (Args->getArgString(Index)[0] == '\0') { ++Index; continue; } unsigned Prev = Index; Arg *A = getOpts().ParseOneArg(*Args, Index); assert(Index > Prev && "Parser failed to consume argument."); // Check for missing argument error. if (!A) { assert(Index >= End && "Unexpected parser error."); Diag(clang::diag::err_drv_missing_argument) << Args->getArgString(Prev) << (Index - Prev - 1); break; } if (A->getOption().isUnsupported()) { Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); continue; } Args->append(A); } return Args; } Compilation *Driver::BuildCompilation(int argc, const char **argv) { llvm::PrettyStackTraceString CrashInfo("Compilation construction"); // FIXME: Handle environment options which effect driver behavior, // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH, // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS. // FIXME: What are we going to do with -V and -b? // FIXME: This stuff needs to go into the Compilation, not the // driver. bool CCCPrintOptions = false, CCCPrintActions = false; const char **Start = argv + 1, **End = argv + argc; const char *HostTriple = DefaultHostTriple.c_str(); // Read -ccc args. // // FIXME: We need to figure out where this behavior should // live. Most of it should be outside in the client; the parts that // aren't should have proper options, either by introducing new ones // or by overloading gcc ones like -V or -b. for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) { const char *Opt = *Start + 5; if (!strcmp(Opt, "print-options")) { CCCPrintOptions = true; } else if (!strcmp(Opt, "print-phases")) { CCCPrintActions = true; } else if (!strcmp(Opt, "print-bindings")) { CCCPrintBindings = true; } else if (!strcmp(Opt, "cxx")) { CCCIsCXX = true; } else if (!strcmp(Opt, "echo")) { CCCEcho = true; } else if (!strcmp(Opt, "gcc-name")) { assert(Start+1 < End && "FIXME: -ccc- argument handling."); CCCGenericGCCName = *++Start; } else if (!strcmp(Opt, "clang-cxx")) { CCCUseClangCXX = true; } else if (!strcmp(Opt, "no-clang")) { CCCUseClang = false; } else if (!strcmp(Opt, "no-clang-cpp")) { CCCUseClangCPP = false; } else if (!strcmp(Opt, "clang-archs")) { assert(Start+1 < End && "FIXME: -ccc- argument handling."); const char *Cur = *++Start; CCCClangArchs.clear(); for (;;) { const char *Next = strchr(Cur, ','); if (Next) { if (Cur != Next) CCCClangArchs.insert(std::string(Cur, Next)); Cur = Next + 1; } else { if (*Cur != '\0') CCCClangArchs.insert(std::string(Cur)); break; } } } else if (!strcmp(Opt, "host-triple")) { assert(Start+1 < End && "FIXME: -ccc- argument handling."); HostTriple = *++Start; } else { // FIXME: Error handling. llvm::errs() << "invalid option: " << *Start << "\n"; exit(1); } } InputArgList *Args = ParseArgStrings(Start, End); Host = GetHostInfo(HostTriple); // The compilation takes ownership of Args. Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args); // FIXME: This behavior shouldn't be here. if (CCCPrintOptions) { PrintOptions(C->getArgs()); return C; } if (!HandleImmediateArgs(*C)) return C; // Construct the list of abstract actions to perform for this // compilation. We avoid passing a Compilation here simply to // enforce the abstraction that pipelining is not host or toolchain // dependent (other than the driver driver test). if (Host->useDriverDriver()) BuildUniversalActions(C->getArgs(), C->getActions()); else BuildActions(C->getArgs(), C->getActions()); if (CCCPrintActions) { PrintActions(*C); return C; } BuildJobs(*C); return C; } void Driver::PrintOptions(const ArgList &Args) const { unsigned i = 0; for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it, ++i) { Arg *A = *it; llvm::errs() << "Option " << i << " - " << "Name: \"" << A->getOption().getName() << "\", " << "Values: {"; for (unsigned j = 0; j < A->getNumValues(); ++j) { if (j) llvm::errs() << ", "; llvm::errs() << '"' << A->getValue(Args, j) << '"'; } llvm::errs() << "}\n"; } } static std::string getOptionHelpName(const OptTable &Opts, options::ID Id) { std::string Name = Opts.getOptionName(Id); // Add metavar, if used. switch (Opts.getOptionKind(Id)) { case Option::GroupClass: case Option::InputClass: case Option::UnknownClass: assert(0 && "Invalid option with help text."); case Option::MultiArgClass: case Option::JoinedAndSeparateClass: assert(0 && "Cannot print metavar for this kind of option."); case Option::FlagClass: break; case Option::SeparateClass: case Option::JoinedOrSeparateClass: Name += ' '; // FALLTHROUGH case Option::JoinedClass: case Option::CommaJoinedClass: Name += Opts.getOptionMetaVar(Id); break; } return Name; } void Driver::PrintHelp(bool ShowHidden) const { llvm::raw_ostream &OS = llvm::outs(); OS << "OVERVIEW: clang \"gcc-compatible\" driver\n"; OS << '\n'; OS << "USAGE: " << Name << " [options] <input files>\n"; OS << '\n'; OS << "OPTIONS:\n"; // Render help text into (option, help) pairs. std::vector< std::pair<std::string, const char*> > OptionHelp; for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) { options::ID Id = (options::ID) i; if (const char *Text = getOpts().getOptionHelpText(Id)) OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id), Text)); } if (ShowHidden) { OptionHelp.push_back(std::make_pair("\nDRIVER OPTIONS:","")); OptionHelp.push_back(std::make_pair("-ccc-cxx", "Act as a C++ driver")); OptionHelp.push_back(std::make_pair("-ccc-gcc-name", "Name for native GCC compiler")); OptionHelp.push_back(std::make_pair("-ccc-clang-cxx", "Use the clang compiler for C++")); OptionHelp.push_back(std::make_pair("-ccc-no-clang", "Never use the clang compiler")); OptionHelp.push_back(std::make_pair("-ccc-no-clang-cpp", "Never use the clang preprocessor")); OptionHelp.push_back(std::make_pair("-ccc-clang-archs", "Comma separate list of architectures " "to use the clang compiler for")); OptionHelp.push_back(std::make_pair("\nDEBUG/DEVELOPMENT OPTIONS:","")); OptionHelp.push_back(std::make_pair("-ccc-host-triple", "Simulate running on the given target")); OptionHelp.push_back(std::make_pair("-ccc-print-options", "Dump parsed command line arguments")); OptionHelp.push_back(std::make_pair("-ccc-print-phases", "Dump list of actions to perform")); OptionHelp.push_back(std::make_pair("-ccc-print-bindings", "Show bindings of tools to actions")); OptionHelp.push_back(std::make_pair("CCC_ADD_ARGS", "(ENVIRONMENT VARIABLE) Comma separated list of " "arguments to prepend to the command line")); } // Find the maximum option length. unsigned OptionFieldWidth = 0; for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { // Skip titles. if (!OptionHelp[i].second) continue; // Limit the amount of padding we are willing to give up for // alignment. unsigned Length = OptionHelp[i].first.size(); if (Length <= 23) OptionFieldWidth = std::max(OptionFieldWidth, Length); } for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { const std::string &Option = OptionHelp[i].first; OS << " " << Option; for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j) OS << ' '; OS << ' ' << OptionHelp[i].second << '\n'; } OS.flush(); } void Driver::PrintVersion(const Compilation &C) const { static char buf[] = "$URL$"; char *zap = strstr(buf, "/lib/Driver"); if (zap) *zap = 0; zap = strstr(buf, "/clang/tools/clang"); if (zap) *zap = 0; const char *vers = buf+6; // FIXME: Add cmake support and remove #ifdef #ifdef SVN_REVISION const char *revision = SVN_REVISION; #else const char *revision = ""; #endif // FIXME: The following handlers should use a callback mechanism, we // don't know what the client would like to do. // FIXME: Do not hardcode clang version. llvm::errs() << "clang version 1.0 (" << vers << " " << revision << ")" << "\n"; const ToolChain &TC = C.getDefaultToolChain(); llvm::errs() << "Target: " << TC.getTripleString() << '\n'; } bool Driver::HandleImmediateArgs(const Compilation &C) { // The order these options are handled in in gcc is all over the // place, but we don't expect inconsistencies w.r.t. that to matter // in practice. if (C.getArgs().hasArg(options::OPT_dumpversion)) { // FIXME: Do not hardcode clang version. llvm::outs() << "1.0\n"; return false; } if (C.getArgs().hasArg(options::OPT__help) || C.getArgs().hasArg(options::OPT__help_hidden)) { PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); return false; } if (C.getArgs().hasArg(options::OPT__version)) { PrintVersion(C); return false; } if (C.getArgs().hasArg(options::OPT_v) || C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { PrintVersion(C); SuppressMissingInputWarning = true; } const ToolChain &TC = C.getDefaultToolChain(); if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { llvm::outs() << "programs: ="; for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), ie = TC.getProgramPaths().end(); it != ie; ++it) { if (it != TC.getProgramPaths().begin()) llvm::outs() << ':'; llvm::outs() << *it; } llvm::outs() << "\n"; llvm::outs() << "libraries: ="; for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), ie = TC.getFilePaths().end(); it != ie; ++it) { if (it != TC.getFilePaths().begin()) llvm::outs() << ':'; llvm::outs() << *it; } llvm::outs() << "\n"; return false; } // FIXME: The following handlers should use a callback mechanism, we // don't know what the client would like to do. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString() << "\n"; return false; } if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString() << "\n"; return false; } if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { llvm::outs() << GetFilePath("libgcc.a", TC).toString() << "\n"; return false; } return true; } static unsigned PrintActions1(const Compilation &C, Action *A, std::map<Action*, unsigned> &Ids) { if (Ids.count(A)) return Ids[A]; std::string str; llvm::raw_string_ostream os(str); os << Action::getClassName(A->getKind()) << ", "; if (InputAction *IA = dyn_cast<InputAction>(A)) { os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\""; } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { os << '"' << (BIA->getArchName() ? BIA->getArchName() : C.getDefaultToolChain().getArchName()) << '"' << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; } else { os << "{"; for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { os << PrintActions1(C, *it, Ids); ++it; if (it != ie) os << ", "; } os << "}"; } unsigned Id = Ids.size(); Ids[A] = Id; llvm::errs() << Id << ": " << os.str() << ", " << types::getTypeName(A->getType()) << "\n"; return Id; } void Driver::PrintActions(const Compilation &C) const { std::map<Action*, unsigned> Ids; for (ActionList::const_iterator it = C.getActions().begin(), ie = C.getActions().end(); it != ie; ++it) PrintActions1(C, *it, Ids); } void Driver::BuildUniversalActions(const ArgList &Args, ActionList &Actions) const { llvm::PrettyStackTraceString CrashInfo("Building actions for universal build"); // Collect the list of architectures. Duplicates are allowed, but // should only be handled once (in the order seen). llvm::StringSet<> ArchNames; llvm::SmallVector<const char *, 4> Archs; for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { Arg *A = *it; if (A->getOption().getId() == options::OPT_arch) { const char *Name = A->getValue(Args); // FIXME: We need to handle canonicalization of the specified // arch? A->claim(); if (ArchNames.insert(Name)) Archs.push_back(Name); } } // When there is no explicit arch for this platform, make sure we // still bind the architecture (to the default) so that -Xarch_ is // handled correctly. if (!Archs.size()) Archs.push_back(0); // FIXME: We killed off some others but these aren't yet detected in // a functional manner. If we added information to jobs about which // "auxiliary" files they wrote then we could detect the conflict // these cause downstream. if (Archs.size() > 1) { // No recovery needed, the point of this is just to prevent // overwriting the same files. if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) << A->getAsString(Args); } ActionList SingleActions; BuildActions(Args, SingleActions); // Add in arch binding and lipo (if necessary) for every top level // action. for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { Action *Act = SingleActions[i]; // Make sure we can lipo this kind of output. If not (and it is an // actual output) then we disallow, since we can't create an // output file with the right name without overwriting it. We // could remove this oddity by just changing the output names to // include the arch, which would also fix // -save-temps. Compatibility wins for now. if (Archs.size() > 1 && !types::canLipoType(Act->getType())) Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) << types::getTypeName(Act->getType()); ActionList Inputs; for (unsigned i = 0, e = Archs.size(); i != e; ++i) Inputs.push_back(new BindArchAction(Act, Archs[i])); // Lipo if necessary, We do it this way because we need to set the // arch flag so that -Xarch_ gets overwritten. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) Actions.append(Inputs.begin(), Inputs.end()); else Actions.push_back(new LipoJobAction(Inputs, Act->getType())); } } void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const { llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); // Start by constructing the list of inputs and their types. // Track the current user specified (-x) input. We also explicitly // track the argument used to set the type; we only want to claim // the type when we actually use it, so we warn about unused -x // arguments. types::ID InputType = types::TY_Nothing; Arg *InputTypeArg = 0; llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs; for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { Arg *A = *it; if (isa<InputOption>(A->getOption())) { const char *Value = A->getValue(Args); types::ID Ty = types::TY_INVALID; // Infer the input type if necessary. if (InputType == types::TY_Nothing) { // If there was an explicit arg for this, claim it. if (InputTypeArg) InputTypeArg->claim(); // stdin must be handled specially. if (memcmp(Value, "-", 2) == 0) { // If running with -E, treat as a C input (this changes the // builtin macros, for example). This may be overridden by // -ObjC below. // // Otherwise emit an error but still use a valid type to // avoid spurious errors (e.g., no inputs). if (!Args.hasArg(options::OPT_E, false)) Diag(clang::diag::err_drv_unknown_stdin_type); Ty = types::TY_C; } else { // Otherwise lookup by extension, and fallback to ObjectType // if not found. We use a host hook here because Darwin at // least has its own idea of what .s is. if (const char *Ext = strrchr(Value, '.')) Ty = Host->lookupTypeForExtension(Ext + 1); if (Ty == types::TY_INVALID) Ty = types::TY_Object; } // -ObjC and -ObjC++ override the default language, but only // -for "source files". We just treat everything that isn't a // -linker input as a source file. // // FIXME: Clean this up if we move the phase sequence into the // type. if (Ty != types::TY_Object) { if (Args.hasArg(options::OPT_ObjC)) Ty = types::TY_ObjC; else if (Args.hasArg(options::OPT_ObjCXX)) Ty = types::TY_ObjCXX; } } else { assert(InputTypeArg && "InputType set w/o InputTypeArg"); InputTypeArg->claim(); Ty = InputType; } // Check that the file exists. It isn't clear this is worth // doing, since the tool presumably does this anyway, and this // just adds an extra stat to the equation, but this is gcc // compatible. if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists()) Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args); else Inputs.push_back(std::make_pair(Ty, A)); } else if (A->getOption().isLinkerInput()) { // Just treat as object type, we could make a special type for // this if necessary. Inputs.push_back(std::make_pair(types::TY_Object, A)); } else if (A->getOption().getId() == options::OPT_x) { InputTypeArg = A; InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args)); // Follow gcc behavior and treat as linker input for invalid -x // options. Its not clear why we shouldn't just revert to // unknown; but this isn't very important, we might as well be // bug comatible. if (!InputType) { Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args); InputType = types::TY_Object; } } } if (!SuppressMissingInputWarning && Inputs.empty()) { Diag(clang::diag::err_drv_no_input_files); return; } // Determine which compilation mode we are in. We look for options // which affect the phase, starting with the earliest phases, and // record which option we used to determine the final phase. Arg *FinalPhaseArg = 0; phases::ID FinalPhase; // -{E,M,MM} only run the preprocessor. if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) || (FinalPhaseArg = Args.getLastArg(options::OPT_M)) || (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) { FinalPhase = phases::Preprocess; // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler. } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) || (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) || (FinalPhaseArg = Args.getLastArg(options::OPT_S))) { FinalPhase = phases::Compile; // -c only runs up to the assembler. } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) { FinalPhase = phases::Assemble; // Otherwise do everything. } else FinalPhase = phases::Link; // Reject -Z* at the top level, these options should never have been // exposed by gcc. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); // Construct the actions to perform. ActionList LinkerInputs; for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { types::ID InputType = Inputs[i].first; const Arg *InputArg = Inputs[i].second; unsigned NumSteps = types::getNumCompilationPhases(InputType); assert(NumSteps && "Invalid number of steps!"); // If the first step comes after the final phase we are doing as // part of this compilation, warn the user about it. phases::ID InitialPhase = types::getCompilationPhase(InputType, 0); if (InitialPhase > FinalPhase) { // Claim here to avoid the more general unused warning. InputArg->claim(); Diag(clang::diag::warn_drv_input_file_unused) << InputArg->getAsString(Args) << getPhaseName(InitialPhase) << FinalPhaseArg->getOption().getName(); continue; } // Build the pipeline for this file. Action *Current = new InputAction(*InputArg, InputType); for (unsigned i = 0; i != NumSteps; ++i) { phases::ID Phase = types::getCompilationPhase(InputType, i); // We are done if this step is past what the user requested. if (Phase > FinalPhase) break; // Queue linker inputs. if (Phase == phases::Link) { assert(i + 1 == NumSteps && "linking must be final compilation step."); LinkerInputs.push_back(Current); Current = 0; break; } // Some types skip the assembler phase (e.g., llvm-bc), but we // can't encode this in the steps because the intermediate type // depends on arguments. Just special case here. if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) continue; // Otherwise construct the appropriate action. Current = ConstructPhaseAction(Args, Phase, Current); if (Current->getType() == types::TY_Nothing) break; } // If we ended with something, add to the output list. if (Current) Actions.push_back(Current); } // Add a link action if necessary. if (!LinkerInputs.empty()) Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); } Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, Action *Input) const { llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); // Build the appropriate action. switch (Phase) { case phases::Link: assert(0 && "link action invalid here."); case phases::Preprocess: { types::ID OutputTy; // -{M, MM} alter the output type. if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) { OutputTy = types::TY_Dependencies; } else { OutputTy = types::getPreprocessedType(Input->getType()); assert(OutputTy != types::TY_INVALID && "Cannot preprocess this input type!"); } return new PreprocessJobAction(Input, OutputTy); } case phases::Precompile: return new PrecompileJobAction(Input, types::TY_PCH); case phases::Compile: { if (Args.hasArg(options::OPT_fsyntax_only)) { return new CompileJobAction(Input, types::TY_Nothing); } else if (Args.hasArg(options::OPT__analyze)) { return new AnalyzeJobAction(Input, types::TY_Plist); } else if (Args.hasArg(options::OPT_emit_llvm) || Args.hasArg(options::OPT_flto) || Args.hasArg(options::OPT_O4)) { types::ID Output = Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC; return new CompileJobAction(Input, Output); } else { return new CompileJobAction(Input, types::TY_PP_Asm); } } case phases::Assemble: return new AssembleJobAction(Input, types::TY_Object); } assert(0 && "invalid phase in ConstructPhaseAction"); return 0; } void Driver::BuildJobs(Compilation &C) const { llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps); bool UsePipes = C.getArgs().hasArg(options::OPT_pipe); // FIXME: Pipes are forcibly disabled until we support executing // them. if (!CCCPrintBindings) UsePipes = false; // -save-temps inhibits pipes. if (SaveTemps && UsePipes) { Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps); UsePipes = true; } Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); // It is an error to provide a -o option if we are making multiple // output files. if (FinalOutput) { unsigned NumOutputs = 0; for (ActionList::const_iterator it = C.getActions().begin(), ie = C.getActions().end(); it != ie; ++it) if ((*it)->getType() != types::TY_Nothing) ++NumOutputs; if (NumOutputs > 1) { Diag(clang::diag::err_drv_output_argument_with_multiple_files); FinalOutput = 0; } } for (ActionList::const_iterator it = C.getActions().begin(), ie = C.getActions().end(); it != ie; ++it) { Action *A = *it; // If we are linking an image for multiple archs then the linker // wants -arch_multiple and -final_output <final image // name>. Unfortunately, this doesn't fit in cleanly because we // have to pass this information down. // // FIXME: This is a hack; find a cleaner way to integrate this // into the process. const char *LinkingOutput = 0; if (isa<LipoJobAction>(A)) { if (FinalOutput) LinkingOutput = FinalOutput->getValue(C.getArgs()); else LinkingOutput = DefaultImageName.c_str(); } InputInfo II; BuildJobsForAction(C, A, &C.getDefaultToolChain(), /*CanAcceptPipe*/ true, /*AtTopLevel*/ true, /*LinkingOutput*/ LinkingOutput, II); } // If the user passed -Qunused-arguments or there were errors, don't // warn about any unused arguments. if (Diags.getNumErrors() || C.getArgs().hasArg(options::OPT_Qunused_arguments)) return; // Claim -### here. (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); it != ie; ++it) { Arg *A = *it; // FIXME: It would be nice to be able to send the argument to the // Diagnostic, so that extra values, position, and so on could be // printed. if (!A->isClaimed()) { if (A->getOption().hasNoArgumentUnused()) continue; // Suppress the warning automatically if this is just a flag, // and it is an instance of an argument we already claimed. const Option &Opt = A->getOption(); if (isa<FlagOption>(Opt)) { bool DuplicateClaimed = false; // FIXME: Use iterator. for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); it != ie; ++it) { if ((*it)->isClaimed() && (*it)->getOption().matches(Opt.getId())) { DuplicateClaimed = true; break; } } if (DuplicateClaimed) continue; } Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(C.getArgs()); } } } void Driver::BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC, bool CanAcceptPipe, bool AtTopLevel, const char *LinkingOutput, InputInfo &Result) const { llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action"); bool UsePipes = C.getArgs().hasArg(options::OPT_pipe); // FIXME: Pipes are forcibly disabled until we support executing // them. if (!CCCPrintBindings) UsePipes = false; if (const InputAction *IA = dyn_cast<InputAction>(A)) { // FIXME: It would be nice to not claim this here; maybe the old // scheme of just using Args was better? const Arg &Input = IA->getInputArg(); Input.claim(); if (isa<PositionalArg>(Input)) { const char *Name = Input.getValue(C.getArgs()); Result = InputInfo(Name, A->getType(), Name); } else Result = InputInfo(&Input, A->getType(), ""); return; } if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { const char *ArchName = BAA->getArchName(); if (!ArchName) ArchName = C.getDefaultToolChain().getArchName().c_str(); BuildJobsForAction(C, *BAA->begin(), Host->getToolChain(C.getArgs(), ArchName), CanAcceptPipe, AtTopLevel, LinkingOutput, Result); return; } const JobAction *JA = cast<JobAction>(A); const Tool &T = TC->SelectTool(C, *JA); // See if we should use an integrated preprocessor. We do so when we // have exactly one input, since this is the only use case we care // about (irrelevant since we don't support combine yet). bool UseIntegratedCPP = false; const ActionList *Inputs = &A->getInputs(); if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) { if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) && !C.getArgs().hasArg(options::OPT_traditional_cpp) && !C.getArgs().hasArg(options::OPT_save_temps) && T.hasIntegratedCPP()) { UseIntegratedCPP = true; Inputs = &(*Inputs)[0]->getInputs(); } } // Only use pipes when there is exactly one input. bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput(); InputInfoList InputInfos; for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); it != ie; ++it) { InputInfo II; BuildJobsForAction(C, *it, TC, TryToUsePipeInput, /*AtTopLevel*/false, LinkingOutput, II); InputInfos.push_back(II); } // Determine if we should output to a pipe. bool OutputToPipe = false; if (CanAcceptPipe && T.canPipeOutput()) { // Some actions default to writing to a pipe if they are the top // level phase and there was no user override. // // FIXME: Is there a better way to handle this? if (AtTopLevel) { if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o)) OutputToPipe = true; } else if (UsePipes) OutputToPipe = true; } // Figure out where to put the job (pipes). Job *Dest = &C.getJobs(); if (InputInfos[0].isPipe()) { assert(TryToUsePipeInput && "Unrequested pipe!"); assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs."); Dest = &InputInfos[0].getPipe(); } // Always use the first input as the base input. const char *BaseInput = InputInfos[0].getBaseInput(); // Determine the place to write output to (nothing, pipe, or // filename) and where to put the new job. if (JA->getType() == types::TY_Nothing) { Result = InputInfo(A->getType(), BaseInput); } else if (OutputToPipe) { // Append to current piped job or create a new one as appropriate. PipedJob *PJ = dyn_cast<PipedJob>(Dest); if (!PJ) { PJ = new PipedJob(); // FIXME: Temporary hack so that -ccc-print-bindings work until // we have pipe support. Please remove later. if (!CCCPrintBindings) cast<JobList>(Dest)->addJob(PJ); Dest = PJ; } Result = InputInfo(PJ, A->getType(), BaseInput); } else { Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel), A->getType(), BaseInput); } if (CCCPrintBindings) { llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"' << " - \"" << T.getName() << "\", inputs: ["; for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { llvm::errs() << InputInfos[i].getAsString(); if (i + 1 != e) llvm::errs() << ", "; } llvm::errs() << "], output: " << Result.getAsString() << "\n"; } else { T.ConstructJob(C, *JA, *Dest, Result, InputInfos, C.getArgsForToolChain(TC), LinkingOutput); } } const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, const char *BaseInput, bool AtTopLevel) const { llvm::PrettyStackTraceString CrashInfo("Computing output path"); // Output to a user requested destination? if (AtTopLevel) { if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) return C.addResultFile(FinalOutput->getValue(C.getArgs())); } // Output to a temporary file? if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) { std::string TmpName = GetTemporaryPath(types::getTypeTempSuffix(JA.getType())); return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); } llvm::sys::Path BasePath(BaseInput); std::string BaseName(BasePath.getLast()); // Determine what the derived output name should be. const char *NamedOutput; if (JA.getType() == types::TY_Image) { NamedOutput = DefaultImageName.c_str(); } else { const char *Suffix = types::getTypeTempSuffix(JA.getType()); assert(Suffix && "All types used for output should have a suffix."); std::string::size_type End = std::string::npos; if (!types::appendSuffixForType(JA.getType())) End = BaseName.rfind('.'); std::string Suffixed(BaseName.substr(0, End)); Suffixed += '.'; Suffixed += Suffix; NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); } // As an annoying special case, PCH generation doesn't strip the // pathname. if (JA.getType() == types::TY_PCH) { BasePath.eraseComponent(); if (BasePath.isEmpty()) BasePath = NamedOutput; else BasePath.appendComponent(NamedOutput); return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str())); } else { return C.addResultFile(NamedOutput); } } llvm::sys::Path Driver::GetFilePath(const char *Name, const ToolChain &TC) const { const ToolChain::path_list &List = TC.getFilePaths(); for (ToolChain::path_list::const_iterator it = List.begin(), ie = List.end(); it != ie; ++it) { llvm::sys::Path P(*it); P.appendComponent(Name); if (P.exists()) return P; } return llvm::sys::Path(Name); } llvm::sys::Path Driver::GetProgramPath(const char *Name, const ToolChain &TC, bool WantFile) const { const ToolChain::path_list &List = TC.getProgramPaths(); for (ToolChain::path_list::const_iterator it = List.begin(), ie = List.end(); it != ie; ++it) { llvm::sys::Path P(*it); P.appendComponent(Name); if (WantFile ? P.exists() : P.canExecute()) return P; } // If all else failed, search the path. llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name)); if (!P.empty()) return P; return llvm::sys::Path(Name); } std::string Driver::GetTemporaryPath(const char *Suffix) const { // FIXME: This is lame; sys::Path should provide this function (in // particular, it should know how to find the temporary files dir). std::string Error; llvm::sys::Path P("/tmp/cc"); if (P.makeUnique(false, &Error)) { Diag(clang::diag::err_drv_unable_to_make_temp) << Error; return ""; } // FIXME: Grumble, makeUnique sometimes leaves the file around!? // PR3837. P.eraseFromDisk(false, 0); P.appendSuffix(Suffix); return P.toString(); } const HostInfo *Driver::GetHostInfo(const char *Triple) const { llvm::PrettyStackTraceString CrashInfo("Constructing host"); // Dice into arch, platform, and OS. This matches // arch,platform,os = '(.*?)-(.*?)-(.*?)' // and missing fields are left empty. std::string Arch, Platform, OS; if (const char *ArchEnd = strchr(Triple, '-')) { Arch = std::string(Triple, ArchEnd); if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) { Platform = std::string(ArchEnd+1, PlatformEnd); OS = PlatformEnd+1; } else Platform = ArchEnd+1; } else Arch = Triple; // Normalize Arch a bit. // // FIXME: This is very incomplete. if (Arch == "i686") Arch = "i386"; else if (Arch == "amd64") Arch = "x86_64"; else if (Arch == "ppc" || Arch == "Power Macintosh") Arch = "powerpc"; else if (Arch == "ppc64") Arch = "powerpc64"; if (memcmp(&OS[0], "darwin", 6) == 0) return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(), OS.c_str()); if (memcmp(&OS[0], "freebsd", 7) == 0) return createFreeBSDHostInfo(*this, Arch.c_str(), Platform.c_str(), OS.c_str()); return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(), OS.c_str()); } bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, const std::string &ArchNameStr) const { // FIXME: Remove this hack. const char *ArchName = ArchNameStr.c_str(); if (ArchNameStr == "powerpc") ArchName = "ppc"; else if (ArchNameStr == "powerpc64") ArchName = "ppc64"; // Check if user requested no clang, or clang doesn't understand // this type (we only handle single inputs for now). if (!CCCUseClang || JA.size() != 1 || !types::isAcceptedByClang((*JA.begin())->getType())) return false; // Otherwise make sure this is an action clang understands. if (isa<PreprocessJobAction>(JA)) { if (!CCCUseClangCPP) { Diag(clang::diag::warn_drv_not_using_clang_cpp); return false; } } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA)) return false; // Use clang for C++? if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) { Diag(clang::diag::warn_drv_not_using_clang_cxx); return false; } // Finally, don't use clang if this isn't one of the user specified // archs to build. if (!CCCClangArchs.empty() && !CCCClangArchs.count(ArchName)) { Diag(clang::diag::warn_drv_not_using_clang_arch) << ArchName; return false; } return true; } /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and /// return the grouped values as integers. Numbers which are not /// provided are set to 0. /// /// \return True if the entire string was parsed (9.2), or all groups /// were parsed (10.3.5extrastuff). bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra) { HadExtra = false; Major = Minor = Micro = 0; if (*Str == '\0') return true; char *End; Major = (unsigned) strtol(Str, &End, 10); if (*Str != '\0' && *End == '\0') return true; if (*End != '.') return false; Str = End+1; Minor = (unsigned) strtol(Str, &End, 10); if (*Str != '\0' && *End == '\0') return true; if (*End != '.') return false; Str = End+1; Micro = (unsigned) strtol(Str, &End, 10); if (*Str != '\0' && *End == '\0') return true; if (Str == End) return false; HadExtra = true; return true; } <file_sep>/test/CodeGen/bitfield-assign.c /* Check that the result of a bitfield assignment is properly truncated and does not generate a redundant load. */ /* Check that we get one load for each simple assign and two for the compound assign (load the old value before the add then load again to store back). Also check that our g0 pattern is good. */ // RUN: clang-cc -triple i386-unknown-unknown -O0 -emit-llvm -o %t %s && // RUN: grep 'load ' %t | count 5 && // RUN: grep "@g0" %t | count 4 && // Check that we got the right value. // RUN: clang-cc -triple i386-unknown-unknown -O3 -emit-llvm -o %t %s && // RUN: grep 'load ' %t | count 0 && // RUN: grep "@g0" %t | count 0 struct s0 { int f0 : 2; _Bool f1 : 1; unsigned f2 : 2; }; int g0(); void f0(void) { struct s0 s; if ((s.f0 = 3) != -1) g0(); } void f1(void) { struct s0 s; if ((s.f1 = 3) != 1) g0(); } void f2(void) { struct s0 s; if ((s.f2 = 3) != 3) g0(); } void f3(void) { struct s0 s; // Just check this one for load counts. s.f0 += 3; } <file_sep>/test/Lexer/unknown-char.c // RUN: clang-cc -E %s 2>&1 | not grep error ` ` ` ` <file_sep>/tools/clang-cc/ASTConsumers.h //===--- ASTConsumers.h - ASTConsumer implementations -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // AST Consumers. // //===----------------------------------------------------------------------===// #ifndef DRIVER_ASTCONSUMERS_H #define DRIVER_ASTCONSUMERS_H #include "llvm/Support/raw_ostream.h" #include <string> #include <iosfwd> namespace llvm { class Module; namespace sys { class Path; } } namespace clang { class ASTConsumer; class Diagnostic; class FileManager; class Preprocessor; class PreprocessorFactory; struct CompileOptions; class LangOptions; ASTConsumer *CreateASTPrinter(llvm::raw_ostream* OS = NULL); ASTConsumer *CreateASTDumper(); ASTConsumer *CreateASTViewer(); ASTConsumer *CreateDeclContextPrinter(); ASTConsumer *CreateCodeRewriterTest(const std::string& InFile, const std::string& OutFile, Diagnostic &Diags, const LangOptions &LOpts); enum BackendAction { Backend_EmitAssembly, Backend_EmitBC, Backend_EmitLL, Backend_EmitNothing }; ASTConsumer *CreateBackendConsumer(BackendAction Action, Diagnostic &Diags, const LangOptions &Features, const CompileOptions &CompileOpts, const std::string &InFile, const std::string &OutFile); ASTConsumer* CreateHTMLPrinter(const std::string &OutFile, Diagnostic &D, Preprocessor *PP, PreprocessorFactory *PPF); ASTConsumer *CreateSerializationTest(Diagnostic &Diags, FileManager &FMgr); ASTConsumer *CreateASTSerializer(const std::string &InFile, const std::string &EmitDir, Diagnostic &Diags); ASTConsumer *CreatePCHGenerator(const Preprocessor &PP, const std::string &OutFile); ASTConsumer *CreateBlockRewriter(const std::string &InFile, const std::string &OutFile, Diagnostic &Diags, const LangOptions &LangOpts); ASTConsumer *CreateInheritanceViewer(const std::string& clsname); ASTConsumer* CreateAnalysisConsumer(Diagnostic &diags, Preprocessor *pp, PreprocessorFactory *ppf, const LangOptions &lopts, const std::string &output); } // end clang namespace #endif <file_sep>/test/Sema/align-x86.c // RUN: clang-cc -triple i386-apple-darwin9 -fsyntax-only -verify %s // PR3433 double g1; short chk1[__alignof__(g1) == 8 ? 1 : -1]; short chk2[__alignof__(double) == 8 ? 1 : -1]; <file_sep>/test/SemaCXX/member-name-lookup.cpp // RUN: clang-cc -fsyntax-only -verify %s struct A { int a; // expected-note 4{{member found by ambiguous name lookup}} static int b; static int c; // expected-note 4{{member found by ambiguous name lookup}} enum E { enumerator }; typedef int type; static void f(int); void f(float); // expected-note 2{{member found by ambiguous name lookup}} static void static_f(int); static void static_f(double); }; struct B : A { int d; // expected-note 2{{member found by ambiguous name lookup}} enum E2 { enumerator2 }; enum E3 { enumerator3 }; // expected-note 2{{member found by ambiguous name lookup}} }; struct C : A { int c; // expected-note 2{{member found by ambiguous name lookup}} int d; // expected-note 2{{member found by ambiguous name lookup}} enum E3 { enumerator3_2 }; // expected-note 2{{member found by ambiguous name lookup}} }; struct D : B, C { void test_lookup(); }; void test_lookup(D d) { d.a; // expected-error{{non-static member 'a' found in multiple base-class subobjects of type 'struct A'}} (void)d.b; // okay d.c; // expected-error{{member 'c' found in multiple base classes of different types}} d.d; // expected-error{{member 'd' found in multiple base classes of different types}} d.f(0); // expected-error{{non-static member 'f' found in multiple base-class subobjects of type 'struct A'}} d.static_f(0); // okay D::E e = D::enumerator; // okay D::type t = 0; // okay D::E2 e2 = D::enumerator2; // okay D::E3 e3; // expected-error{{multiple base classes}} } void D::test_lookup() { a; // expected-error{{non-static member 'a' found in multiple base-class subobjects of type 'struct A'}} (void)b; // okay c; // expected-error{{member 'c' found in multiple base classes of different types}} d; // expected-error{{member 'd' found in multiple base classes of different types}} f(0); // expected-error{{non-static member 'f' found in multiple base-class subobjects of type 'struct A'}} static_f(0); // okay E e = enumerator; // okay type t = 0; // okay E2 e2 = enumerator2; // okay E3 e3; // expected-error{{member 'E3' found in multiple base classes of different types}} } struct B2 : virtual A { int d; // expected-note 2{{member found by ambiguous name lookup}} enum E2 { enumerator2 }; enum E3 { enumerator3 }; // expected-note 2 {{member found by ambiguous name lookup}} }; struct C2 : virtual A { int c; // expected-note 2{{member found by ambiguous name lookup}} int d; // expected-note 2{{member found by ambiguous name lookup}} enum E3 { enumerator3_2 }; // expected-note 2{{member found by ambiguous name lookup}} }; struct D2 : B2, C2 { void test_virtual_lookup(); }; struct F : A { }; struct G : F, D2 { void test_virtual_lookup(); }; void test_virtual_lookup(D2 d2, G g) { (void)d2.a; (void)d2.b; d2.c; // expected-error{{member 'c' found in multiple base classes of different types}} d2.d; // expected-error{{member 'd' found in multiple base classes of different types}} d2.f(0); // okay d2.static_f(0); // okay D2::E e = D2::enumerator; // okay D2::type t = 0; // okay D2::E2 e2 = D2::enumerator2; // okay D2::E3 e3; // expected-error{{member 'E3' found in multiple base classes of different types}} g.a; // expected-error{{non-static member 'a' found in multiple base-class subobjects of type 'struct A'}} g.static_f(0); // okay } void D2::test_virtual_lookup() { (void)a; (void)b; c; // expected-error{{member 'c' found in multiple base classes of different types}} d; // expected-error{{member 'd' found in multiple base classes of different types}} f(0); // okay static_f(0); // okay E e = enumerator; // okay type t = 0; // okay E2 e2 = enumerator2; // okay E3 e3; // expected-error{{member 'E3' found in multiple base classes of different types}} } void G::test_virtual_lookup() { a; // expected-error{{non-static member 'a' found in multiple base-class subobjects of type 'struct A'}} static_f(0); // okay } struct HasMemberType1 { struct type { }; // expected-note{{member found by ambiguous name lookup}} }; struct HasMemberType2 { struct type { }; // expected-note{{member found by ambiguous name lookup}} }; struct HasAnotherMemberType : HasMemberType1, HasMemberType2 { struct type { }; }; struct UsesAmbigMemberType : HasMemberType1, HasMemberType2 { type t; // expected-error{{member 'type' found in multiple base classes of different types}} }; <file_sep>/Makefile LEVEL = ../.. DIRS := include lib tools docs include $(LEVEL)/Makefile.common ifneq ($(PROJ_SRC_ROOT),$(PROJ_OBJ_ROOT)) test:: $(Verb) if [ ! -f test/Makefile ]; then \ $(MKDIR) test; \ $(CP) $(PROJ_SRC_DIR)/test/Makefile test/Makefile; \ fi endif test:: @ $(MAKE) -C test report:: @ $(MAKE) -C test report clean:: @ $(MAKE) -C test clean tags:: $(Verb) etags `find . -type f -name \*.h | grep -v /lib/Headers | grep -v /test/` `find . -type f -name \*.cpp | grep -v /lib/Headers | grep -v /test/` cscope.files: find tools lib include -name '*.cpp' \ -or -name '*.def' \ -or -name '*.td' \ -or -name '*.h' > cscope.files .PHONY: test report clean cscope.files <file_sep>/test/PCH/struct.c // Test this without pch. // RUN: clang-cc -include %S/struct.h -fsyntax-only -verify %s // Test with pch. // RUN: clang-cc -emit-pch -o %t %S/struct.h && // RUN: clang-cc -include-pch %t -fsyntax-only -verify %s struct Point *p1; float getX(struct Point *p1) { return p1->x; } void *get_fun_ptr() { return fun->is_ptr? fun->ptr : 0; } struct Fun2 { int very_fun; }; int get_very_fun() { return fun2->very_fun; } int *int_ptr_fail = &fun->is_ptr; // expected-error{{address of bit-field requested}} /* FIXME: DeclContexts aren't yet able to find "struct Nested" nested within "struct S", so causing the following to fail. When not using PCH, this works because Sema puts the nested struct onto the declaration chain for its identifier, where C/Objective-C always look. To fix the problem, we either need to give DeclContexts a way to keep track of declarations that are visible without having to build a full lookup table, or we need PCH files to read the declaration chains. */ /* struct Nested nested = { 1, 2 }; */ <file_sep>/include/clang/Analysis/PathSensitive/MemRegion.h //== MemRegion.h - Abstract memory regions for static analysis --*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines MemRegion and its subclasses. MemRegion defines a // partially-typed abstraction of memory useful for path-sensitive dataflow // analyses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_MEMREGION_H #define LLVM_CLANG_ANALYSIS_MEMREGION_H #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/Analysis/PathSensitive/SymbolManager.h" #include "clang/Analysis/PathSensitive/SVals.h" #include "clang/AST/ASTContext.h" #include "llvm/Support/Casting.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableList.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/Support/Allocator.h" #include <string> namespace llvm { class raw_ostream; } namespace clang { class MemRegionManager; /// MemRegion - The root abstract class for all memory regions. class MemRegion : public llvm::FoldingSetNode { public: enum Kind { MemSpaceRegionKind, CodeTextRegionKind, SymbolicRegionKind, AllocaRegionKind, // Typed regions. BEG_TYPED_REGIONS, CompoundLiteralRegionKind, StringRegionKind, ElementRegionKind, TypedViewRegionKind, // Decl Regions. BEG_DECL_REGIONS, VarRegionKind, FieldRegionKind, ObjCIvarRegionKind, ObjCObjectRegionKind, END_DECL_REGIONS, END_TYPED_REGIONS }; private: const Kind kind; protected: MemRegion(Kind k) : kind(k) {} virtual ~MemRegion(); public: // virtual MemExtent getExtent(MemRegionManager& mrm) const = 0; virtual void Profile(llvm::FoldingSetNodeID& ID) const = 0; std::string getString() const; virtual void print(llvm::raw_ostream& os) const; Kind getKind() const { return kind; } template<typename RegionTy> const RegionTy* getAs() const; virtual bool isBoundable(ASTContext&) const { return true; } static bool classof(const MemRegion*) { return true; } }; /// MemSpaceRegion - A memory region that represents and "memory space"; /// for example, the set of global variables, the stack frame, etc. class MemSpaceRegion : public MemRegion { friend class MemRegionManager; MemSpaceRegion() : MemRegion(MemSpaceRegionKind) {} public: //RegionExtent getExtent() const { return UndefinedExtent(); } void Profile(llvm::FoldingSetNodeID& ID) const; bool isBoundable(ASTContext &) const { return false; } static bool classof(const MemRegion* R) { return R->getKind() == MemSpaceRegionKind; } }; /// SubRegion - A region that subsets another larger region. Most regions /// are subclasses of SubRegion. class SubRegion : public MemRegion { protected: const MemRegion* superRegion; SubRegion(const MemRegion* sReg, Kind k) : MemRegion(k), superRegion(sReg) {} public: const MemRegion* getSuperRegion() const { return superRegion; } bool isSubRegionOf(const MemRegion* R) const; static bool classof(const MemRegion* R) { return R->getKind() > MemSpaceRegionKind; } }; /// AllocaRegion - A region that represents an untyped blob of bytes created /// by a call to 'alloca'. class AllocaRegion : public SubRegion { friend class MemRegionManager; protected: unsigned Cnt; // Block counter. Used to distinguish different pieces of // memory allocated by alloca at the same call site. const Expr* Ex; AllocaRegion(const Expr* ex, unsigned cnt, const MemRegion* superRegion) : SubRegion(superRegion, AllocaRegionKind), Cnt(cnt), Ex(ex) {} public: const Expr* getExpr() const { return Ex; } void Profile(llvm::FoldingSetNodeID& ID) const; static void ProfileRegion(llvm::FoldingSetNodeID& ID, const Expr* Ex, unsigned Cnt); void print(llvm::raw_ostream& os) const; static bool classof(const MemRegion* R) { return R->getKind() == AllocaRegionKind; } }; /// TypedRegion - An abstract class representing regions that are typed. class TypedRegion : public SubRegion { protected: TypedRegion(const MemRegion* sReg, Kind k) : SubRegion(sReg, k) {} public: virtual QualType getRValueType(ASTContext &C) const = 0; virtual QualType getLValueType(ASTContext& C) const { // FIXME: We can possibly optimize this later to cache this value. return C.getPointerType(getRValueType(C)); } QualType getDesugaredRValueType(ASTContext& C) const { QualType T = getRValueType(C); return T.getTypePtr() ? T->getDesugaredType() : T; } QualType getDesugaredLValueType(ASTContext& C) const { return getLValueType(C)->getDesugaredType(); } bool isBoundable(ASTContext &C) const { return !getRValueType(C).isNull(); } static bool classof(const MemRegion* R) { unsigned k = R->getKind(); return k > BEG_TYPED_REGIONS && k < END_TYPED_REGIONS; } }; /// CodeTextRegion - A region that represents code texts of a function. It wraps /// two kinds of code texts: real function and symbolic function. Real function /// is a function declared in the program. Symbolic function is a function /// pointer that we don't know which function it points to. class CodeTextRegion : public TypedRegion { public: enum CodeKind { Declared, Symbolic }; private: // The function pointer kind that this CodeTextRegion represents. CodeKind codekind; // Data may be a SymbolRef or FunctionDecl*. const void* Data; // Cached function pointer type. QualType LocationType; public: CodeTextRegion(const FunctionDecl* fd, QualType t, const MemRegion* sreg) : TypedRegion(sreg, CodeTextRegionKind), codekind(Declared), Data(fd), LocationType(t) {} CodeTextRegion(SymbolRef sym, QualType t, const MemRegion* sreg) : TypedRegion(sreg, CodeTextRegionKind), codekind(Symbolic), Data(sym), LocationType(t) {} QualType getRValueType(ASTContext &C) const { // Do not get the object type of a CodeTextRegion. assert(0); return QualType(); } QualType getLValueType(ASTContext &C) const { return LocationType; } virtual bool isBoundable(ASTContext&) const { return false; } void Profile(llvm::FoldingSetNodeID& ID) const; static void ProfileRegion(llvm::FoldingSetNodeID& ID, const void* data, QualType t); static bool classof(const MemRegion* R) { return R->getKind() == CodeTextRegionKind; } }; /// SymbolicRegion - A special, "non-concrete" region. Unlike other region /// clases, SymbolicRegion represents a region that serves as an alias for /// either a real region, a NULL pointer, etc. It essentially is used to /// map the concept of symbolic values into the domain of regions. Symbolic /// regions do not need to be typed. class SymbolicRegion : public SubRegion { protected: const SymbolRef sym; public: SymbolicRegion(const SymbolRef s, const MemRegion* sreg) : SubRegion(sreg, SymbolicRegionKind), sym(s) {} SymbolRef getSymbol() const { return sym; } void Profile(llvm::FoldingSetNodeID& ID) const; static void ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym); void print(llvm::raw_ostream& os) const; static bool classof(const MemRegion* R) { return R->getKind() == SymbolicRegionKind; } }; /// StringRegion - Region associated with a StringLiteral. class StringRegion : public TypedRegion { friend class MemRegionManager; const StringLiteral* Str; protected: StringRegion(const StringLiteral* str, MemRegion* sreg) : TypedRegion(sreg, StringRegionKind), Str(str) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, const StringLiteral* Str, const MemRegion* superRegion); public: const StringLiteral* getStringLiteral() const { return Str; } QualType getRValueType(ASTContext& C) const; void Profile(llvm::FoldingSetNodeID& ID) const { ProfileRegion(ID, Str, superRegion); } void print(llvm::raw_ostream& os) const; static bool classof(const MemRegion* R) { return R->getKind() == StringRegionKind; } }; class TypedViewRegion : public TypedRegion { friend class MemRegionManager; QualType LValueType; TypedViewRegion(QualType lvalueType, const MemRegion* sreg) : TypedRegion(sreg, TypedViewRegionKind), LValueType(lvalueType) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, QualType T, const MemRegion* superRegion); public: void print(llvm::raw_ostream& os) const; QualType getLValueType(ASTContext&) const { return LValueType; } QualType getRValueType(ASTContext&) const { const PointerType* PTy = LValueType->getAsPointerType(); assert(PTy); return PTy->getPointeeType(); } bool isBoundable(ASTContext &C) const { return isa<PointerType>(LValueType); } void Profile(llvm::FoldingSetNodeID& ID) const { ProfileRegion(ID, LValueType, superRegion); } static bool classof(const MemRegion* R) { return R->getKind() == TypedViewRegionKind; } const MemRegion *removeViews() const; }; /// CompoundLiteralRegion - A memory region representing a compound literal. /// Compound literals are essentially temporaries that are stack allocated /// or in the global constant pool. class CompoundLiteralRegion : public TypedRegion { private: friend class MemRegionManager; const CompoundLiteralExpr* CL; CompoundLiteralRegion(const CompoundLiteralExpr* cl, const MemRegion* sReg) : TypedRegion(sReg, CompoundLiteralRegionKind), CL(cl) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, const CompoundLiteralExpr* CL, const MemRegion* superRegion); public: QualType getRValueType(ASTContext& C) const { return C.getCanonicalType(CL->getType()); } void Profile(llvm::FoldingSetNodeID& ID) const; void print(llvm::raw_ostream& os) const; const CompoundLiteralExpr* getLiteralExpr() const { return CL; } static bool classof(const MemRegion* R) { return R->getKind() == CompoundLiteralRegionKind; } }; class DeclRegion : public TypedRegion { protected: const Decl* D; DeclRegion(const Decl* d, const MemRegion* sReg, Kind k) : TypedRegion(sReg, k), D(d) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl* D, const MemRegion* superRegion, Kind k); public: const Decl* getDecl() const { return D; } void Profile(llvm::FoldingSetNodeID& ID) const; QualType getRValueType(ASTContext& C) const = 0; static bool classof(const MemRegion* R) { unsigned k = R->getKind(); return k > BEG_DECL_REGIONS && k < END_DECL_REGIONS; } }; class VarRegion : public DeclRegion { friend class MemRegionManager; VarRegion(const VarDecl* vd, const MemRegion* sReg) : DeclRegion(vd, sReg, VarRegionKind) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, VarDecl* VD, const MemRegion* superRegion) { DeclRegion::ProfileRegion(ID, VD, superRegion, VarRegionKind); } public: const VarDecl* getDecl() const { return cast<VarDecl>(D); } QualType getRValueType(ASTContext& C) const { // FIXME: We can cache this if needed. return C.getCanonicalType(getDecl()->getType()); } void print(llvm::raw_ostream& os) const; static bool classof(const MemRegion* R) { return R->getKind() == VarRegionKind; } }; class FieldRegion : public DeclRegion { friend class MemRegionManager; FieldRegion(const FieldDecl* fd, const MemRegion* sReg) : DeclRegion(fd, sReg, FieldRegionKind) {} public: void print(llvm::raw_ostream& os) const; const FieldDecl* getDecl() const { return cast<FieldDecl>(D); } QualType getRValueType(ASTContext& C) const { // FIXME: We can cache this if needed. return C.getCanonicalType(getDecl()->getType()); } static void ProfileRegion(llvm::FoldingSetNodeID& ID, FieldDecl* FD, const MemRegion* superRegion) { DeclRegion::ProfileRegion(ID, FD, superRegion, FieldRegionKind); } static bool classof(const MemRegion* R) { return R->getKind() == FieldRegionKind; } }; class ObjCObjectRegion : public DeclRegion { friend class MemRegionManager; ObjCObjectRegion(const ObjCInterfaceDecl* ivd, const MemRegion* sReg) : DeclRegion(ivd, sReg, ObjCObjectRegionKind) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, ObjCInterfaceDecl* ivd, const MemRegion* superRegion) { DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCObjectRegionKind); } public: const ObjCInterfaceDecl* getInterface() const { return cast<ObjCInterfaceDecl>(D); } QualType getRValueType(ASTContext& C) const { ObjCInterfaceDecl* ID = const_cast<ObjCInterfaceDecl*>(getInterface()); return C.getObjCInterfaceType(ID); } static bool classof(const MemRegion* R) { return R->getKind() == ObjCObjectRegionKind; } }; class ObjCIvarRegion : public DeclRegion { friend class MemRegionManager; ObjCIvarRegion(const ObjCIvarDecl* ivd, const MemRegion* sReg) : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, ObjCIvarDecl* ivd, const MemRegion* superRegion) { DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind); } public: const ObjCIvarDecl* getDecl() const { return cast<ObjCIvarDecl>(D); } QualType getRValueType(ASTContext&) const { return getDecl()->getType(); } static bool classof(const MemRegion* R) { return R->getKind() == ObjCIvarRegionKind; } }; class ElementRegion : public TypedRegion { friend class MemRegionManager; SVal Index; ElementRegion(SVal Idx, const MemRegion* sReg) : TypedRegion(sReg, ElementRegionKind), Index(Idx) { assert((!isa<nonloc::ConcreteInt>(&Idx) || cast<nonloc::ConcreteInt>(&Idx)->getValue().isSigned()) && "The index must be signed"); } static void ProfileRegion(llvm::FoldingSetNodeID& ID, SVal Idx, const MemRegion* superRegion); public: SVal getIndex() const { return Index; } QualType getRValueType(ASTContext&) const; /// getArrayRegion - Return the region of the enclosing array. This is /// the same as getSuperRegion() except that this returns a TypedRegion* /// instead of a MemRegion*. const TypedRegion* getArrayRegion() const { return cast<TypedRegion>(getSuperRegion()); } void print(llvm::raw_ostream& os) const; void Profile(llvm::FoldingSetNodeID& ID) const; static bool classof(const MemRegion* R) { return R->getKind() == ElementRegionKind; } }; template<typename RegionTy> const RegionTy* MemRegion::getAs() const { const MemRegion *R = this; do { if (const RegionTy* RT = dyn_cast<RegionTy>(R)) return RT; if (const TypedViewRegion *TR = dyn_cast<TypedViewRegion>(R)) { R = TR->getSuperRegion(); continue; } break; } while (R); return 0; } //===----------------------------------------------------------------------===// // MemRegionManager - Factory object for creating regions. //===----------------------------------------------------------------------===// class MemRegionManager { llvm::BumpPtrAllocator& A; llvm::FoldingSet<MemRegion> Regions; MemSpaceRegion* globals; MemSpaceRegion* stack; MemSpaceRegion* heap; MemSpaceRegion* unknown; MemSpaceRegion* code; public: MemRegionManager(llvm::BumpPtrAllocator& a) : A(a), globals(0), stack(0), heap(0), unknown(0), code(0) {} ~MemRegionManager() {} /// getStackRegion - Retrieve the memory region associated with the /// current stack frame. MemSpaceRegion* getStackRegion(); /// getGlobalsRegion - Retrieve the memory region associated with /// all global variables. MemSpaceRegion* getGlobalsRegion(); /// getHeapRegion - Retrieve the memory region associated with the /// generic "heap". MemSpaceRegion* getHeapRegion(); /// getUnknownRegion - Retrieve the memory region associated with unknown /// memory space. MemSpaceRegion* getUnknownRegion(); MemSpaceRegion* getCodeRegion(); bool isGlobalsRegion(const MemRegion* R) { assert(R); return R == globals; } /// onStack - check if the region is allocated on the stack. bool onStack(const MemRegion* R); /// onHeap - check if the region is allocated on the heap, usually by malloc. bool onHeap(const MemRegion* R); /// getAllocaRegion - Retrieve a region associated with a call to alloca(). AllocaRegion* getAllocaRegion(const Expr* Ex, unsigned Cnt); /// getCompoundLiteralRegion - Retrieve the region associated with a /// given CompoundLiteral. CompoundLiteralRegion* getCompoundLiteralRegion(const CompoundLiteralExpr* CL); /// getSymbolicRegion - Retrieve or create a "symbolic" memory region. SymbolicRegion* getSymbolicRegion(SymbolRef sym); StringRegion* getStringRegion(const StringLiteral* Str); /// getVarRegion - Retrieve or create the memory region associated with /// a specified VarDecl. VarRegion* getVarRegion(const VarDecl* vd); ElementRegion* getElementRegion(SVal Idx, const TypedRegion* superRegion); /// getFieldRegion - Retrieve or create the memory region associated with /// a specified FieldDecl. 'superRegion' corresponds to the containing /// memory region (which typically represents the memory representing /// a structure or class). FieldRegion* getFieldRegion(const FieldDecl* fd, const MemRegion* superRegion); /// getObjCObjectRegion - Retrieve or create the memory region associated with /// the instance of a specified Objective-C class. ObjCObjectRegion* getObjCObjectRegion(const ObjCInterfaceDecl* ID, const MemRegion* superRegion); /// getObjCIvarRegion - Retrieve or create the memory region associated with /// a specified Objective-c instance variable. 'superRegion' corresponds /// to the containing region (which typically represents the Objective-C /// object). ObjCIvarRegion* getObjCIvarRegion(const ObjCIvarDecl* ivd, const MemRegion* superRegion); TypedViewRegion* getTypedViewRegion(QualType LValueType, const MemRegion* superRegion); CodeTextRegion* getCodeTextRegion(SymbolRef sym, QualType t); CodeTextRegion* getCodeTextRegion(const FunctionDecl* fd, QualType t); bool hasStackStorage(const MemRegion* R); private: MemSpaceRegion* LazyAllocate(MemSpaceRegion*& region); }; } // end clang namespace namespace llvm { static inline raw_ostream& operator<<(raw_ostream& O, const clang::MemRegion* R) { R->print(O); return O; } } // end llvm namespace #endif <file_sep>/lib/CodeGen/README.txt IRgen optimization opportunities. //===---------------------------------------------------------------------===// The common pattern of -- short x; // or char, etc (x == 10) -- generates an zext/sext of x which can easily be avoided. //===---------------------------------------------------------------------===// Bitfields accesses can be shifted to simplify masking and sign extension. For example, if the bitfield width is 8 and it is appropriately aligned then is is a lot shorter to just load the char directly. //===---------------------------------------------------------------------===// It may be worth avoiding creation of alloca's for formal arguments for the common situation where the argument is never written to or has its address taken. The idea would be to begin generating code by using the argument directly and if its address is taken or it is stored to then generate the alloca and patch up the existing code. In theory, the same optimization could be a win for block local variables as long as the declaration dominates all statements in the block. NOTE: The main case we care about this for is for -O0 -g compile time performance, and in that scenario we will need to emit the alloca anyway currently to emit proper debug info. So this is blocked by being able to emit debug information which refers to an LLVM temporary, not an alloca. //===---------------------------------------------------------------------===// We should try and avoid generating basic blocks which only contain jumps. At -O0, this penalizes us all the way from IRgen (malloc & instruction overhead), all the way down through code generation and assembly time. On 176.gcc:expr.ll, it looks like over 12% of basic blocks are just direct branches! //===---------------------------------------------------------------------===// There are some more places where we could avoid generating unreachable code. For example: void f0(int a) { abort(); if (a) printf("hi"); } still generates a call to printf. This doesn't occur much in real code, but would still be nice to clean up. //===---------------------------------------------------------------------===// Deferred generation of statics incurs some additional overhead. Currently it is even possible to construct test cases with O(N^2) behavior! For at least simple cases where we can tell a global is used, it is probably not worth deferring it. This doesn't solve the O(N^2) cases, ,though... PR3810 //===---------------------------------------------------------------------===// <file_sep>/include/clang/AST/StmtNodes.def //===-- StmtNodes.def - Metadata about Stmt AST nodes -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the AST Node info database. // //===----------------------------------------------------------------------===// #ifndef FIRST_STMT #define FIRST_STMT(CLASS) #define LAST_STMT(CLASS) #endif #ifndef FIRST_EXPR #define FIRST_EXPR(CLASS) #define LAST_EXPR(CLASS) #endif // Normal Statements. STMT(NullStmt , Stmt) FIRST_STMT(NullStmt) STMT(CompoundStmt , Stmt) STMT(CaseStmt , SwitchCase) STMT(DefaultStmt , SwitchCase) STMT(LabelStmt , Stmt) STMT(IfStmt , Stmt) STMT(SwitchStmt , Stmt) STMT(WhileStmt , Stmt) STMT(DoStmt , Stmt) STMT(ForStmt , Stmt) STMT(GotoStmt , Stmt) STMT(IndirectGotoStmt, Stmt) STMT(ContinueStmt , Stmt) STMT(BreakStmt , Stmt) STMT(ReturnStmt , Stmt) STMT(DeclStmt , Stmt) STMT(SwitchCase , Stmt) // GNU Stmt Extensions STMT(AsmStmt , Stmt) // Obj-C statements STMT(ObjCAtTryStmt , Stmt) STMT(ObjCAtCatchStmt , Stmt) STMT(ObjCAtFinallyStmt , Stmt) STMT(ObjCAtThrowStmt , Stmt) STMT(ObjCAtSynchronizedStmt , Stmt) // Obj-C2 statements STMT(ObjCForCollectionStmt, Stmt) // C++ statements STMT(CXXCatchStmt, Stmt) STMT(CXXTryStmt , Stmt) LAST_STMT(CXXTryStmt) // Expressions. STMT(Expr , Stmt) FIRST_EXPR(Expr) STMT(PredefinedExpr , Expr) STMT(DeclRefExpr , Expr) STMT(IntegerLiteral , Expr) STMT(FloatingLiteral , Expr) STMT(ImaginaryLiteral , Expr) STMT(StringLiteral , Expr) STMT(CharacterLiteral , Expr) STMT(ParenExpr , Expr) STMT(UnaryOperator , Expr) STMT(SizeOfAlignOfExpr , Expr) STMT(ArraySubscriptExpr , Expr) STMT(CallExpr , Expr) STMT(MemberExpr , Expr) STMT(CastExpr , Expr) STMT(BinaryOperator , Expr) STMT(CompoundAssignOperator, BinaryOperator) STMT(ConditionalOperator , Expr) STMT(ImplicitCastExpr , CastExpr) STMT(ExplicitCastExpr , CastExpr) STMT(CStyleCastExpr , ExplicitCastExpr) STMT(CompoundLiteralExpr , Expr) STMT(ExtVectorElementExpr , Expr) STMT(InitListExpr , Expr) STMT(DesignatedInitExpr , Expr) STMT(ImplicitValueInitExpr , Expr) STMT(VAArgExpr , Expr) // GNU Extensions. STMT(AddrLabelExpr , Expr) STMT(StmtExpr , Expr) STMT(TypesCompatibleExpr , Expr) STMT(ChooseExpr , Expr) STMT(GNUNullExpr , Expr) // C++ Expressions. STMT(CXXOperatorCallExpr , CallExpr) STMT(CXXMemberCallExpr , CallExpr) STMT(CXXNamedCastExpr , ExplicitCastExpr) STMT(CXXStaticCastExpr , CXXNamedCastExpr) STMT(CXXDynamicCastExpr , CXXNamedCastExpr) STMT(CXXReinterpretCastExpr , CXXNamedCastExpr) STMT(CXXConstCastExpr , CXXNamedCastExpr) STMT(CXXFunctionalCastExpr , ExplicitCastExpr) STMT(CXXTemporaryObjectExpr , Expr) STMT(CXXTypeidExpr , Expr) STMT(CXXBoolLiteralExpr , Expr) STMT(CXXThisExpr , Expr) STMT(CXXThrowExpr , Expr) STMT(CXXDefaultArgExpr , Expr) STMT(CXXZeroInitValueExpr , Expr) STMT(CXXConditionDeclExpr , DeclRefExpr) STMT(CXXNewExpr , Expr) STMT(CXXDeleteExpr , Expr) STMT(UnresolvedFunctionNameExpr , Expr) STMT(UnaryTypeTraitExpr , Expr) STMT(QualifiedDeclRefExpr , DeclRefExpr) STMT(UnresolvedDeclRefExpr , Expr) // Obj-C Expressions. STMT(ObjCStringLiteral , Expr) STMT(ObjCEncodeExpr , Expr) STMT(ObjCMessageExpr , Expr) STMT(ObjCSelectorExpr , Expr) STMT(ObjCProtocolExpr , Expr) STMT(ObjCIvarRefExpr , Expr) STMT(ObjCPropertyRefExpr , Expr) STMT(ObjCKVCRefExpr , Expr) STMT(ObjCSuperExpr , Expr) // Clang Extensions. STMT(ShuffleVectorExpr , Expr) STMT(BlockExpr , Expr) STMT(BlockDeclRefExpr , Expr) LAST_EXPR(BlockDeclRefExpr) #undef STMT #undef FIRST_STMT #undef LAST_STMT #undef FIRST_EXPR #undef LAST_EXPR <file_sep>/test/Analysis/fields.c // RUN: clang-cc -analyze -checker-cfref %s --analyzer-store=basic -verify && // RUN: clang-cc -analyze -checker-cfref %s --analyzer-store=region -verify && // RUN: clang-cc -analyze -checker-simple %s -verify unsigned foo(); typedef struct bf { unsigned x:2; } bf; void bar() { bf y; *(unsigned*)&y = foo(); y.x = 1; } <file_sep>/test/CodeGen/boolassign.c // RUN: clang-cc %s -emit-llvm -o %t int testBoolAssign(void) { int ss; if ((ss = ss && ss)) {} } <file_sep>/tools/ccc/test/ccc/invalid.c // RUN: not xcc -### -c -o %t %s %s <file_sep>/test/Preprocessor/macro_paste_spacing.c // RUN: clang-cc %s -E | grep "^xy$" #define A x ## y blah A <file_sep>/tools/CMakeLists.txt add_subdirectory(clang-cc) add_subdirectory(driver) <file_sep>/test/SemaTemplate/temp_param.cpp // RUN: clang-cc -fsyntax-only -verify %s class X; // C++ [temp.param]p4 typedef int INT; enum E { enum1, enum2 }; template<int N> struct A1; template<INT N, INT M> struct A2; template<enum E x, E y> struct A3; template<int &X> struct A4; template<int *Ptr> struct A5; template<int (&f)(int, int)> struct A6; template<int (*fp)(float, double)> struct A7; template<int X::*pm> struct A8; template<float (X::*pmf)(float, int)> struct A9; template<typename T, T x> struct A10; template<float f> struct A11; // expected-error{{a non-type template parameter cannot have type 'float'}} template<void *Ptr> struct A12; // expected-error{{a non-type template parameter cannot have type 'void *'}} // C++ [temp.param]p8 template<int X[10]> struct A5; template<int f(float, double)> struct A7; // C++ [temp.param]p11: template<typename> struct Y1; // expected-note{{too few template parameters in template template argument}} template<typename, int> struct Y2; template<class T1 = int, // expected-note{{previous default template argument defined here}} class T2> // expected-error{{template parameter missing a default argument}} class B1; template<template<class> class = Y1, // expected-note{{previous default template argument defined here}} template<class> class> // expected-error{{template parameter missing a default argument}} class B1t; template<int N = 5, // expected-note{{previous default template argument defined here}} int M> // expected-error{{template parameter missing a default argument}} class B1n; // Check for bogus template parameter shadow warning. template<template<class T> class, template<class T> class> class B1noshadow; // C++ [temp.param]p10: template<class T1, class T2 = int> class B2; template<class T1 = int, class T2> class B2; template<template<class, int> class, template<class> class = Y1> class B2t; template<template<class, int> class = Y2, template<class> class> class B2t; template<int N, int M = 5> class B2n; template<int N = 5, int M> class B2n; // C++ [temp.param]p12: template<class T1, class T2 = int> // expected-note{{previous default template argument defined here}} class B3; template<class T1, typename T2> class B3; template<class T1, typename T2 = float> // expected-error{{template parameter redefines default argument}} class B3; template<template<class, int> class, template<class> class = Y1> // expected-note{{previous default template argument defined here}} class B3t; template<template<class, int> class, template<class> class> class B3t; template<template<class, int> class, template<class> class = Y1> // expected-error{{template parameter redefines default argument}} class B3t; template<int N, int M = 5> // expected-note{{previous default template argument defined here}} class B3n; template<int N, int M> class B3n; template<int N, int M = 7> // expected-error{{template parameter redefines default argument}} class B3n; // Check validity of default arguments template<template<class, int> class // expected-note{{previous template template parameter is here}} = Y1> // expected-error{{template template argument has different template parameters than its corresponding template template parameter}} class C1; <file_sep>/test/Sema/block-misc.c // RUN: clang-cc -fsyntax-only -verify %s -fblocks void donotwarn(); int (^IFP) (); int (^II) (int); int test1() { int (^PFR) (int) = 0; // OK PFR = II; // OK if (PFR == II) // OK donotwarn(); if (PFR == IFP) // expected-error {{comparison of distinct block types}} donotwarn(); if (PFR == (int (^) (int))IFP) // OK donotwarn(); if (PFR == 0) // OK donotwarn(); if (PFR) // OK donotwarn(); if (!PFR) // OK donotwarn(); return PFR != IFP; // expected-error {{comparison of distinct block types}} } int test2(double (^S)()) { double (^I)(int) = (void*) S; (void*)I = (void *)S; // expected-error {{assignment to cast is illegal, lvalue casts are not supported}} void *pv = I; pv = S; I(1); return (void*)I == (void *)S; } int^ x; // expected-error {{block pointer to non-function type is invalid}} int^^ x1; // expected-error {{block pointer to non-function type is invalid}} expected-error {{block pointer to non-function type is invalid}} int test3() { char *^ y; // expected-error {{block pointer to non-function type is invalid}} } enum {NSBIRLazilyAllocated = 0}; int test4(int argc) { // rdar://6251437 ^{ switch (argc) { case NSBIRLazilyAllocated: // is an integer constant expression. default: break; } }(); return 0; } // rdar://6257721 - reference to static/global is byref by default. static int test5g; void test5() { bar(^{ test5g = 1; }); } // rdar://6405429 - __func__ in a block refers to the containing function name. const char*test6() { return ^{ return __func__; } (); } // radr://6732116 - block comparisons void (^g)(); int foo(void (^p)()) { return g == p; } <file_sep>/test/CodeGen/indirect-goto.c // RUN: clang-cc -triple i386-unknown-unknown -emit-llvm-bc -o - %s | opt -std-compile-opts | llvm-dis > %t && // RUN: grep "ret i32" %t | count 1 && // RUN: grep "ret i32 210" %t | count 1 static int foo(unsigned i) { const void *addrs[] = { &&L1, &&L2, &&L3, &&L4, &&L5 }; int res = 1; goto *addrs[i]; L5: res *= 11; L4: res *= 7; L3: res *= 5; L2: res *= 3; L1: res *= 2; return res; } int bar() { return foo(3); } <file_sep>/lib/Sema/SemaTemplateInstantiateExpr.cpp //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/ // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. //===----------------------------------------------------------------------===/ // // This file implements C++ template instantiation for declarations. // //===----------------------------------------------------------------------===/ #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/StmtVisitor.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/Parse/DeclSpec.h" #include "clang/Lex/Preprocessor.h" // for the identifier table #include "llvm/Support/Compiler.h" using namespace clang; namespace { class VISIBILITY_HIDDEN TemplateExprInstantiator : public StmtVisitor<TemplateExprInstantiator, Sema::OwningExprResult> { Sema &SemaRef; const TemplateArgument *TemplateArgs; unsigned NumTemplateArgs; public: typedef Sema::OwningExprResult OwningExprResult; TemplateExprInstantiator(Sema &SemaRef, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) : SemaRef(SemaRef), TemplateArgs(TemplateArgs), NumTemplateArgs(NumTemplateArgs) { } // FIXME: Once we get closer to completion, replace these // manually-written declarations with automatically-generated ones // from clang/AST/StmtNodes.def. OwningExprResult VisitIntegerLiteral(IntegerLiteral *E); OwningExprResult VisitDeclRefExpr(DeclRefExpr *E); OwningExprResult VisitParenExpr(ParenExpr *E); OwningExprResult VisitUnaryOperator(UnaryOperator *E); OwningExprResult VisitBinaryOperator(BinaryOperator *E); OwningExprResult VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E); OwningExprResult VisitConditionalOperator(ConditionalOperator *E); OwningExprResult VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); OwningExprResult VisitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *E); OwningExprResult VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); OwningExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); // Base case. I'm supposed to ignore this. Sema::OwningExprResult VisitStmt(Stmt *S) { S->dump(); assert(false && "Cannot instantiate this kind of expression"); return SemaRef.ExprError(); } }; } Sema::OwningExprResult TemplateExprInstantiator::VisitIntegerLiteral(IntegerLiteral *E) { return SemaRef.Clone(E); } Sema::OwningExprResult TemplateExprInstantiator::VisitDeclRefExpr(DeclRefExpr *E) { Decl *D = E->getDecl(); if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { assert(NTTP->getDepth() == 0 && "No nested templates yet"); const TemplateArgument &Arg = TemplateArgs[NTTP->getPosition()]; QualType T = Arg.getIntegralType(); if (T->isCharType() || T->isWideCharType()) return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral( Arg.getAsIntegral()->getZExtValue(), T->isWideCharType(), T, E->getSourceRange().getBegin())); else if (T->isBooleanType()) return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr( Arg.getAsIntegral()->getBoolValue(), T, E->getSourceRange().getBegin())); return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral( *Arg.getAsIntegral(), T, E->getSourceRange().getBegin())); } else assert(false && "Can't handle arbitrary declaration references"); return SemaRef.ExprError(); } Sema::OwningExprResult TemplateExprInstantiator::VisitParenExpr(ParenExpr *E) { Sema::OwningExprResult SubExpr = Visit(E->getSubExpr()); if (SubExpr.isInvalid()) return SemaRef.ExprError(); return SemaRef.Owned(new (SemaRef.Context) ParenExpr( E->getLParen(), E->getRParen(), (Expr *)SubExpr.release())); } Sema::OwningExprResult TemplateExprInstantiator::VisitUnaryOperator(UnaryOperator *E) { Sema::OwningExprResult Arg = Visit(E->getSubExpr()); if (Arg.isInvalid()) return SemaRef.ExprError(); return SemaRef.CreateBuiltinUnaryOp(E->getOperatorLoc(), E->getOpcode(), move(Arg)); } Sema::OwningExprResult TemplateExprInstantiator::VisitBinaryOperator(BinaryOperator *E) { Sema::OwningExprResult LHS = Visit(E->getLHS()); if (LHS.isInvalid()) return SemaRef.ExprError(); Sema::OwningExprResult RHS = Visit(E->getRHS()); if (RHS.isInvalid()) return SemaRef.ExprError(); Sema::OwningExprResult Result = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(), E->getOpcode(), (Expr *)LHS.get(), (Expr *)RHS.get()); if (Result.isInvalid()) return SemaRef.ExprError(); LHS.release(); RHS.release(); return move(Result); } Sema::OwningExprResult TemplateExprInstantiator::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { Sema::OwningExprResult First = Visit(E->getArg(0)); if (First.isInvalid()) return SemaRef.ExprError(); Expr *Args[2] = { (Expr *)First.get(), 0 }; Sema::OwningExprResult Second(SemaRef); if (E->getNumArgs() == 2) { Second = Visit(E->getArg(1)); if (Second.isInvalid()) return SemaRef.ExprError(); Args[1] = (Expr *)Second.get(); } if (!E->isTypeDependent()) { // Since our original expression was not type-dependent, we do not // perform lookup again at instantiation time (C++ [temp.dep]p1). // Instead, we just build the new overloaded operator call // expression. First.release(); Second.release(); // FIXME: Don't reuse the callee here. We need to instantiate it. return SemaRef.Owned(new (SemaRef.Context) CXXOperatorCallExpr( SemaRef.Context, E->getOperator(), E->getCallee(), Args, E->getNumArgs(), E->getType(), E->getOperatorLoc())); } bool isPostIncDec = E->getNumArgs() == 2 && (E->getOperator() == OO_PlusPlus || E->getOperator() == OO_MinusMinus); if (E->getNumArgs() == 1 || isPostIncDec) { if (!Args[0]->getType()->isOverloadableType()) { // The argument is not of overloadable type, so try to create a // built-in unary operation. UnaryOperator::Opcode Opc = UnaryOperator::getOverloadedOpcode(E->getOperator(), isPostIncDec); return SemaRef.CreateBuiltinUnaryOp(E->getOperatorLoc(), Opc, move(First)); } // Fall through to perform overload resolution } else { assert(E->getNumArgs() == 2 && "Expected binary operation"); Sema::OwningExprResult Result(SemaRef); if (!Args[0]->getType()->isOverloadableType() && !Args[1]->getType()->isOverloadableType()) { // Neither of the arguments is an overloadable type, so try to // create a built-in binary operation. BinaryOperator::Opcode Opc = BinaryOperator::getOverloadedOpcode(E->getOperator()); Result = SemaRef.CreateBuiltinBinOp(E->getOperatorLoc(), Opc, Args[0], Args[1]); if (Result.isInvalid()) return SemaRef.ExprError(); First.release(); Second.release(); return move(Result); } // Fall through to perform overload resolution. } // Compute the set of functions that were found at template // definition time. Sema::FunctionSet Functions; DeclRefExpr *DRE = cast<DeclRefExpr>(E->getCallee()); OverloadedFunctionDecl *Overloads = cast<OverloadedFunctionDecl>(DRE->getDecl()); // FIXME: Do we have to check // IsAcceptableNonMemberOperatorCandidate for each of these? for (OverloadedFunctionDecl::function_iterator F = Overloads->function_begin(), FEnd = Overloads->function_end(); F != FEnd; ++F) Functions.insert(*F); // Add any functions found via argument-dependent lookup. DeclarationName OpName = SemaRef.Context.DeclarationNames.getCXXOperatorName(E->getOperator()); SemaRef.ArgumentDependentLookup(OpName, Args, E->getNumArgs(), Functions); // Create the overloaded operator invocation. if (E->getNumArgs() == 1 || isPostIncDec) { UnaryOperator::Opcode Opc = UnaryOperator::getOverloadedOpcode(E->getOperator(), isPostIncDec); return SemaRef.CreateOverloadedUnaryOp(E->getOperatorLoc(), Opc, Functions, move(First)); } // FIXME: This would be far less ugly if CreateOverloadedBinOp took // in ExprArg arguments! BinaryOperator::Opcode Opc = BinaryOperator::getOverloadedOpcode(E->getOperator()); OwningExprResult Result = SemaRef.CreateOverloadedBinOp(E->getOperatorLoc(), Opc, Functions, Args[0], Args[1]); if (Result.isInvalid()) return SemaRef.ExprError(); First.release(); Second.release(); return move(Result); } Sema::OwningExprResult TemplateExprInstantiator::VisitConditionalOperator(ConditionalOperator *E) { Sema::OwningExprResult Cond = Visit(E->getCond()); if (Cond.isInvalid()) return SemaRef.ExprError(); // FIXME: use getLHS() and cope with NULLness Sema::OwningExprResult True = Visit(E->getTrueExpr()); if (True.isInvalid()) return SemaRef.ExprError(); Sema::OwningExprResult False = Visit(E->getFalseExpr()); if (False.isInvalid()) return SemaRef.ExprError(); if (!E->isTypeDependent()) { // Since our original expression was not type-dependent, we do not // perform lookup again at instantiation time (C++ [temp.dep]p1). // Instead, we just build the new conditional operator call expression. return SemaRef.Owned(new (SemaRef.Context) ConditionalOperator( Cond.takeAs<Expr>(), True.takeAs<Expr>(), False.takeAs<Expr>(), E->getType())); } return SemaRef.ActOnConditionalOp(/*FIXME*/E->getCond()->getLocEnd(), /*FIXME*/E->getFalseExpr()->getLocStart(), move(Cond), move(True), move(False)); } Sema::OwningExprResult TemplateExprInstantiator::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { bool isSizeOf = E->isSizeOf(); if (E->isArgumentType()) { QualType T = E->getArgumentType(); if (T->isDependentType()) { T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs, /*FIXME*/E->getOperatorLoc(), &SemaRef.PP.getIdentifierTable().get("sizeof")); if (T.isNull()) return SemaRef.ExprError(); } return SemaRef.CreateSizeOfAlignOfExpr(T, E->getOperatorLoc(), isSizeOf, E->getSourceRange()); } Sema::OwningExprResult Arg = Visit(E->getArgumentExpr()); if (Arg.isInvalid()) return SemaRef.ExprError(); Sema::OwningExprResult Result = SemaRef.CreateSizeOfAlignOfExpr((Expr *)Arg.get(), E->getOperatorLoc(), isSizeOf, E->getSourceRange()); if (Result.isInvalid()) return SemaRef.ExprError(); Arg.release(); return move(Result); } Sema::OwningExprResult TemplateExprInstantiator::VisitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *E) { NestedNameSpecifier *NNS = SemaRef.InstantiateNestedNameSpecifier(E->getQualifier(), E->getQualifierRange(), TemplateArgs, NumTemplateArgs); if (!NNS) return SemaRef.ExprError(); CXXScopeSpec SS; SS.setRange(E->getQualifierRange()); SS.setScopeRep(NNS); // FIXME: We're passing in a NULL scope, because // ActOnDeclarationNameExpr doesn't actually use the scope when we // give it a non-empty scope specifier. Investigate whether it would // be better to refactor ActOnDeclarationNameExpr. return SemaRef.ActOnDeclarationNameExpr(/*Scope=*/0, E->getLocation(), E->getDeclName(), /*HasTrailingLParen=*/false, &SS, /*FIXME:isAddressOfOperand=*/false); } Sema::OwningExprResult TemplateExprInstantiator::VisitCXXTemporaryObjectExpr( CXXTemporaryObjectExpr *E) { QualType T = E->getType(); if (T->isDependentType()) { T = SemaRef.InstantiateType(T, TemplateArgs, NumTemplateArgs, E->getTypeBeginLoc(), DeclarationName()); if (T.isNull()) return SemaRef.ExprError(); } llvm::SmallVector<Expr *, 16> Args; Args.reserve(E->getNumArgs()); bool Invalid = false; for (CXXTemporaryObjectExpr::arg_iterator Arg = E->arg_begin(), ArgEnd = E->arg_end(); Arg != ArgEnd; ++Arg) { OwningExprResult InstantiatedArg = Visit(*Arg); if (InstantiatedArg.isInvalid()) { Invalid = true; break; } Args.push_back((Expr *)InstantiatedArg.release()); } if (!Invalid) { SourceLocation CommaLoc; // FIXME: HACK! if (Args.size() > 1) CommaLoc = SemaRef.PP.getLocForEndOfToken(Args[0]->getSourceRange().getEnd()); Sema::OwningExprResult Result( SemaRef.ActOnCXXTypeConstructExpr(SourceRange(E->getTypeBeginLoc() /*, FIXME*/), T.getAsOpaquePtr(), /*FIXME*/E->getTypeBeginLoc(), Sema::MultiExprArg(SemaRef, (void**)&Args[0], Args.size()), /*HACK*/&CommaLoc, E->getSourceRange().getEnd())); // At this point, Args no longer owns the arguments, no matter what. return move(Result); } // Clean up the instantiated arguments. // FIXME: Would rather do this with RAII. for (unsigned Idx = 0; Idx < Args.size(); ++Idx) SemaRef.DeleteExpr(Args[Idx]); return SemaRef.ExprError(); } Sema::OwningExprResult TemplateExprInstantiator::VisitImplicitCastExpr( ImplicitCastExpr *E) { assert(!E->isTypeDependent() && "Implicit casts must have known types"); Sema::OwningExprResult SubExpr = Visit(E->getSubExpr()); if (SubExpr.isInvalid()) return SemaRef.ExprError(); ImplicitCastExpr *ICE = new (SemaRef.Context) ImplicitCastExpr(E->getType(), (Expr *)SubExpr.release(), E->isLvalueCast()); return SemaRef.Owned(ICE); } Sema::OwningExprResult Sema::InstantiateExpr(Expr *E, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { TemplateExprInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs); return Instantiator.Visit(E); } <file_sep>/test/PCH/attrs.c // Test this without pch. // RUN: clang-cc -include %S/attrs.h -fsyntax-only -verify %s // Test with pch. // RUN: clang-cc -emit-pch -o %t %S/attrs.h && // RUN: clang-cc -include-pch %t -fsyntax-only -verify %s // expected-note{{previous overload}} double f(double); // expected-error{{overloadable}} <file_sep>/tools/clang-cc/GeneratePCH.cpp //===--- GeneratePCH.cpp - AST Consumer for PCH Generation ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the CreatePCHGenerate function, which creates an // ASTConsume that generates a PCH file. // //===----------------------------------------------------------------------===// #include "ASTConsumers.h" #include "clang/Frontend/PCHWriter.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/System/Path.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Streams.h" #include <string> using namespace clang; using namespace llvm; namespace { class VISIBILITY_HIDDEN PCHGenerator : public ASTConsumer { const Preprocessor &PP; std::string OutFile; public: explicit PCHGenerator(const Preprocessor &PP, const std::string &OutFile) : PP(PP), OutFile(OutFile) { } virtual void HandleTranslationUnit(ASTContext &Ctx); }; } void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) { if (PP.getDiagnostics().hasErrorOccurred()) return; // Write the PCH contents into a buffer std::vector<unsigned char> Buffer; BitstreamWriter Stream(Buffer); PCHWriter Writer(Stream); // Emit the PCH file Writer.WritePCH(Ctx, PP); // Open up the PCH file. std::string ErrMsg; llvm::raw_fd_ostream Out(OutFile.c_str(), true, ErrMsg); if (!ErrMsg.empty()) { llvm::errs() << "PCH error: " << ErrMsg << "\n"; return; } // Write the generated bitstream to "Out". Out.write((char *)&Buffer.front(), Buffer.size()); // Make sure it hits disk now. Out.flush(); } ASTConsumer *clang::CreatePCHGenerator(const Preprocessor &PP, const std::string &OutFile) { return new PCHGenerator(PP, OutFile); } <file_sep>/test/Preprocessor/macro_arg_keyword.c // RUN: clang-cc -E %s | grep xxx-xxx #define foo(return) return-return foo(xxx) <file_sep>/test/Preprocessor/extension-warning.c // RUN: clang-cc -fsyntax-only -verify -pedantic %s // The preprocessor shouldn't warn about extensions within macro bodies that // aren't expanded. #define __block __attribute__((__blocks__(byref))) // This warning is entirely valid. __block int x; // expected-warning{{extension used}} void whatever() {} <file_sep>/test/Driver/std.c // RUN: clang -std=c99 -trigraphs -std=gnu99 %s -E -o %t && // RUN: grep '??(??)' %t && // RUN: clang -ansi %s -E -o %t && // RUN: grep -F '[]' %t && // RUN: clang -std=gnu99 -trigraphs %s -E -o %t && // RUN: grep -F '[]' %t ??(??) <file_sep>/lib/Parse/AttributeList.cpp //===--- AttributeList.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the AttributeList class implementation // //===----------------------------------------------------------------------===// #include "clang/Parse/AttributeList.h" #include "clang/Basic/IdentifierTable.h" using namespace clang; AttributeList::AttributeList(IdentifierInfo *aName, SourceLocation aLoc, IdentifierInfo *pName, SourceLocation pLoc, ActionBase::ExprTy **ExprList, unsigned numArgs, AttributeList *n) : AttrName(aName), AttrLoc(aLoc), ParmName(pName), ParmLoc(pLoc), NumArgs(numArgs), Next(n) { if (numArgs == 0) Args = 0; else { Args = new ActionBase::ExprTy*[numArgs]; memcpy(Args, ExprList, numArgs*sizeof(Args[0])); } } AttributeList::~AttributeList() { if (Args) { // FIXME: before we delete the vector, we need to make sure the Expr's // have been deleted. Since ActionBase::ExprTy is "void", we are dependent // on the actions module for actually freeing the memory. The specific // hooks are ActOnDeclarator, ActOnTypeName, ActOnParamDeclaratorType, // ParseField, ParseTag. Once these routines have freed the expression, // they should zero out the Args slot (to indicate the memory has been // freed). If any element of the vector is non-null, we should assert. delete [] Args; } delete Next; } AttributeList::Kind AttributeList::getKind(const IdentifierInfo *Name) { const char *Str = Name->getName(); unsigned Len = Name->getLength(); // Normalize the attribute name, __foo__ becomes foo. if (Len > 4 && Str[0] == '_' && Str[1] == '_' && Str[Len - 2] == '_' && Str[Len - 1] == '_') { Str += 2; Len -= 4; } // FIXME: Hand generating this is neither smart nor efficient. switch (Len) { case 4: if (!memcmp(Str, "weak", 4)) return AT_weak; if (!memcmp(Str, "pure", 4)) return AT_pure; if (!memcmp(Str, "mode", 4)) return AT_mode; if (!memcmp(Str, "used", 4)) return AT_used; break; case 5: if (!memcmp(Str, "alias", 5)) return AT_alias; if (!memcmp(Str, "const", 5)) return AT_const; break; case 6: if (!memcmp(Str, "packed", 6)) return AT_packed; if (!memcmp(Str, "malloc", 6)) return IgnoredAttribute; // FIXME: noalias. if (!memcmp(Str, "format", 6)) return AT_format; if (!memcmp(Str, "unused", 6)) return AT_unused; if (!memcmp(Str, "blocks", 6)) return AT_blocks; break; case 7: if (!memcmp(Str, "aligned", 7)) return AT_aligned; if (!memcmp(Str, "cleanup", 7)) return AT_cleanup; if (!memcmp(Str, "nodebug", 7)) return AT_nodebug; if (!memcmp(Str, "nonnull", 7)) return AT_nonnull; if (!memcmp(Str, "nothrow", 7)) return AT_nothrow; if (!memcmp(Str, "objc_gc", 7)) return AT_objc_gc; if (!memcmp(Str, "regparm", 7)) return AT_regparm; if (!memcmp(Str, "section", 7)) return AT_section; if (!memcmp(Str, "stdcall", 7)) return AT_stdcall; break; case 8: if (!memcmp(Str, "annotate", 8)) return AT_annotate; if (!memcmp(Str, "noreturn", 8)) return AT_noreturn; if (!memcmp(Str, "noinline", 8)) return AT_noinline; if (!memcmp(Str, "fastcall", 8)) return AT_fastcall; if (!memcmp(Str, "iboutlet", 8)) return AT_IBOutlet; if (!memcmp(Str, "sentinel", 8)) return AT_sentinel; if (!memcmp(Str, "NSObject", 8)) return AT_nsobject; break; case 9: if (!memcmp(Str, "dllimport", 9)) return AT_dllimport; if (!memcmp(Str, "dllexport", 9)) return AT_dllexport; if (!memcmp(Str, "may_alias", 9)) return IgnoredAttribute; // FIXME: TBAA break; case 10: if (!memcmp(Str, "deprecated", 10)) return AT_deprecated; if (!memcmp(Str, "visibility", 10)) return AT_visibility; if (!memcmp(Str, "destructor", 10)) return AT_destructor; if (!memcmp(Str, "format_arg", 10)) return IgnoredAttribute; // FIXME: printf format string checking. break; case 11: if (!memcmp(Str, "weak_import", 11)) return AT_weak_import; if (!memcmp(Str, "vector_size", 11)) return AT_vector_size; if (!memcmp(Str, "constructor", 11)) return AT_constructor; if (!memcmp(Str, "unavailable", 11)) return AT_unavailable; if (!memcmp(Str, "gnuc_inline", 11)) return AT_gnuc_inline; break; case 12: if (!memcmp(Str, "overloadable", 12)) return AT_overloadable; break; case 13: if (!memcmp(Str, "address_space", 13)) return AT_address_space; if (!memcmp(Str, "always_inline", 13)) return AT_always_inline; break; case 14: if (!memcmp(Str, "objc_exception", 14)) return AT_objc_exception; break; case 15: if (!memcmp(Str, "ext_vector_type", 15)) return AT_ext_vector_type; break; case 17: if (!memcmp(Str, "transparent_union", 17)) return AT_transparent_union; if (!memcmp(Str, "analyzer_noreturn", 17)) return AT_analyzer_noreturn; break; case 18: if (!memcmp(Str, "warn_unused_result", 18)) return AT_warn_unused_result; break; } return UnknownAttribute; } <file_sep>/test/Sema/arg-scope-c99.c // RUN: clang-cc -fsyntax-only -std=c99 -verify %s int bb(int sz, int ar[sz][sz]) { } <file_sep>/test/Driver/clang-translation.c // RUN: clang -ccc-host-triple i386-unknown-unknown -### -S -O0 -Os %s -o %t.s -fverbose-asm 2> %t.log // RUN: grep '"-triple" "i386-unknown-unknown"' %t.log && // RUN: grep '"-S"' %t.log && // RUN: grep '"-disable-free"' %t.log && // RUN: grep '"--relocation-model" "static"' %t.log && // RUN: grep '"--disable-fp-elim"' %t.log && // RUN: grep '"--unwind-tables=0"' %t.log && // RUN: grep '"--fmath-errno=1"' %t.log && // RUN: grep '"-Os"' %t.log && // RUN: grep '"-o" .*clang-translation\.c\.out\.tmp\.s' %t.log && // RUN: grep '"--asm-verbose"' %t.log && // RUN: true <file_sep>/test/SemaCXX/basic_lookup_argdep.cpp // RUN: clang-cc -fsyntax-only -verify %s namespace N { struct X { }; X operator+(X, X); void f(X); void g(X); // expected-note{{candidate function}} void test_multiadd(X x) { (void)(x + x); } } namespace M { struct Y : N::X { }; } void f(); void test_operator_adl(N::X x, M::Y y) { (void)(x + x); (void)(y + y); } void test_func_adl(N::X x, M::Y y) { f(x); f(y); (f)(x); // expected-error{{too many arguments to function call}} ::f(x); // expected-error{{too many arguments to function call}} } namespace N { void test_multiadd2(X x) { (void)(x + x); } } void test_func_adl_only(N::X x) { g(x); } namespace M { int g(N::X); // expected-note{{candidate function}} void test(N::X x) { g(x); // expected-error{{call to 'g' is ambiguous; candidates are:}} int i = (g)(x); int g(N::X); g(x); // okay; calls locally-declared function, no ADL } } void test_operator_name_adl(N::X x) { (void)operator+(x, x); } <file_sep>/include/clang/Driver/Arg.h //===--- Arg.h - Parsed Argument Classes ------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef CLANG_DRIVER_ARG_H_ #define CLANG_DRIVER_ARG_H_ #include "llvm/Support/Casting.h" using llvm::isa; using llvm::cast; using llvm::cast_or_null; using llvm::dyn_cast; using llvm::dyn_cast_or_null; #include "Util.h" #include <vector> #include <string> namespace clang { namespace driver { class ArgList; class Option; /// Arg - A concrete instance of a particular driver option. /// /// The Arg class encodes just enough information to be able to /// derive the argument values efficiently. In addition, Arg /// instances have an intrusive double linked list which is used by /// ArgList to provide efficient iteration over all instances of a /// particular option. class Arg { public: enum ArgClass { FlagClass = 0, PositionalClass, JoinedClass, SeparateClass, CommaJoinedClass, JoinedAndSeparateClass }; private: ArgClass Kind; /// The option this argument is an instance of. const Option *Opt; /// The argument this argument was derived from (during tool chain /// argument translation), if any. const Arg *BaseArg; /// The index at which this argument appears in the containing /// ArgList. unsigned Index; /// Flag indicating whether this argument was used to effect /// compilation; used for generating "argument unused" /// diagnostics. mutable bool Claimed; protected: Arg(ArgClass Kind, const Option *Opt, unsigned Index, const Arg *BaseArg = 0); public: Arg(const Arg &); virtual ~Arg(); ArgClass getKind() const { return Kind; } const Option &getOption() const { return *Opt; } unsigned getIndex() const { return Index; } /// getBaseArg - Return the base argument which generated this /// arg; this is either the argument itself or the argument it was /// derived from during tool chain specific argument translation. const Arg &getBaseArg() const { return BaseArg ? *BaseArg : *this; } void setBaseArg(const Arg *_BaseArg) { BaseArg = _BaseArg; } bool isClaimed() const { return getBaseArg().Claimed; } /// claim - Set the Arg claimed bit. // FIXME: We need to deal with derived arguments and set the bit // in the original argument; not the derived one. void claim() const { getBaseArg().Claimed = true; } virtual unsigned getNumValues() const = 0; virtual const char *getValue(const ArgList &Args, unsigned N=0) const = 0; /// render - Append the argument onto the given array as strings. virtual void render(const ArgList &Args, ArgStringList &Output) const = 0; /// renderAsInput - Append the argument, render as an input, onto /// the given array as strings. The distinction is that some /// options only render their values when rendered as a input /// (e.g., Xlinker). void renderAsInput(const ArgList &Args, ArgStringList &Output) const; static bool classof(const Arg *) { return true; } void dump() const; /// getAsString - Return a formatted version of the argument and /// its values, for debugging and diagnostics. std::string getAsString(const ArgList &Args) const; }; /// FlagArg - An argument with no value. class FlagArg : public Arg { public: FlagArg(const Option *Opt, unsigned Index, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; virtual unsigned getNumValues() const { return 0; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; static bool classof(const Arg *A) { return A->getKind() == Arg::FlagClass; } static bool classof(const FlagArg *) { return true; } }; /// PositionalArg - A simple positional argument. class PositionalArg : public Arg { public: PositionalArg(const Option *Opt, unsigned Index, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; virtual unsigned getNumValues() const { return 1; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; static bool classof(const Arg *A) { return A->getKind() == Arg::PositionalClass; } static bool classof(const PositionalArg *) { return true; } }; /// JoinedArg - A single value argument where the value is joined /// (suffixed) to the option. class JoinedArg : public Arg { public: JoinedArg(const Option *Opt, unsigned Index, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; virtual unsigned getNumValues() const { return 1; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; static bool classof(const Arg *A) { return A->getKind() == Arg::JoinedClass; } static bool classof(const JoinedArg *) { return true; } }; /// SeparateArg - An argument where one or more values follow the /// option specifier immediately in the argument vector. class SeparateArg : public Arg { unsigned NumValues; public: SeparateArg(const Option *Opt, unsigned Index, unsigned NumValues, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; virtual unsigned getNumValues() const { return NumValues; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; static bool classof(const Arg *A) { return A->getKind() == Arg::SeparateClass; } static bool classof(const SeparateArg *) { return true; } }; /// CommaJoinedArg - An argument with multiple values joined by /// commas and joined (suffixed) to the option specifier. /// /// The key point of this arg is that it renders its values into /// separate arguments, which allows it to be used as a generic /// mechanism for passing arguments through to tools. class CommaJoinedArg : public Arg { std::vector<std::string> Values; public: CommaJoinedArg(const Option *Opt, unsigned Index, const char *Str, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; virtual unsigned getNumValues() const { return Values.size(); } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; static bool classof(const Arg *A) { return A->getKind() == Arg::CommaJoinedClass; } static bool classof(const CommaJoinedArg *) { return true; } }; /// JoinedAndSeparateArg - An argument with both joined and separate /// values. class JoinedAndSeparateArg : public Arg { public: JoinedAndSeparateArg(const Option *Opt, unsigned Index, const Arg *BaseArg = 0); virtual void render(const ArgList &Args, ArgStringList &Output) const; virtual unsigned getNumValues() const { return 2; } virtual const char *getValue(const ArgList &Args, unsigned N=0) const; static bool classof(const Arg *A) { return A->getKind() == Arg::JoinedAndSeparateClass; } static bool classof(const JoinedAndSeparateArg *) { return true; } }; } // end namespace driver } // end namespace clang #endif <file_sep>/test/SemaTemplate/class-template-spec.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T, typename U = int> struct A; // expected-note 2{{template is declared here}} template<> struct A<double, double>; // expected-note{{forward declaration}} template<> struct A<float, float> { // expected-note{{previous definition}} int x; }; template<> struct A<float> { // expected-note{{previous definition}} int y; }; int test_specs(A<float, float> *a1, A<float, int> *a2) { return a1->x + a2->y; } int test_incomplete_specs(A<double, double> *a1, A<double> *a2) { (void)a1->x; // expected-error{{incomplete definition of type 'A<double, double>'}} (void)a2->x; // expected-error{{implicit instantiation of undefined template 'struct A<double, int>'}} } typedef float FLOAT; template<> struct A<float, FLOAT>; template<> struct A<FLOAT, float> { }; // expected-error{{redefinition}} template<> struct A<float, int> { }; // expected-error{{redefinition}} template<typename T, typename U = int> struct X; template <> struct X<int, int> { int foo(); }; // #1 template <> struct X<float> { int bar(); }; // #2 typedef int int_type; void testme(X<int_type> *x1, X<float, int> *x2) { (void)x1->foo(); // okay: refers to #1 (void)x2->bar(); // okay: refers to #2 } // Make sure specializations are proper classes. template<> struct A<char> { A(); }; A<char>::A() { } // Diagnose specialization errors struct A<double> { }; // expected-error{{template specialization requires 'template<>'}} template<typename T> // expected-error{{class template partial specialization is not yet supported}} struct A<T*> { }; template<> struct ::A<double>; namespace N { template<typename T> struct B; // expected-note 2{{template is declared here}} template<> struct ::N::B<char>; // okay template<> struct ::N::B<short>; // okay template<> struct ::N::B<int>; // okay int f(int); } template<> struct N::B<int> { }; // okay template<> struct N::B<float> { }; // expected-error{{class template specialization of 'B' not in namespace 'N'}} namespace M { template<> struct ::N::B<short> { }; // expected-error{{class template specialization of 'B' not in a namespace enclosing 'N'}} template<> struct ::A<long double>; // expected-error{{class template specialization of 'A' must occur in the global scope}} } template<> struct N::B<char> { int testf(int x) { return f(x); } }; <file_sep>/test/CodeGen/mandel.c // RUN: clang-cc -emit-llvm %s -o %t /* Sparc is not C99-compliant */ #if defined(sparc) || defined(__sparc__) || defined(__sparcv9) int main() { return 0; } #else /* sparc */ #define ESCAPE 2 #define IMAGE_WIDTH 150 #define IMAGE_HEIGHT 50 #if 1 #define IMAGE_SIZE 60 #else #define IMAGE_SIZE 5000 #endif #define START_X -2.1 #define END_X 1.0 #define START_Y -1.25 #define MAX_ITER 100 #define step_X ((END_X - START_X)/IMAGE_WIDTH) #define step_Y ((-START_Y - START_Y)/IMAGE_HEIGHT) #define I 1.0iF #include <math.h> #include <stdio.h> volatile double __complex__ accum; void mandel() { int x, y, n; for (y = 0; y < IMAGE_HEIGHT; ++y) { for (x = 0; x < IMAGE_WIDTH; ++x) { double __complex__ c = (START_X+x*step_X) + (START_Y+y*step_Y) * I; double __complex__ z = 0.0; for (n = 0; n < MAX_ITER; ++n) { z = z * z + c; if (hypot(__real__ z, __imag__ z) >= ESCAPE) break; } if (n == MAX_ITER) putchar(' '); else if (n > 6) putchar('.'); else if (n > 3) putchar('+'); else if (n > 2) putchar('x'); else putchar('*'); } putchar('\n'); } } int main() { mandel(); return 0; } #endif /* sparc */ <file_sep>/tools/driver/Makefile ##===- tools/driver/Makefile -------------------------------*- Makefile -*-===## # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # ##===----------------------------------------------------------------------===## LEVEL = ../../../.. TOOLNAME = clang CPPFLAGS += -I$(PROJ_SRC_DIR)/../../include -I$(PROJ_OBJ_DIR)/../../include CXXFLAGS = -fno-rtti # This tool has no plugins, optimize startup time. TOOL_NO_EXPORTS = 1 # FIXME: It is unfortunate we need to pull in the bitcode reader and # writer just to get the serializer stuff used by clangBasic. LINK_COMPONENTS := system support bitreader bitwriter USEDLIBS = clangDriver.a clangBasic.a include $(LEVEL)/Makefile.common <file_sep>/test/Sema/arg-scope.c // RUN: clang-cc -fsyntax-only -verify %s int aa(int b, int x[sizeof b]) {} void foo(int i, int A[i]) {} <file_sep>/test/Sema/carbon-pth.c // RUN: clang-cc -emit-pth -o %t %s && // RUN: clang-cc -token-cache %t %s && // RUN: clang-cc -token-cache %t %s -E %s -o /dev/null #ifdef __APPLE__ #include <Carbon/Carbon.h> #endif <file_sep>/include/clang/AST/PrettyPrinter.h //===--- PrettyPrinter.h - Classes for aiding with AST printing -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PrinterHelper interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_PRETTY_PRINTER_H #define LLVM_CLANG_AST_PRETTY_PRINTER_H #include "llvm/Support/raw_ostream.h" namespace clang { class Stmt; class PrinterHelper { public: virtual ~PrinterHelper(); virtual bool handledStmt(Stmt* E, llvm::raw_ostream& OS) = 0; }; } // end namespace clang #endif <file_sep>/test/Coverage/serialize.c // DISABLED: // R U N: clang-cc -fsyntax-only --serialize %s // RUN: #include "c-language-features.inc" <file_sep>/test/Misc/diag-checker.c // RUN: clang-cc -fsyntax-only -verify %s #include <stdio.h> void foo(FILE *FP) {} <file_sep>/lib/Sema/SemaTemplateInstantiate.cpp //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/ // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. //===----------------------------------------------------------------------===/ // // This file implements C++ template instantiation. // //===----------------------------------------------------------------------===/ #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Expr.h" #include "clang/AST/DeclTemplate.h" #include "clang/Parse/DeclSpec.h" #include "clang/Basic/LangOptions.h" #include "llvm/Support/Compiler.h" using namespace clang; //===----------------------------------------------------------------------===/ // Template Instantiation Support //===----------------------------------------------------------------------===/ Sema::InstantiatingTemplate:: InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, CXXRecordDecl *Entity, SourceRange InstantiationRange) : SemaRef(SemaRef) { Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange); if (!Invalid) { ActiveTemplateInstantiation Inst; Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation; Inst.PointOfInstantiation = PointOfInstantiation; Inst.Entity = reinterpret_cast<uintptr_t>(Entity); Inst.TemplateArgs = 0; Inst.NumTemplateArgs = 0; Inst.InstantiationRange = InstantiationRange; SemaRef.ActiveTemplateInstantiations.push_back(Inst); Invalid = false; } } Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceRange InstantiationRange) : SemaRef(SemaRef) { Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange); if (!Invalid) { ActiveTemplateInstantiation Inst; Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation; Inst.PointOfInstantiation = PointOfInstantiation; Inst.Entity = reinterpret_cast<uintptr_t>(Template); Inst.TemplateArgs = TemplateArgs; Inst.NumTemplateArgs = NumTemplateArgs; Inst.InstantiationRange = InstantiationRange; SemaRef.ActiveTemplateInstantiations.push_back(Inst); Invalid = false; } } Sema::InstantiatingTemplate::~InstantiatingTemplate() { if (!Invalid) SemaRef.ActiveTemplateInstantiations.pop_back(); } bool Sema::InstantiatingTemplate::CheckInstantiationDepth( SourceLocation PointOfInstantiation, SourceRange InstantiationRange) { if (SemaRef.ActiveTemplateInstantiations.size() <= SemaRef.getLangOptions().InstantiationDepth) return false; SemaRef.Diag(PointOfInstantiation, diag::err_template_recursion_depth_exceeded) << SemaRef.getLangOptions().InstantiationDepth << InstantiationRange; SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) << SemaRef.getLangOptions().InstantiationDepth; return true; } /// \brief Prints the current instantiation stack through a series of /// notes. void Sema::PrintInstantiationStack() { for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator Active = ActiveTemplateInstantiations.rbegin(), ActiveEnd = ActiveTemplateInstantiations.rend(); Active != ActiveEnd; ++Active) { switch (Active->Kind) { case ActiveTemplateInstantiation::TemplateInstantiation: { unsigned DiagID = diag::note_template_member_class_here; CXXRecordDecl *Record = (CXXRecordDecl *)Active->Entity; if (isa<ClassTemplateSpecializationDecl>(Record)) DiagID = diag::note_template_class_instantiation_here; Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), DiagID) << Context.getTypeDeclType(Record) << Active->InstantiationRange; break; } case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: { TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity); std::string TemplateArgsStr = TemplateSpecializationType::PrintTemplateArgumentList( Active->TemplateArgs, Active->NumTemplateArgs); Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), diag::note_default_arg_instantiation_here) << (Template->getNameAsString() + TemplateArgsStr) << Active->InstantiationRange; break; } } } } //===----------------------------------------------------------------------===/ // Template Instantiation for Types //===----------------------------------------------------------------------===/ namespace { class VISIBILITY_HIDDEN TemplateTypeInstantiator { Sema &SemaRef; const TemplateArgument *TemplateArgs; unsigned NumTemplateArgs; SourceLocation Loc; DeclarationName Entity; public: TemplateTypeInstantiator(Sema &SemaRef, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation Loc, DeclarationName Entity) : SemaRef(SemaRef), TemplateArgs(TemplateArgs), NumTemplateArgs(NumTemplateArgs), Loc(Loc), Entity(Entity) { } QualType operator()(QualType T) const { return Instantiate(T); } QualType Instantiate(QualType T) const; // Declare instantiate functions for each type. #define TYPE(Class, Base) \ QualType Instantiate##Class##Type(const Class##Type *T, \ unsigned Quals) const; #define ABSTRACT_TYPE(Class, Base) #include "clang/AST/TypeNodes.def" }; } QualType TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate ExtQualType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T, unsigned Quals) const { assert(false && "Builtin types are not dependent and cannot be instantiated"); return QualType(T, Quals); } QualType TemplateTypeInstantiator:: InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate FixedWidthIntType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate ComplexType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T, unsigned Quals) const { QualType PointeeType = Instantiate(T->getPointeeType()); if (PointeeType.isNull()) return QualType(); return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity); } QualType TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate BlockPointerType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiateLValueReferenceType( const LValueReferenceType *T, unsigned Quals) const { QualType ReferentType = Instantiate(T->getPointeeType()); if (ReferentType.isNull()) return QualType(); return SemaRef.BuildReferenceType(ReferentType, true, Quals, Loc, Entity); } QualType TemplateTypeInstantiator::InstantiateRValueReferenceType( const RValueReferenceType *T, unsigned Quals) const { QualType ReferentType = Instantiate(T->getPointeeType()); if (ReferentType.isNull()) return QualType(); return SemaRef.BuildReferenceType(ReferentType, false, Quals, Loc, Entity); } QualType TemplateTypeInstantiator:: InstantiateMemberPointerType(const MemberPointerType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate MemberPointerType yet"); return QualType(); } QualType TemplateTypeInstantiator:: InstantiateConstantArrayType(const ConstantArrayType *T, unsigned Quals) const { QualType ElementType = Instantiate(T->getElementType()); if (ElementType.isNull()) return ElementType; // Build a temporary integer literal to specify the size for // BuildArrayType. Since we have already checked the size as part of // creating the dependent array type in the first place, we know // there aren't any errors. // FIXME: Is IntTy big enough? Maybe not, but LongLongTy causes // problems that I have yet to investigate. IntegerLiteral ArraySize(T->getSize(), SemaRef.Context.IntTy, Loc); return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(), &ArraySize, T->getIndexTypeQualifier(), Loc, Entity); } QualType TemplateTypeInstantiator:: InstantiateIncompleteArrayType(const IncompleteArrayType *T, unsigned Quals) const { QualType ElementType = Instantiate(T->getElementType()); if (ElementType.isNull()) return ElementType; return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(), 0, T->getIndexTypeQualifier(), Loc, Entity); } QualType TemplateTypeInstantiator:: InstantiateVariableArrayType(const VariableArrayType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate VariableArrayType yet"); return QualType(); } QualType TemplateTypeInstantiator:: InstantiateDependentSizedArrayType(const DependentSizedArrayType *T, unsigned Quals) const { Expr *ArraySize = T->getSizeExpr(); assert(ArraySize->isValueDependent() && "dependent sized array types must have value dependent size expr"); // Instantiate the element type if needed QualType ElementType = T->getElementType(); if (ElementType->isDependentType()) { ElementType = Instantiate(ElementType); if (ElementType.isNull()) return QualType(); } // Instantiate the size expression Sema::OwningExprResult InstantiatedArraySize = SemaRef.InstantiateExpr(ArraySize, TemplateArgs, NumTemplateArgs); if (InstantiatedArraySize.isInvalid()) return QualType(); return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(), (Expr *)InstantiatedArraySize.release(), T->getIndexTypeQualifier(), Loc, Entity); } QualType TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate VectorType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate ExtVectorType yet"); return QualType(); } QualType TemplateTypeInstantiator:: InstantiateFunctionProtoType(const FunctionProtoType *T, unsigned Quals) const { QualType ResultType = Instantiate(T->getResultType()); if (ResultType.isNull()) return ResultType; llvm::SmallVector<QualType, 16> ParamTypes; for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(), ParamEnd = T->arg_type_end(); Param != ParamEnd; ++Param) { QualType P = Instantiate(*Param); if (P.isNull()) return P; ParamTypes.push_back(P); } return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0], ParamTypes.size(), T->isVariadic(), T->getTypeQuals(), Loc, Entity); } QualType TemplateTypeInstantiator:: InstantiateFunctionNoProtoType(const FunctionNoProtoType *T, unsigned Quals) const { assert(false && "Functions without prototypes cannot be dependent."); return QualType(); } QualType TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate TypedefType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate TypeOfExprType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate TypeOfType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate RecordType yet"); return QualType(); } QualType TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T, unsigned Quals) const { // FIXME: Implement this assert(false && "Cannot instantiate EnumType yet"); return QualType(); } QualType TemplateTypeInstantiator:: InstantiateTemplateTypeParmType(const TemplateTypeParmType *T, unsigned Quals) const { if (T->getDepth() == 0) { // Replace the template type parameter with its corresponding // template argument. assert(T->getIndex() < NumTemplateArgs && "Wrong # of template args"); assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type && "Template argument kind mismatch"); QualType Result = TemplateArgs[T->getIndex()].getAsType(); if (Result.isNull() || !Quals) return Result; // C++ [dcl.ref]p1: // [...] Cv-qualified references are ill-formed except when // the cv-qualifiers are introduced through the use of a // typedef (7.1.3) or of a template type argument (14.3), in // which case the cv-qualifiers are ignored. if (Quals && Result->isReferenceType()) Quals = 0; return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers()); } // The template type parameter comes from an inner template (e.g., // the template parameter list of a member template inside the // template we are instantiating). Create a new template type // parameter with the template "level" reduced by one. return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1, T->getIndex(), T->getName()) .getQualifiedType(Quals); } QualType TemplateTypeInstantiator:: InstantiateTemplateSpecializationType( const TemplateSpecializationType *T, unsigned Quals) const { llvm::SmallVector<TemplateArgument, 16> InstantiatedTemplateArgs; InstantiatedTemplateArgs.reserve(T->getNumArgs()); for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end(); Arg != ArgEnd; ++Arg) { switch (Arg->getKind()) { case TemplateArgument::Type: { QualType T = SemaRef.InstantiateType(Arg->getAsType(), TemplateArgs, NumTemplateArgs, Arg->getLocation(), DeclarationName()); if (T.isNull()) return QualType(); InstantiatedTemplateArgs.push_back( TemplateArgument(Arg->getLocation(), T)); break; } case TemplateArgument::Declaration: case TemplateArgument::Integral: InstantiatedTemplateArgs.push_back(*Arg); break; case TemplateArgument::Expression: Sema::OwningExprResult E = SemaRef.InstantiateExpr(Arg->getAsExpr(), TemplateArgs, NumTemplateArgs); if (E.isInvalid()) return QualType(); InstantiatedTemplateArgs.push_back((Expr *)E.release()); break; } } // FIXME: We're missing the locations of the template name, '<', and // '>'. TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(), Loc, TemplateArgs, NumTemplateArgs); return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(), &InstantiatedTemplateArgs[0], InstantiatedTemplateArgs.size(), SourceLocation()); } QualType TemplateTypeInstantiator:: InstantiateQualifiedNameType(const QualifiedNameType *T, unsigned Quals) const { // When we instantiated a qualified name type, there's no point in // keeping the qualification around in the instantiated result. So, // just instantiate the named type. return (*this)(T->getNamedType()); } QualType TemplateTypeInstantiator:: InstantiateTypenameType(const TypenameType *T, unsigned Quals) const { if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) { // When the typename type refers to a template-id, the template-id // is dependent and has enough information to instantiate the // result of the typename type. Since we don't care about keeping // the spelling of the typename type in template instantiations, // we just instantiate the template-id. return InstantiateTemplateSpecializationType(TemplateId, Quals); } NestedNameSpecifier *NNS = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(), SourceRange(Loc), TemplateArgs, NumTemplateArgs); if (!NNS) return QualType(); return SemaRef.CheckTypenameType(NNS, *T->getIdentifier(), SourceRange(Loc)); } QualType TemplateTypeInstantiator:: InstantiateObjCInterfaceType(const ObjCInterfaceType *T, unsigned Quals) const { assert(false && "Objective-C types cannot be dependent"); return QualType(); } QualType TemplateTypeInstantiator:: InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T, unsigned Quals) const { assert(false && "Objective-C types cannot be dependent"); return QualType(); } QualType TemplateTypeInstantiator:: InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *T, unsigned Quals) const { assert(false && "Objective-C types cannot be dependent"); return QualType(); } QualType TemplateTypeInstantiator:: InstantiateObjCQualifiedClassType(const ObjCQualifiedClassType *T, unsigned Quals) const { assert(false && "Objective-C types cannot be dependent"); return QualType(); } /// \brief The actual implementation of Sema::InstantiateType(). QualType TemplateTypeInstantiator::Instantiate(QualType T) const { // If T is not a dependent type, there is nothing to do. if (!T->isDependentType()) return T; switch (T->getTypeClass()) { #define TYPE(Class, Base) \ case Type::Class: \ return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()), \ T.getCVRQualifiers()); #define ABSTRACT_TYPE(Class, Base) #include "clang/AST/TypeNodes.def" } assert(false && "Not all types have been decoded for instantiation"); return QualType(); } /// \brief Instantiate the type T with a given set of template arguments. /// /// This routine substitutes the given template arguments into the /// type T and produces the instantiated type. /// /// \param T the type into which the template arguments will be /// substituted. If this type is not dependent, it will be returned /// immediately. /// /// \param TemplateArgs the template arguments that will be /// substituted for the top-level template parameters within T. /// /// \param NumTemplateArgs the number of template arguments provided /// by TemplateArgs. /// /// \param Loc the location in the source code where this substitution /// is being performed. It will typically be the location of the /// declarator (if we're instantiating the type of some declaration) /// or the location of the type in the source code (if, e.g., we're /// instantiating the type of a cast expression). /// /// \param Entity the name of the entity associated with a declaration /// being instantiated (if any). May be empty to indicate that there /// is no such entity (if, e.g., this is a type that occurs as part of /// a cast expression) or that the entity has no name (e.g., an /// unnamed function parameter). /// /// \returns If the instantiation succeeds, the instantiated /// type. Otherwise, produces diagnostics and returns a NULL type. QualType Sema::InstantiateType(QualType T, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs, SourceLocation Loc, DeclarationName Entity) { assert(!ActiveTemplateInstantiations.empty() && "Cannot perform an instantiation without some context on the " "instantiation stack"); // If T is not a dependent type, there is nothing to do. if (!T->isDependentType()) return T; TemplateTypeInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs, Loc, Entity); return Instantiator(T); } /// \brief Instantiate the base class specifiers of the given class /// template specialization. /// /// Produces a diagnostic and returns true on error, returns false and /// attaches the instantiated base classes to the class template /// specialization if successful. bool Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { bool Invalid = false; llvm::SmallVector<CXXBaseSpecifier*, 8> InstantiatedBases; for (ClassTemplateSpecializationDecl::base_class_iterator Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end(); Base != BaseEnd; ++Base) { if (!Base->getType()->isDependentType()) { // FIXME: Allocate via ASTContext InstantiatedBases.push_back(new CXXBaseSpecifier(*Base)); continue; } QualType BaseType = InstantiateType(Base->getType(), TemplateArgs, NumTemplateArgs, Base->getSourceRange().getBegin(), DeclarationName()); if (BaseType.isNull()) { Invalid = true; continue; } if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(Instantiation, Base->getSourceRange(), Base->isVirtual(), Base->getAccessSpecifierAsWritten(), BaseType, /*FIXME: Not totally accurate */ Base->getSourceRange().getBegin())) InstantiatedBases.push_back(InstantiatedBase); else Invalid = true; } if (!Invalid && AttachBaseSpecifiers(Instantiation, &InstantiatedBases[0], InstantiatedBases.size())) Invalid = true; return Invalid; } /// \brief Instantiate the definition of a class from a given pattern. /// /// \param PointOfInstantiation The point of instantiation within the /// source code. /// /// \param Instantiation is the declaration whose definition is being /// instantiated. This will be either a class template specialization /// or a member class of a class template specialization. /// /// \param Pattern is the pattern from which the instantiation /// occurs. This will be either the declaration of a class template or /// the declaration of a member class of a class template. /// /// \param TemplateArgs The template arguments to be substituted into /// the pattern. /// /// \param NumTemplateArgs The number of templates arguments in /// TemplateArgs. /// /// \returns true if an error occurred, false otherwise. bool Sema::InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { bool Invalid = false; CXXRecordDecl *PatternDef = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context)); if (!PatternDef) { if (Pattern == Instantiation->getInstantiatedFromMemberClass()) { Diag(PointOfInstantiation, diag::err_implicit_instantiate_member_undefined) << Context.getTypeDeclType(Instantiation); Diag(Pattern->getLocation(), diag::note_member_of_template_here); } else { Diag(PointOfInstantiation, diag::err_template_implicit_instantiate_undefined) << Context.getTypeDeclType(Instantiation); Diag(Pattern->getLocation(), diag::note_template_decl_here); } return true; } Pattern = PatternDef; InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); if (Inst) return true; // Enter the scope of this instantiation. We don't use // PushDeclContext because we don't have a scope. DeclContext *PreviousContext = CurContext; CurContext = Instantiation; // Start the definition of this instantiation. Instantiation->startDefinition(); // Instantiate the base class specifiers. if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs, NumTemplateArgs)) Invalid = true; llvm::SmallVector<DeclPtrTy, 32> Fields; for (RecordDecl::decl_iterator Member = Pattern->decls_begin(Context), MemberEnd = Pattern->decls_end(Context); Member != MemberEnd; ++Member) { Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs, NumTemplateArgs); if (NewMember) { if (NewMember->isInvalidDecl()) Invalid = true; else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) Fields.push_back(DeclPtrTy::make(Field)); } else { // FIXME: Eventually, a NULL return will mean that one of the // instantiations was a semantic disaster, and we'll want to set // Invalid = true. For now, we expect to skip some members that // we can't yet handle. } } // Finish checking fields. ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation), &Fields[0], Fields.size(), SourceLocation(), SourceLocation(), 0); // Add any implicitly-declared members that we might need. AddImplicitlyDeclaredMembersToClass(Instantiation); // Exit the scope of this instantiation. CurContext = PreviousContext; return Invalid; } bool Sema::InstantiateClassTemplateSpecialization( ClassTemplateSpecializationDecl *ClassTemplateSpec, bool ExplicitInstantiation) { // Perform the actual instantiation on the canonical declaration. ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( Context.getCanonicalDecl(ClassTemplateSpec)); // We can only instantiate something that hasn't already been // instantiated or specialized. Fail without any diagnostics: our // caller will provide an error message. if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) return true; // FIXME: Push this class template instantiation onto the // instantiation stack, checking for recursion that exceeds a // certain depth. // FIXME: Perform class template partial specialization to select // the best template. ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); CXXRecordDecl *Pattern = Template->getTemplatedDecl(); // Note that this is an instantiation. ClassTemplateSpec->setSpecializationKind( ExplicitInstantiation? TSK_ExplicitInstantiation : TSK_ImplicitInstantiation); return InstantiateClass(ClassTemplateSpec->getLocation(), ClassTemplateSpec, Pattern, ClassTemplateSpec->getTemplateArgs(), ClassTemplateSpec->getNumTemplateArgs()); } /// \brief Instantiate a nested-name-specifier. NestedNameSpecifier * Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { // Instantiate the prefix of this nested name specifier. NestedNameSpecifier *Prefix = NNS->getPrefix(); if (Prefix) { Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs, NumTemplateArgs); if (!Prefix) return 0; } switch (NNS->getKind()) { case NestedNameSpecifier::Identifier: { assert(Prefix && "Can't have an identifier nested-name-specifier with no prefix"); CXXScopeSpec SS; // FIXME: The source location information is all wrong. SS.setRange(Range); SS.setScopeRep(Prefix); return static_cast<NestedNameSpecifier *>( ActOnCXXNestedNameSpecifier(0, SS, Range.getEnd(), Range.getEnd(), *NNS->getAsIdentifier())); break; } case NestedNameSpecifier::Namespace: case NestedNameSpecifier::Global: return NNS; case NestedNameSpecifier::TypeSpecWithTemplate: case NestedNameSpecifier::TypeSpec: { QualType T = QualType(NNS->getAsType(), 0); if (!T->isDependentType()) return NNS; T = InstantiateType(T, TemplateArgs, NumTemplateArgs, Range.getBegin(), DeclarationName()); if (T.isNull()) return 0; if (T->isRecordType() || (getLangOptions().CPlusPlus0x && T->isEnumeralType())) { assert(T.getCVRQualifiers() == 0 && "Can't get cv-qualifiers here"); return NestedNameSpecifier::Create(Context, Prefix, NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, T.getTypePtr()); } Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T; return 0; } } // Required to silence a GCC warning return 0; } TemplateName Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { if (TemplateTemplateParmDecl *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>( Name.getAsTemplateDecl())) { assert(TTP->getDepth() == 0 && "Cannot reduce depth of a template template parameter"); assert(TTP->getPosition() < NumTemplateArgs && "Wrong # of template args"); assert(TemplateArgs[TTP->getPosition()].getAsDecl() && "Wrong kind of template template argument"); ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>( TemplateArgs[TTP->getPosition()].getAsDecl()); assert(ClassTemplate && "Expected a class template"); if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) { NestedNameSpecifier *NNS = InstantiateNestedNameSpecifier(QTN->getQualifier(), /*FIXME=*/SourceRange(Loc), TemplateArgs, NumTemplateArgs); if (NNS) return Context.getQualifiedTemplateName(NNS, QTN->hasTemplateKeyword(), ClassTemplate); } return TemplateName(ClassTemplate); } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) { NestedNameSpecifier *NNS = InstantiateNestedNameSpecifier(DTN->getQualifier(), /*FIXME=*/SourceRange(Loc), TemplateArgs, NumTemplateArgs); if (!NNS) // FIXME: Not the best recovery strategy. return Name; if (NNS->isDependent()) return Context.getDependentTemplateName(NNS, DTN->getName()); // Somewhat redundant with ActOnDependentTemplateName. CXXScopeSpec SS; SS.setRange(SourceRange(Loc)); SS.setScopeRep(NNS); TemplateTy Template; TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS); if (TNK == TNK_Non_template) { Diag(Loc, diag::err_template_kw_refers_to_non_template) << DTN->getName(); return Name; } else if (TNK == TNK_Function_template) { Diag(Loc, diag::err_template_kw_refers_to_non_template) << DTN->getName(); return Name; } return Template.getAsVal<TemplateName>(); } // FIXME: Even if we're referring to a Decl that isn't a template // template parameter, we may need to instantiate the outer contexts // of that Decl. However, this won't be needed until we implement // member templates. return Name; } <file_sep>/test/SemaCXX/vararg-non-pod.cpp // RUN: clang-cc -fsyntax-only -verify -fblocks %s extern char version[]; class C { public: C(int); void g(int a, ...); static void h(int a, ...); }; void g(int a, ...); void t1() { C c(10); g(10, c); // expected-warning{{cannot pass object of non-POD type 'class C' through variadic function; call will abort at runtime}} g(10, version); } void t2() { C c(10); c.g(10, c); // expected-warning{{cannot pass object of non-POD type 'class C' through variadic method; call will abort at runtime}} c.g(10, version); C::h(10, c); // expected-warning{{cannot pass object of non-POD type 'class C' through variadic function; call will abort at runtime}} C::h(10, version); } int (^block)(int, ...); void t3() { C c(10); block(10, c); // expected-warning{{cannot pass object of non-POD type 'class C' through variadic block; call will abort at runtime}} block(10, version); } class D { public: void operator() (int a, ...); }; void t4() { C c(10); D d; d(10, c); // expected-warning{{Line 48: cannot pass object of non-POD type 'class C' through variadic method; call will abort at runtime}} d(10, version); } <file_sep>/test/Rewriter/block-test.c // RUN: clang-cc -rewrite-blocks %s -fblocks -o - static int (^block)(const void *, const void *) = (int (^)(const void *, const void *))0; static int (*func)(int (^block)(void *, void *)) = (int (*)(int (^block)(void *, void *)))0; typedef int (^block_T)(const void *, const void *); typedef int (*func_T)(int (^block)(void *, void *)); void foo(const void *a, const void *b, void *c) { int (^block)(const void *, const void *) = (int (^)(const void *, const void *))c; int (*func)(int (^block)(void *, void *)) = (int (*)(int (^block)(void *, void *)))c; } typedef void (^test_block_t)(); int main(int argc, char **argv) { int a; void (^test_block_v)(); void (^test_block_v2)(int, float); void (^test_block_v3)(void (^barg)(int)); a = 77; test_block_v = ^(){ int local=1; printf("a=%d\n",a+local); }; test_block_v(); a++; test_block_v(); __block int b; b = 88; test_block_v2 = ^(int x, float f){ printf("b=%d\n",b); }; test_block_v2(1,2.0); b++; test_block_v2(3,4.0); return 7; } <file_sep>/test/SemaCXX/member-pointer.cpp // RUN: clang-cc -fsyntax-only -verify %s struct A {}; enum B { Dummy }; namespace C {} struct D : A {}; struct E : A {}; struct F : D, E {}; struct G : virtual D {}; int A::*pdi1; int (::A::*pdi2); int (A::*pfi)(int); int B::*pbi; // expected-error {{expected a class or namespace}} int C::*pci; // expected-error {{'pci' does not point into a class}} void A::*pdv; // expected-error {{'pdv' declared as a member pointer to void}} int& A::*pdr; // expected-error {{'pdr' declared as a pointer to a reference}} void f() { // This requires tentative parsing. int (A::*pf)(int, int); // Implicit conversion to bool. bool b = pdi1; b = pfi; // Conversion from null pointer constant. pf = 0; pf = __null; // Conversion to member of derived. int D::*pdid = pdi1; pdid = pdi2; // Fail conversion due to ambiguity and virtuality. int F::*pdif = pdi1; // expected-error {{ambiguous conversion from pointer to member of base class 'struct A' to pointer to member of derived class 'struct F'}} expected-error {{incompatible type}} int G::*pdig = pdi1; // expected-error {{conversion from pointer to member of class 'struct A' to pointer to member of class 'struct G' via virtual base 'struct D' is not allowed}} expected-error {{incompatible type}} // Conversion to member of base. pdi1 = pdid; // expected-error {{incompatible type assigning 'int struct D::*', expected 'int struct A::*'}} } struct TheBase { void d(); }; struct HasMembers : TheBase { int i; void f(); void g(); void g(int); static void g(double); }; namespace Fake { int i; void f(); } void g() { HasMembers hm; int HasMembers::*pmi = &HasMembers::i; int *pni = &Fake::i; int *pmii = &hm.i; void (HasMembers::*pmf)() = &HasMembers::f; void (*pnf)() = &Fake::f; &hm.f; // expected-error {{address expression must be an lvalue or a function designator}} void (HasMembers::*pmgv)() = &HasMembers::g; void (HasMembers::*pmgi)(int) = &HasMembers::g; void (*pmgd)(double) = &HasMembers::g; void (HasMembers::*pmd)() = &HasMembers::d; } struct Incomplete; // expected-note{{forward declaration}} void h() { HasMembers hm, *phm = &hm; int HasMembers::*pi = &HasMembers::i; hm.*pi = 0; int i = phm->*pi; (void)&(hm.*pi); (void)&(phm->*pi); (void)&((&hm)->*pi); // expected-error {{address expression must be an lvalue or a function designator}} void (HasMembers::*pf)() = &HasMembers::f; (hm.*pf)(); (phm->*pf)(); (void)(hm->*pi); // expected-error {{left hand operand to ->* must be a pointer to class compatible with the right hand operand, but is 'struct HasMembers'}} (void)(phm.*pi); // expected-error {{left hand operand to .* must be a class compatible with the right hand operand, but is 'struct HasMembers *'}} (void)(i.*pi); // expected-error {{left hand operand to .* must be a class compatible with the right hand operand, but is 'int'}} int *ptr; (void)(ptr->*pi); // expected-error {{left hand operand to ->* must be a pointer to class compatible with the right hand operand, but is 'int *'}} int A::*pai = 0; D d, *pd = &d; (void)(d.*pai); (void)(pd->*pai); F f, *ptrf = &f; (void)(f.*pai); // expected-error {{left hand operand to .* must be a class compatible with the right hand operand, but is 'struct F'}} (void)(ptrf->*pai); // expected-error {{left hand operand to ->* must be a pointer to class compatible with the right hand operand, but is 'struct F *'}} (void)(hm.*i); // expected-error {{pointer-to-member}} (void)(phm->*i); // expected-error {{pointer-to-member}} Incomplete *inc; int Incomplete::*pii = 0; (void)inc->*pii; // expected-error {{right hand operand is a pointer to member of incomplete type 'struct Incomplete'}} } struct OverloadsPtrMem { int operator ->*(const char *); }; void i() { OverloadsPtrMem m; int foo = m->*"Awesome!"; } <file_sep>/test/CodeGen/cast-to-union.c // RUN: clang-cc -emit-llvm < %s -o %t && // RUN: grep "store i32 351, i32*" %t && // RUN: grep "w = global %0 <{ i32 2, i8 0, i8 0, i8 0, i8 0 }>" %t && // RUN: grep "y = global %1 <{ double 7.300000e+01 }>" %t union u { int i; double d; }; void foo() { union u ola = (union u) 351; } union u w = (union u)2; union u y = (union u)73.0; <file_sep>/include/clang/AST/X86Builtins.def //===--- X86Builtins.def - X86 Builtin function database --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the X86-specific builtin function database. Users of // this file must define the BUILTIN macro to make use of this information. // //===----------------------------------------------------------------------===// // FIXME: this needs to be the full list supported by GCC. Right now, I'm just // adding stuff on demand. // The format of this database matches clang/AST/Builtins.def. // FIXME: In GCC, these builtins are defined depending on whether support for // MMX/SSE/etc is turned on. We should do this too. // FIXME: Ideally we would be able to pull this information from what // LLVM already knows about X86 builtins. We need to match the LLVM // definition anyway, since code generation will lower to the // intrinsic if one exists. BUILTIN(__builtin_ia32_emms , "v", "") // FIXME: Are these nothrow/const? // SSE intrinsics. BUILTIN(__builtin_ia32_comieq, "iV4fV4f", "") BUILTIN(__builtin_ia32_comilt, "iV4fV4f", "") BUILTIN(__builtin_ia32_comile, "iV4fV4f", "") BUILTIN(__builtin_ia32_comigt, "iV4fV4f", "") BUILTIN(__builtin_ia32_comige, "iV4fV4f", "") BUILTIN(__builtin_ia32_comineq, "iV4fV4f", "") BUILTIN(__builtin_ia32_ucomieq, "iV4fV4f", "") BUILTIN(__builtin_ia32_ucomilt, "iV4fV4f", "") BUILTIN(__builtin_ia32_ucomile, "iV4fV4f", "") BUILTIN(__builtin_ia32_ucomigt, "iV4fV4f", "") BUILTIN(__builtin_ia32_ucomige, "iV4fV4f", "") BUILTIN(__builtin_ia32_ucomineq, "iV4fV4f", "") BUILTIN(__builtin_ia32_comisdeq, "iV2dV2d", "") BUILTIN(__builtin_ia32_comisdlt, "iV2dV2d", "") BUILTIN(__builtin_ia32_comisdle, "iV2dV2d", "") BUILTIN(__builtin_ia32_comisdgt, "iV2dV2d", "") BUILTIN(__builtin_ia32_comisdge, "iV2dV2d", "") BUILTIN(__builtin_ia32_comisdneq, "iV2dV2d", "") BUILTIN(__builtin_ia32_ucomisdeq, "iV2dV2d", "") BUILTIN(__builtin_ia32_ucomisdlt, "iV2dV2d", "") BUILTIN(__builtin_ia32_ucomisdle, "iV2dV2d", "") BUILTIN(__builtin_ia32_ucomisdgt, "iV2dV2d", "") BUILTIN(__builtin_ia32_ucomisdge, "iV2dV2d", "") BUILTIN(__builtin_ia32_ucomisdneq, "iV2dV2d", "") BUILTIN(__builtin_ia32_addps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_subps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_mulps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_divps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_addss, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_subss, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_mulss, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_divss, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_cmpeqps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpltps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpleps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpgtps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpgeps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpunordps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpneqps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpnltps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpnleps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpngtps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpngeps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpordps, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpeqss, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpltss, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpless, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpunordss, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpneqss, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpnltss, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpnless, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpngtss, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpngess, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_cmpordss, "V4iV4fV4f", "") BUILTIN(__builtin_ia32_minps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_maxps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_minss, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_maxss, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_andps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_andnps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_orps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_xorps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_movss, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_movhlps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_movlhps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_unpckhps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_unpcklps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_paddb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_paddw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_paddd, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_paddq, "V1LLiV1LLiV1LLi", "") BUILTIN(__builtin_ia32_psubb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_psubw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_psubd, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_psubq, "V1LLiV1LLiV1LLi", "") BUILTIN(__builtin_ia32_paddsb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_paddsw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_psubsb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_psubsw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_paddusb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_paddusw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_psubusb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_psubusw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pmullw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pmulhw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pmulhuw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pand, "V1LLiV1LLiV1LLi", "") BUILTIN(__builtin_ia32_pandn, "V1LLiV1LLiV1LLi", "") BUILTIN(__builtin_ia32_por, "V1LLiV1LLiV1LLi", "") BUILTIN(__builtin_ia32_pxor, "V1LLiV1LLiV1LLi", "") BUILTIN(__builtin_ia32_pavgb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_pavgw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pcmpeqb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_pcmpeqw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pcmpeqd, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_pcmpgtb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_pcmpgtw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pcmpgtd, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_pmaxub, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_pmaxsw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pminub, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_pminsw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_punpckhbw, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_punpckhwd, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_punpckhdq, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_punpcklbw, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_punpcklwd, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_punpckldq, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_addpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_subpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_mulpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_divpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_addsd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_subsd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_mulsd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_divsd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_cmpeqpd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpltpd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmplepd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpgtpd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpgepd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpunordpd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpneqpd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpnltpd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpnlepd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpngtpd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpngepd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpordpd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpeqsd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpltsd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmplesd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpunordsd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpneqsd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpnltsd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpnlesd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_cmpordsd, "V4iV2dV2d", "") BUILTIN(__builtin_ia32_minpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_maxpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_minsd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_maxsd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_andpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_andnpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_orpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_xorpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_movsd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_unpckhpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_unpcklpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_paddb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_paddw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_paddd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_paddq128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_psubb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_psubw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_psubd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_psubq128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_paddsb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_paddsw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_psubsb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_psubsw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_paddusb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_paddusw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_psubusb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_psubusw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pmullw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pmulhw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pand128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_pandn128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_por128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_pxor128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_pavgb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pavgw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pcmpeqb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pcmpeqw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pcmpeqd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_pcmpgtb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pcmpgtw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pcmpgtd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_pmaxub128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pmaxsw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pminub128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pminsw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_punpckhbw128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_punpckhwd128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_punpckhdq128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_punpckhqdq128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_punpcklbw128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_punpcklwd128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_punpckldq128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_punpcklqdq128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_packsswb128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_packssdw128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_packuswb128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pmulhuw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_addsubps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_addsubpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_haddps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_haddpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_hsubps, "V4fV4fV4f", "") BUILTIN(__builtin_ia32_hsubpd, "V2dV2dV2d", "") BUILTIN(__builtin_ia32_phaddw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_phaddw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_phaddd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_phaddd, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_phaddsw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_phaddsw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_phsubw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_phsubw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_phsubd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_phsubd, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_phsubsw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_phsubsw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pmaddubsw128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pmaddubsw, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_pmulhrsw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pmulhrsw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pshufb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pshufb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_psignb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_psignb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_psignw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_psignw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_psignd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_psignd, "V2iV2iV2i", "") BUILTIN(__builtin_ia32_pabsb128, "V16cV16c", "") BUILTIN(__builtin_ia32_pabsb, "V8cV8c", "") BUILTIN(__builtin_ia32_pabsw128, "V8sV8s", "") BUILTIN(__builtin_ia32_pabsw, "V4sV4s", "") BUILTIN(__builtin_ia32_pabsd128, "V4iV4i", "") BUILTIN(__builtin_ia32_pabsd, "V2iV2i", "") BUILTIN(__builtin_ia32_psllw, "V4sV4sV1LLi", "") BUILTIN(__builtin_ia32_pslld, "V2iV2iV1LLi", "") BUILTIN(__builtin_ia32_psllq, "V1LLiV1LLiV1LLi", "") BUILTIN(__builtin_ia32_psrlw, "V4sV4sV1LLi", "") BUILTIN(__builtin_ia32_psrld, "V2iV2iV1LLi", "") BUILTIN(__builtin_ia32_psrlq, "V1LLiV1LLiV1LLi", "") BUILTIN(__builtin_ia32_psraw, "V4sV4sV1LLi", "") BUILTIN(__builtin_ia32_psrad, "V2iV2iV1LLi", "") BUILTIN(__builtin_ia32_pshufw, "V4sV4si", "") BUILTIN(__builtin_ia32_pmaddwd, "V2iV4sV4s", "") BUILTIN(__builtin_ia32_packsswb, "V8cV4sV4s", "") BUILTIN(__builtin_ia32_packssdw, "V4sV2iV2i", "") BUILTIN(__builtin_ia32_packuswb, "V8cV4sV4s", "") BUILTIN(__builtin_ia32_ldmxcsr, "vUi", "") BUILTIN(__builtin_ia32_stmxcsr, "Ui", "") BUILTIN(__builtin_ia32_cvtpi2ps, "V4fV4fV2i", "") BUILTIN(__builtin_ia32_cvtps2pi, "V2iV4f", "") BUILTIN(__builtin_ia32_cvtsi2ss, "V4fV4fi", "") BUILTIN(__builtin_ia32_cvtsi642ss, "V4fV4fLLi", "") BUILTIN(__builtin_ia32_cvtss2si, "iV4f", "") BUILTIN(__builtin_ia32_cvtss2si64, "LLiV4f", "") BUILTIN(__builtin_ia32_cvttps2pi, "V2iV4f", "") BUILTIN(__builtin_ia32_cvttss2si, "iV4f", "") BUILTIN(__builtin_ia32_cvttss2si64, "LLiV4f", "") BUILTIN(__builtin_ia32_maskmovq, "vV8cV8cc*", "") BUILTIN(__builtin_ia32_loadups, "V4ffC*", "") BUILTIN(__builtin_ia32_storeups, "vf*V4f", "") BUILTIN(__builtin_ia32_loadhps, "V4fV4fV2i*", "") BUILTIN(__builtin_ia32_loadlps, "V4fV4fV2i*", "") BUILTIN(__builtin_ia32_storehps, "vV2i*V4f", "") BUILTIN(__builtin_ia32_storelps, "vV2i*V4f", "") BUILTIN(__builtin_ia32_movmskps, "iV4f", "") BUILTIN(__builtin_ia32_pmovmskb, "iV8c", "") BUILTIN(__builtin_ia32_movntps, "vf*V4f", "") BUILTIN(__builtin_ia32_movntq, "vV1LLi*V1LLi", "") BUILTIN(__builtin_ia32_sfence, "v", "") BUILTIN(__builtin_ia32_psadbw, "V4sV8cV8c", "") BUILTIN(__builtin_ia32_rcpps, "V4fV4f", "") BUILTIN(__builtin_ia32_rcpss, "V4fV4f", "") BUILTIN(__builtin_ia32_rsqrtps, "V4fV4f", "") BUILTIN(__builtin_ia32_rsqrtss, "V4fV4f", "") BUILTIN(__builtin_ia32_sqrtps, "V4fV4f", "") BUILTIN(__builtin_ia32_sqrtss, "V4fV4f", "") BUILTIN(__builtin_ia32_shufps, "V4fV4fV4fi", "") BUILTIN(__builtin_ia32_femms, "v", "") BUILTIN(__builtin_ia32_pavgusb, "V8cV8cV8c", "") BUILTIN(__builtin_ia32_pf2id, "V2iV2f", "") BUILTIN(__builtin_ia32_pfacc, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfadd, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfcmpeq, "V2iV2fV2f", "") BUILTIN(__builtin_ia32_pfcmpge, "V2iV2fV2f", "") BUILTIN(__builtin_ia32_pfcmpgt, "V2iV2fV2f", "") BUILTIN(__builtin_ia32_pfmax, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfmin, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfmul, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfrcp, "V2fV2f", "") BUILTIN(__builtin_ia32_pfrcpit1, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfrcpit2, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfrsqrt, "V2fV2f", "") BUILTIN(__builtin_ia32_pfrsqit1, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfsub, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfsubr, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pi2fd, "V2fV2i", "") BUILTIN(__builtin_ia32_pmulhrw, "V4sV4sV4s", "") BUILTIN(__builtin_ia32_pf2iw, "V2iV2f", "") BUILTIN(__builtin_ia32_pfnacc, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pfpnacc, "V2fV2fV2f", "") BUILTIN(__builtin_ia32_pi2fw, "V2fV2i", "") BUILTIN(__builtin_ia32_pswapdsf, "V2fV2f", "") BUILTIN(__builtin_ia32_pswapdsi, "V2iV2i", "") BUILTIN(__builtin_ia32_maskmovdqu, "vV16cV16cc*", "") BUILTIN(__builtin_ia32_loadupd, "V2ddC*", "") BUILTIN(__builtin_ia32_storeupd, "vd*V2d", "") BUILTIN(__builtin_ia32_loadhpd, "V2dV2ddC*", "") BUILTIN(__builtin_ia32_loadlpd, "V2dV2ddC*", "") BUILTIN(__builtin_ia32_movmskpd, "iV2d", "") BUILTIN(__builtin_ia32_pmovmskb128, "iV16c", "") BUILTIN(__builtin_ia32_movnti, "vi*i", "") BUILTIN(__builtin_ia32_movntpd, "vd*V2d", "") BUILTIN(__builtin_ia32_movntdq, "vV2LLi*V2LLi", "") BUILTIN(__builtin_ia32_pshufd, "V4iV4ii", "") BUILTIN(__builtin_ia32_pshuflw, "V8sV8si", "") BUILTIN(__builtin_ia32_pshufhw, "V8sV8si", "") BUILTIN(__builtin_ia32_psadbw128, "V2LLiV16cV16c", "") BUILTIN(__builtin_ia32_sqrtpd, "V2dV2d", "") BUILTIN(__builtin_ia32_sqrtsd, "V2dV2d", "") BUILTIN(__builtin_ia32_shufpd, "V2dV2dV2di", "") BUILTIN(__builtin_ia32_cvtdq2pd, "V2dV4i", "") BUILTIN(__builtin_ia32_cvtdq2ps, "V4fV4i", "") BUILTIN(__builtin_ia32_cvtpd2dq, "V2LLiV2d", "") BUILTIN(__builtin_ia32_cvtpd2pi, "V2iV2d", "") BUILTIN(__builtin_ia32_cvtpd2ps, "V4fV2d", "") BUILTIN(__builtin_ia32_cvttpd2dq, "V4iV2d", "") BUILTIN(__builtin_ia32_cvttpd2pi, "V2iV2d", "") BUILTIN(__builtin_ia32_cvtpi2pd, "V2dV2i", "") BUILTIN(__builtin_ia32_cvtsd2si, "iV2d", "") BUILTIN(__builtin_ia32_cvttsd2si, "iV2d", "") BUILTIN(__builtin_ia32_cvtsd2si64, "LLiV2d", "") BUILTIN(__builtin_ia32_cvttsd2si64, "LLiV2d", "") BUILTIN(__builtin_ia32_cvtps2dq, "V4iV4f", "") BUILTIN(__builtin_ia32_cvtps2pd, "V2dV4f", "") BUILTIN(__builtin_ia32_cvttps2dq, "V4iV4f", "") BUILTIN(__builtin_ia32_cvtsi2sd, "V2dV2di", "") BUILTIN(__builtin_ia32_cvtsi642sd, "V2dV2dLLi", "") BUILTIN(__builtin_ia32_cvtsd2ss, "V4fV4fV2d", "") BUILTIN(__builtin_ia32_cvtss2sd, "V2dV2dV4f", "") BUILTIN(__builtin_ia32_clflush, "vvC*", "") BUILTIN(__builtin_ia32_lfence, "v", "") BUILTIN(__builtin_ia32_mfence, "v", "") BUILTIN(__builtin_ia32_loaddqu, "V16ccC*", "") BUILTIN(__builtin_ia32_storedqu, "vc*V16c", "") BUILTIN(__builtin_ia32_psllwi, "V4sV4si", "") BUILTIN(__builtin_ia32_pslldi, "V2iV2ii", "") BUILTIN(__builtin_ia32_psllqi, "V1LLiV1LLii", "") BUILTIN(__builtin_ia32_psrawi, "V4sV4si", "") BUILTIN(__builtin_ia32_psradi, "V2iV2ii", "") BUILTIN(__builtin_ia32_psrlwi, "V4sV4si", "") BUILTIN(__builtin_ia32_psrldi, "V2iV2ii", "") BUILTIN(__builtin_ia32_psrlqi, "V1LLiV1LLii", "") BUILTIN(__builtin_ia32_pmuludq, "V1LLiV2iV2i", "") BUILTIN(__builtin_ia32_pmuludq128, "V2LLiV4iV4i", "") BUILTIN(__builtin_ia32_psraw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_psrad128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_psrlw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_psrld128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_pslldqi128, "V2LLiV2LLii", "") BUILTIN(__builtin_ia32_psrldqi128, "V2LLiV2LLii", "") BUILTIN(__builtin_ia32_psrlq128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_psllw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pslld128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_psllq128, "V2LLiV2LLiV2LLi", "") BUILTIN(__builtin_ia32_psllwi128, "V8sV8si", "") BUILTIN(__builtin_ia32_pslldi128, "V4iV4ii", "") BUILTIN(__builtin_ia32_psllqi128, "V2LLiV2LLii", "") BUILTIN(__builtin_ia32_psrlwi128, "V8sV8si", "") BUILTIN(__builtin_ia32_psrldi128, "V4iV4ii", "") BUILTIN(__builtin_ia32_psrlqi128, "V2LLiV2LLii", "") BUILTIN(__builtin_ia32_psrawi128, "V8sV8si", "") BUILTIN(__builtin_ia32_psradi128, "V4iV4ii", "") BUILTIN(__builtin_ia32_pmaddwd128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_monitor, "vv*UiUi", "") BUILTIN(__builtin_ia32_mwait, "vUiUi", "") BUILTIN(__builtin_ia32_movshdup, "V4fV4f", "") BUILTIN(__builtin_ia32_movsldup, "V4fV4f", "") BUILTIN(__builtin_ia32_lddqu, "V16ccC*", "") BUILTIN(__builtin_ia32_palignr128, "V2LLiV2LLiV2LLii", "") BUILTIN(__builtin_ia32_palignr, "V1LLiV1LLiV1LLis", "") BUILTIN(__builtin_ia32_vec_init_v2si, "V2iii", "") BUILTIN(__builtin_ia32_vec_init_v4hi, "V4sssss", "") BUILTIN(__builtin_ia32_vec_init_v8qi, "V8ccccccccc", "") BUILTIN(__builtin_ia32_vec_ext_v2df, "dV2di", "") BUILTIN(__builtin_ia32_vec_ext_v2di, "LLiV2LLii", "") BUILTIN(__builtin_ia32_vec_ext_v4sf, "fV4fi", "") BUILTIN(__builtin_ia32_vec_ext_v4si, "iV4ii", "") BUILTIN(__builtin_ia32_vec_ext_v8hi, "UsV8si", "") BUILTIN(__builtin_ia32_vec_ext_v4hi, "sV4si", "") BUILTIN(__builtin_ia32_vec_ext_v2si, "iV2ii", "") BUILTIN(__builtin_ia32_vec_set_v8hi, "V8sV8ssi", "") BUILTIN(__builtin_ia32_vec_set_v4hi, "V4sV4ssi", "") BUILTIN(__builtin_ia32_vec_set_v16qi, "V16cV16cii", "") BUILTIN(__builtin_ia32_vec_set_v4si, "V4iV4iii", "") BUILTIN(__builtin_ia32_vec_set_v2di, "V2LLiV2LLiLLii", "") BUILTIN(__builtin_ia32_insertps128, "V4fV4fV4fi", "") BUILTIN(__builtin_ia32_movqv4si, "V4iV4i", "") BUILTIN(__builtin_ia32_loadlv4si, "V4iV2i*", "") BUILTIN(__builtin_ia32_storelv4si, "vV2i*V2LLi", "") BUILTIN(__builtin_ia32_pblendvb128, "V16cV16cV16cV16c", "") BUILTIN(__builtin_ia32_pblendw128, "V8sV8sV8si", "") BUILTIN(__builtin_ia32_blendpd, "V2dV2dV2di", "") BUILTIN(__builtin_ia32_blendps, "V4fV4fV4fi", "") BUILTIN(__builtin_ia32_blendvpd, "V2dV2dV2dV2d", "") BUILTIN(__builtin_ia32_blendvps, "V4fV4fV4fV4f", "") BUILTIN(__builtin_ia32_packusdw128, "V8sV4iV4i", "") BUILTIN(__builtin_ia32_pmaxsb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pmaxsd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_pmaxud128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_pmaxuw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pminsb128, "V16cV16cV16c", "") BUILTIN(__builtin_ia32_pminsd128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_pminud128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_pminuw128, "V8sV8sV8s", "") BUILTIN(__builtin_ia32_pmovsxbd128, "V4iV16c", "") BUILTIN(__builtin_ia32_pmovsxbq128, "V2LLiV16c", "") BUILTIN(__builtin_ia32_pmovsxbw128, "V8sV16c", "") BUILTIN(__builtin_ia32_pmovsxdq128, "V2LLiV4i", "") BUILTIN(__builtin_ia32_pmovsxwd128, "V4iV8s", "") BUILTIN(__builtin_ia32_pmovsxwq128, "V2LLiV8s", "") BUILTIN(__builtin_ia32_pmovzxbd128, "V4iV16c", "") BUILTIN(__builtin_ia32_pmovzxbq128, "V2LLiV16c", "") BUILTIN(__builtin_ia32_pmovzxbw128, "V8sV16c", "") BUILTIN(__builtin_ia32_pmovzxdq128, "V2LLiV4i", "") BUILTIN(__builtin_ia32_pmovzxwd128, "V4iV8s", "") BUILTIN(__builtin_ia32_pmovzxwq128, "V2LLiV8s", "") BUILTIN(__builtin_ia32_pmuldq128, "V2LLiV4iV4i", "") BUILTIN(__builtin_ia32_pmulld128, "V4iV4iV4i", "") BUILTIN(__builtin_ia32_roundps, "V4fV4fi", "") BUILTIN(__builtin_ia32_roundss, "V4fV4fi", "") BUILTIN(__builtin_ia32_roundsd, "V2dV2di", "") BUILTIN(__builtin_ia32_roundpd, "V2dV2di", "") #undef BUILTIN <file_sep>/test/CodeGen/ext-vector-shuffle.c // RUN: clang-cc %s -emit-llvm -o - | not grep 'extractelement' // RUN: clang-cc %s -emit-llvm -o - | not grep 'insertelement' // RUN: clang-cc %s -emit-llvm -o - | grep 'shufflevector' typedef __attribute__(( ext_vector_type(2) )) float float2; typedef __attribute__(( ext_vector_type(4) )) float float4; float2 test1(float4 V) { return V.xy + V.wz; } float4 test2(float4 V) { float2 W = V.ww; return W.xyxy + W.yxyx; } <file_sep>/test/SemaCXX/overloaded-operator.cpp // RUN: clang-cc -fsyntax-only -verify %s class X { }; X operator+(X, X); void f(X x) { x = x + x; } struct Y; struct Z; struct Y { Y(const Z&); }; struct Z { Z(const Y&); }; Y operator+(Y, Y); bool operator-(Y, Y); // expected-note{{candidate function}} bool operator-(Z, Z); // expected-note{{candidate function}} void g(Y y, Z z) { y = y + z; bool b = y - z; // expected-error{{use of overloaded operator '-' is ambiguous; candidates are:}} } struct A { bool operator==(Z&); // expected-note{{candidate function}} }; A make_A(); bool operator==(A&, Z&); // expected-note{{candidate function}} void h(A a, const A ac, Z z) { make_A() == z; a == z; // expected-error{{use of overloaded operator '==' is ambiguous; candidates are:}} ac == z; // expected-error{{invalid operands to binary expression ('struct A const' and 'struct Z')}} } struct B { bool operator==(const B&) const; void test(Z z) { make_A() == z; } }; enum Enum1 { }; enum Enum2 { }; struct E1 { E1(Enum1) { } }; struct E2 { E2(Enum2); }; // C++ [over.match.oper]p3 - enum restriction. float& operator==(E1, E2); void enum_test(Enum1 enum1, Enum2 enum2, E1 e1, E2 e2) { float &f1 = (e1 == e2); float &f2 = (enum1 == e2); float &f3 = (e1 == enum2); float &f4 = (enum1 == enum2); // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a temporary of type '_Bool'}} } struct PostInc { PostInc operator++(int); PostInc& operator++(); }; struct PostDec { PostDec operator--(int); PostDec& operator--(); }; void incdec_test(PostInc pi, PostDec pd) { const PostInc& pi1 = pi++; const PostDec& pd1 = pd--; PostInc &pi2 = ++pi; PostDec &pd2 = --pd; } struct SmartPtr { int& operator*(); long& operator*() const volatile; }; void test_smartptr(SmartPtr ptr, const SmartPtr cptr, const volatile SmartPtr cvptr) { int &ir = *ptr; long &lr = *cptr; long &lr2 = *cvptr; } struct ArrayLike { int& operator[](int); }; void test_arraylike(ArrayLike a) { int& ir = a[17]; } struct SmartRef { int* operator&(); }; void test_smartref(SmartRef r) { int* ip = &r; } bool& operator,(X, Y); void test_comma(X x, Y y) { bool& b1 = (x, y); X& xr = (x, x); } struct Callable { int& operator()(int, double = 2.71828); // expected-note{{candidate function}} float& operator()(int, double, long, ...); // expected-note{{candidate function}} double& operator()(float); // expected-note{{candidate function}} }; struct Callable2 { int& operator()(int i = 0); double& operator()(...) const; }; void test_callable(Callable c, Callable2 c2, const Callable2& c2c) { int &ir = c(1); float &fr = c(1, 3.14159, 17, 42); c(); // expected-error{{no matching function for call to object of type 'struct Callable'; candidates are:}} double &dr = c(1.0f); int &ir2 = c2(); int &ir3 = c2(1); double &fr2 = c2c(); } typedef float FLOAT; typedef int& INTREF; typedef INTREF Func1(FLOAT, double); typedef float& Func2(int, double); struct ConvertToFunc { operator Func1*(); // expected-note{{conversion candidate of type 'INTREF (*)(FLOAT, double)'}} operator Func2&(); // expected-note{{conversion candidate of type 'float &(&)(int, double)'}} void operator()(); }; void test_funcptr_call(ConvertToFunc ctf) { int &i1 = ctf(1.0f, 2.0); float &f2 = ctf((short int)1, 1.0f); ctf((long int)17, 2.0); // expected-error{{error: call to object of type 'struct ConvertToFunc' is ambiguous; candidates are:}} ctf(); } struct HasMember { int m; }; struct Arrow1 { HasMember* operator->(); }; struct Arrow2 { Arrow1 operator->(); // expected-note{{candidate function}} }; void test_arrow(Arrow1 a1, Arrow2 a2, const Arrow2 a3) { int &i1 = a1->m; int &i2 = a2->m; a3->m; // expected-error{{no viable overloaded 'operator->'; candidate is}} } struct CopyConBase { }; struct CopyCon : public CopyConBase { CopyCon(const CopyConBase &Base); CopyCon(const CopyConBase *Base) { *this = *Base; } }; namespace N { struct X { }; } namespace M { N::X operator+(N::X, N::X); } namespace M { void test_X(N::X x) { (void)(x + x); } } <file_sep>/tools/clang-cc/DependencyFile.cpp //===--- DependencyFile.cpp - Generate dependency file --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This code generates dependency files. // //===----------------------------------------------------------------------===// #include "clang-cc.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/FileManager.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/DirectoryLookup.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/StringSet.h" #include "llvm/System/Path.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #include <string> using namespace clang; namespace { class VISIBILITY_HIDDEN DependencyFileCallback : public PPCallbacks { std::vector<std::string> Files; llvm::StringSet<> FilesSet; const Preprocessor *PP; std::vector<std::string> Targets; llvm::raw_ostream *OS; private: bool FileMatchesDepCriteria(const char *Filename, SrcMgr::CharacteristicKind FileType); void OutputDependencyFile(); public: DependencyFileCallback(const Preprocessor *_PP, llvm::raw_ostream *_OS, const std::vector<std::string> &_Targets) : PP(_PP), Targets(_Targets), OS(_OS) { } ~DependencyFileCallback() { OutputDependencyFile(); OS->flush(); delete OS; } virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType); }; } //===----------------------------------------------------------------------===// // Dependency file options //===----------------------------------------------------------------------===// static llvm::cl::opt<std::string> DependencyFile("dependency-file", llvm::cl::desc("Filename (or -) to write dependency output to")); static llvm::cl::opt<bool> DependenciesIncludeSystemHeaders("sys-header-deps", llvm::cl::desc("Include system headers in dependency output")); static llvm::cl::list<std::string> DependencyTargets("MT", llvm::cl::desc("Specify target for dependency")); // FIXME: Implement feature static llvm::cl::opt<bool> PhonyDependencyTarget("MP", llvm::cl::desc("Create phony target for each dependency " "(other than main file)")); bool clang::CreateDependencyFileGen(Preprocessor *PP, std::string &ErrStr) { ErrStr = ""; if (DependencyFile.empty()) return false; if (DependencyTargets.empty()) { ErrStr = "-dependency-file requires at least one -MT option\n"; return false; } std::string ErrMsg; llvm::raw_ostream *OS; if (DependencyFile == "-") { OS = new llvm::raw_stdout_ostream(); } else { OS = new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr); if (!ErrMsg.empty()) { ErrStr = "unable to open dependency file: " + ErrMsg; return false; } } DependencyFileCallback *PPDep = new DependencyFileCallback(PP, OS, DependencyTargets); PP->setPPCallbacks(PPDep); return true; } /// FileMatchesDepCriteria - Determine whether the given Filename should be /// considered as a dependency. bool DependencyFileCallback::FileMatchesDepCriteria(const char *Filename, SrcMgr::CharacteristicKind FileType) { if (strcmp("<built-in>", Filename) == 0) return false; if (DependenciesIncludeSystemHeaders) return true; return FileType == SrcMgr::C_User; } void DependencyFileCallback::FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType) { if (Reason != PPCallbacks::EnterFile) return; // Dependency generation really does want to go all the way to the // file entry for a source location to find out what is depended on. // We do not want #line markers to affect dependency generation! SourceManager &SM = PP->getSourceManager(); const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(SM.getInstantiationLoc(Loc))); if (FE == 0) return; const char *Filename = FE->getName(); if (!FileMatchesDepCriteria(Filename, FileType)) return; // Remove leading "./" if (Filename[0] == '.' && Filename[1] == '/') Filename = &Filename[2]; if (FilesSet.insert(Filename)) Files.push_back(Filename); } void DependencyFileCallback::OutputDependencyFile() { // Write out the dependency targets, trying to avoid overly long // lines when possible. We try our best to emit exactly the same // dependency file as GCC (4.2), assuming the included files are the // same. const unsigned MaxColumns = 75; unsigned Columns = 0; for (std::vector<std::string>::iterator I = Targets.begin(), E = Targets.end(); I != E; ++I) { unsigned N = I->length(); if (Columns == 0) { Columns += N; *OS << *I; } else if (Columns + N + 2 > MaxColumns) { Columns = N + 2; *OS << " \\\n " << *I; } else { Columns += N + 1; *OS << ' ' << *I; } } *OS << ':'; Columns += 1; // Now add each dependency in the order it was seen, but avoiding // duplicates. for (std::vector<std::string>::iterator I = Files.begin(), E = Files.end(); I != E; ++I) { // Start a new line if this would exceed the column limit. Make // sure to leave space for a trailing " \" in case we need to // break the line on the next iteration. unsigned N = I->length(); if (Columns + (N + 1) + 2 > MaxColumns) { *OS << " \\\n "; Columns = 2; } *OS << ' ' << *I; Columns += N + 1; } *OS << '\n'; // Create phony targets if requested. if (PhonyDependencyTarget) { // Skip the first entry, this is always the input file itself. for (std::vector<std::string>::iterator I = Files.begin() + 1, E = Files.end(); I != E; ++I) { *OS << '\n'; *OS << *I << ":\n"; } } } <file_sep>/tools/ccc/test/ccc/pth.c // RUN: cp %s %t.h && // RUN: xcc %t.h && // RUN: xcc -### -S -include %t.h -x c /dev/null &> %t.log && // RUN: grep '"-token-cache" ".*/pth.c.out.tmp.h.pth"' %t.log // RUN: true <file_sep>/test/CodeGen/attributes.c // RUN: clang-cc -emit-llvm -o %t %s && // RUN: grep 't1.*noreturn' %t && // RUN: grep 't2.*nounwind' %t && // RUN: grep 'weak.*t3' %t && // RUN: grep 'hidden.*t4' %t && // RUN: grep 't5.*weak' %t && // RUN: grep 't6.*protected' %t && // RUN: grep 't7.*noreturn' %t && // RUN: grep 't7.*nounwind' %t && // RUN: grep 't9.*alias.*weak.*t8' %t && // RUN: grep '@t10().*section "SECT"' %t && // RUN: grep '@t11().*section "SECT"' %t && // RUN: grep '@t12 =.*section "SECT"' %t && // RUN: grep '@t13 =.*section "SECT"' %t && // RUN: grep '@t14.x =.*section "SECT"' %t // RUN: grep 'declare extern_weak i32 @t15()' %t && // RUN: grep '@t16 = extern_weak global i32' %t void t1() __attribute__((noreturn)); void t1() {} void t2() __attribute__((nothrow)); void t2() {} void t3() __attribute__((weak)); void t3() {} void t4() __attribute__((visibility("hidden"))); void t4() {} int t5 __attribute__((weak)) = 2; int t6 __attribute__((visibility("protected"))); void t7() __attribute__((noreturn, nothrow)); void t7() {} void __t8() {} void t9() __attribute__((weak, alias("__t8"))); void t10(void) __attribute__((section("SECT"))); void t10(void) {} void __attribute__((section("SECT"))) t11(void) {} int t12 __attribute__((section("SECT"))); struct s0 { int x; }; struct s0 t13 __attribute__((section("SECT"))) = { 0 }; void t14(void) { static int x __attribute__((section("SECT"))) = 0; } int __attribute__((weak_import)) t15(void); extern int t16 __attribute__((weak_import)); int t17() { return t15() + t16; } <file_sep>/lib/Driver/Option.cpp //===--- Option.cpp - Abstract Driver Options ---------------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/Option.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <algorithm> using namespace clang::driver; Option::Option(OptionClass _Kind, options::ID _ID, const char *_Name, const OptionGroup *_Group, const Option *_Alias) : Kind(_Kind), ID(_ID), Name(_Name), Group(_Group), Alias(_Alias), Unsupported(false), LinkerInput(false), NoOptAsInput(false), ForceSeparateRender(false), ForceJoinedRender(false), DriverOption(false), NoArgumentUnused(false) { // Multi-level aliases are not supported, and alias options cannot // have groups. This just simplifies option tracking, it is not an // inherent limitation. assert((!Alias || (!Alias->Alias && !Group)) && "Multi-level aliases and aliases with groups are unsupported."); } Option::~Option() { } void Option::dump() const { llvm::errs() << "<"; switch (Kind) { default: assert(0 && "Invalid kind"); #define P(N) case N: llvm::errs() << #N; break P(GroupClass); P(InputClass); P(UnknownClass); P(FlagClass); P(JoinedClass); P(SeparateClass); P(CommaJoinedClass); P(MultiArgClass); P(JoinedOrSeparateClass); P(JoinedAndSeparateClass); #undef P } llvm::errs() << " Name:\"" << Name << '"'; if (Group) { llvm::errs() << " Group:"; Group->dump(); } if (Alias) { llvm::errs() << " Alias:"; Alias->dump(); } if (const MultiArgOption *MOA = dyn_cast<MultiArgOption>(this)) llvm::errs() << " NumArgs:" << MOA->getNumArgs(); llvm::errs() << ">\n"; } bool Option::matches(const Option *Opt) const { // Aliases are never considered in matching. if (Opt->getAlias()) return matches(Opt->getAlias()); if (Alias) return Alias->matches(Opt); if (this == Opt) return true; if (Group) return Group->matches(Opt); return false; } bool Option::matches(options::ID Id) const { // FIXME: Decide what to do here; we should either pull out the // handling of alias on the option for Id from the other matches, or // find some other solution (which hopefully doesn't require using // the option table). if (Alias) return Alias->matches(Id); if (ID == Id) return true; if (Group) return Group->matches(Id); return false; } OptionGroup::OptionGroup(options::ID ID, const char *Name, const OptionGroup *Group) : Option(Option::GroupClass, ID, Name, Group, 0) { } Arg *OptionGroup::accept(const InputArgList &Args, unsigned &Index) const { assert(0 && "accept() should never be called on an OptionGroup"); return 0; } InputOption::InputOption() : Option(Option::InputClass, options::OPT_INPUT, "<input>", 0, 0) { } Arg *InputOption::accept(const InputArgList &Args, unsigned &Index) const { assert(0 && "accept() should never be called on an InputOption"); return 0; } UnknownOption::UnknownOption() : Option(Option::UnknownClass, options::OPT_UNKNOWN, "<unknown>", 0, 0) { } Arg *UnknownOption::accept(const InputArgList &Args, unsigned &Index) const { assert(0 && "accept() should never be called on an UnknownOption"); return 0; } FlagOption::FlagOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::FlagClass, ID, Name, Group, Alias) { } Arg *FlagOption::accept(const InputArgList &Args, unsigned &Index) const { // Matches iff this is an exact match. // FIXME: Avoid strlen. if (strlen(getName()) != strlen(Args.getArgString(Index))) return 0; return new FlagArg(this, Index++); } JoinedOption::JoinedOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::JoinedClass, ID, Name, Group, Alias) { } Arg *JoinedOption::accept(const InputArgList &Args, unsigned &Index) const { // Always matches. return new JoinedArg(this, Index++); } CommaJoinedOption::CommaJoinedOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::CommaJoinedClass, ID, Name, Group, Alias) { } Arg *CommaJoinedOption::accept(const InputArgList &Args, unsigned &Index) const { // Always matches. We count the commas now so we can answer // getNumValues easily. // Get the suffix string. // FIXME: Avoid strlen, and move to helper method? const char *Suffix = Args.getArgString(Index) + strlen(getName()); return new CommaJoinedArg(this, Index++, Suffix); } SeparateOption::SeparateOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::SeparateClass, ID, Name, Group, Alias) { } Arg *SeparateOption::accept(const InputArgList &Args, unsigned &Index) const { // Matches iff this is an exact match. // FIXME: Avoid strlen. if (strlen(getName()) != strlen(Args.getArgString(Index))) return 0; Index += 2; if (Index > Args.getNumInputArgStrings()) return 0; return new SeparateArg(this, Index - 2, 1); } MultiArgOption::MultiArgOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias, unsigned _NumArgs) : Option(Option::MultiArgClass, ID, Name, Group, Alias), NumArgs(_NumArgs) { assert(NumArgs > 1 && "Invalid MultiArgOption!"); } Arg *MultiArgOption::accept(const InputArgList &Args, unsigned &Index) const { // Matches iff this is an exact match. // FIXME: Avoid strlen. if (strlen(getName()) != strlen(Args.getArgString(Index))) return 0; Index += 1 + NumArgs; if (Index > Args.getNumInputArgStrings()) return 0; return new SeparateArg(this, Index - 1 - NumArgs, NumArgs); } JoinedOrSeparateOption::JoinedOrSeparateOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::JoinedOrSeparateClass, ID, Name, Group, Alias) { } Arg *JoinedOrSeparateOption::accept(const InputArgList &Args, unsigned &Index) const { // If this is not an exact match, it is a joined arg. // FIXME: Avoid strlen. if (strlen(getName()) != strlen(Args.getArgString(Index))) return new JoinedArg(this, Index++); // Otherwise it must be separate. Index += 2; if (Index > Args.getNumInputArgStrings()) return 0; return new SeparateArg(this, Index - 2, 1); } JoinedAndSeparateOption::JoinedAndSeparateOption(options::ID ID, const char *Name, const OptionGroup *Group, const Option *Alias) : Option(Option::JoinedAndSeparateClass, ID, Name, Group, Alias) { } Arg *JoinedAndSeparateOption::accept(const InputArgList &Args, unsigned &Index) const { // Always matches. Index += 2; if (Index > Args.getNumInputArgStrings()) return 0; return new JoinedAndSeparateArg(this, Index - 2); } <file_sep>/test/SemaCXX/bool.cpp // RUN: clang-cc -fsyntax-only -verify %s // Bool literals can be enum values. enum { ReadWrite = false, ReadOnly = true }; // bool cannot be decremented, and gives a warning on increment void test(bool b) { ++b; // expected-warning {{incrementing expression of type bool is deprecated}} b++; // expected-warning {{incrementing expression of type bool is deprecated}} --b; // expected-error {{cannot decrement expression of type bool}} b--; // expected-error {{cannot decrement expression of type bool}} } <file_sep>/lib/Analysis/BasicObjCFoundationChecks.cpp //== BasicObjCFoundationChecks.cpp - Simple Apple-Foundation checks -*- C++ -*-- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines BasicObjCFoundationChecks, a class that encapsulates // a set of simple checks to run on Objective-C code using Apple's Foundation // classes. // //===----------------------------------------------------------------------===// #include "BasicObjCFoundationChecks.h" #include "clang/Analysis/PathSensitive/ExplodedGraph.h" #include "clang/Analysis/PathSensitive/GRSimpleAPICheck.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Analysis/PathSensitive/MemRegion.h" #include "clang/Analysis/PathDiagnostic.h" #include "clang/Analysis/LocalCheckers.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ASTContext.h" #include "llvm/Support/Compiler.h" using namespace clang; static ObjCInterfaceType* GetReceiverType(ObjCMessageExpr* ME) { Expr* Receiver = ME->getReceiver(); if (!Receiver) return NULL; QualType X = Receiver->getType(); if (X->isPointerType()) { Type* TP = X.getTypePtr(); const PointerType* T = TP->getAsPointerType(); return dyn_cast<ObjCInterfaceType>(T->getPointeeType().getTypePtr()); } // FIXME: Support ObjCQualifiedIdType? return NULL; } static const char* GetReceiverNameType(ObjCMessageExpr* ME) { ObjCInterfaceType* ReceiverType = GetReceiverType(ME); return ReceiverType ? ReceiverType->getDecl()->getIdentifier()->getName() : NULL; } namespace { class VISIBILITY_HIDDEN APIMisuse : public BugType { public: APIMisuse(const char* name) : BugType(name, "API Misuse (Apple)") {} }; class VISIBILITY_HIDDEN BasicObjCFoundationChecks : public GRSimpleAPICheck { APIMisuse *BT; BugReporter& BR; ASTContext &Ctx; GRStateManager* VMgr; SVal GetSVal(const GRState* St, Expr* E) { return VMgr->GetSVal(St, E); } bool isNSString(ObjCInterfaceType* T, const char* suffix); bool AuditNSString(NodeTy* N, ObjCMessageExpr* ME); void Warn(NodeTy* N, Expr* E, const std::string& s); void WarnNilArg(NodeTy* N, Expr* E); bool CheckNilArg(NodeTy* N, unsigned Arg); public: BasicObjCFoundationChecks(ASTContext& ctx, GRStateManager* vmgr, BugReporter& br) : BT(0), BR(br), Ctx(ctx), VMgr(vmgr) {} bool Audit(ExplodedNode<GRState>* N, GRStateManager&); private: void WarnNilArg(NodeTy* N, ObjCMessageExpr* ME, unsigned Arg) { std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Argument to '" << GetReceiverNameType(ME) << "' method '" << ME->getSelector().getAsString() << "' cannot be nil."; // Lazily create the BugType object for NilArg. This will be owned // by the BugReporter object 'BR' once we call BR.EmitWarning. if (!BT) BT = new APIMisuse("nil argument"); RangedBugReport *R = new RangedBugReport(*BT, os.str().c_str(), N); R->addRange(ME->getArg(Arg)->getSourceRange()); BR.EmitReport(R); } }; } // end anonymous namespace GRSimpleAPICheck* clang::CreateBasicObjCFoundationChecks(ASTContext& Ctx, GRStateManager* VMgr, BugReporter& BR) { return new BasicObjCFoundationChecks(Ctx, VMgr, BR); } bool BasicObjCFoundationChecks::Audit(ExplodedNode<GRState>* N, GRStateManager&) { ObjCMessageExpr* ME = cast<ObjCMessageExpr>(cast<PostStmt>(N->getLocation()).getStmt()); ObjCInterfaceType* ReceiverType = GetReceiverType(ME); if (!ReceiverType) return false; const char* name = ReceiverType->getDecl()->getIdentifier()->getName(); if (!name) return false; if (name[0] != 'N' || name[1] != 'S') return false; name += 2; // FIXME: Make all of this faster. if (isNSString(ReceiverType, name)) return AuditNSString(N, ME); return false; } static inline bool isNil(SVal X) { return isa<loc::ConcreteInt>(X); } //===----------------------------------------------------------------------===// // Error reporting. //===----------------------------------------------------------------------===// bool BasicObjCFoundationChecks::CheckNilArg(NodeTy* N, unsigned Arg) { ObjCMessageExpr* ME = cast<ObjCMessageExpr>(cast<PostStmt>(N->getLocation()).getStmt()); Expr * E = ME->getArg(Arg); if (isNil(GetSVal(N->getState(), E))) { WarnNilArg(N, ME, Arg); return true; } return false; } //===----------------------------------------------------------------------===// // NSString checking. //===----------------------------------------------------------------------===// bool BasicObjCFoundationChecks::isNSString(ObjCInterfaceType* T, const char* suffix) { return !strcmp("String", suffix) || !strcmp("MutableString", suffix); } bool BasicObjCFoundationChecks::AuditNSString(NodeTy* N, ObjCMessageExpr* ME) { Selector S = ME->getSelector(); if (S.isUnarySelector()) return false; // FIXME: This is going to be really slow doing these checks with // lexical comparisons. std::string name = S.getAsString(); assert (!name.empty()); const char* cstr = &name[0]; unsigned len = name.size(); switch (len) { default: break; case 8: if (!strcmp(cstr, "compare:")) return CheckNilArg(N, 0); break; case 15: // FIXME: Checking for initWithFormat: will not work in most cases // yet because [NSString alloc] returns id, not NSString*. We will // need support for tracking expected-type information in the analyzer // to find these errors. if (!strcmp(cstr, "initWithFormat:")) return CheckNilArg(N, 0); break; case 16: if (!strcmp(cstr, "compare:options:")) return CheckNilArg(N, 0); break; case 22: if (!strcmp(cstr, "compare:options:range:")) return CheckNilArg(N, 0); break; case 23: if (!strcmp(cstr, "caseInsensitiveCompare:")) return CheckNilArg(N, 0); break; case 29: if (!strcmp(cstr, "compare:options:range:locale:")) return CheckNilArg(N, 0); break; case 37: if (!strcmp(cstr, "componentsSeparatedByCharactersInSet:")) return CheckNilArg(N, 0); break; } return false; } //===----------------------------------------------------------------------===// // Error reporting. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN AuditCFNumberCreate : public GRSimpleAPICheck { APIMisuse* BT; // FIXME: Either this should be refactored into GRSimpleAPICheck, or // it should always be passed with a call to Audit. The latter // approach makes this class more stateless. ASTContext& Ctx; IdentifierInfo* II; GRStateManager* VMgr; BugReporter& BR; SVal GetSVal(const GRState* St, Expr* E) { return VMgr->GetSVal(St, E); } public: AuditCFNumberCreate(ASTContext& ctx, GRStateManager* vmgr, BugReporter& br) : BT(0), Ctx(ctx), II(&Ctx.Idents.get("CFNumberCreate")), VMgr(vmgr), BR(br){} ~AuditCFNumberCreate() {} bool Audit(ExplodedNode<GRState>* N, GRStateManager&); private: void AddError(const TypedRegion* R, Expr* Ex, ExplodedNode<GRState> *N, uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind); }; } // end anonymous namespace enum CFNumberType { kCFNumberSInt8Type = 1, kCFNumberSInt16Type = 2, kCFNumberSInt32Type = 3, kCFNumberSInt64Type = 4, kCFNumberFloat32Type = 5, kCFNumberFloat64Type = 6, kCFNumberCharType = 7, kCFNumberShortType = 8, kCFNumberIntType = 9, kCFNumberLongType = 10, kCFNumberLongLongType = 11, kCFNumberFloatType = 12, kCFNumberDoubleType = 13, kCFNumberCFIndexType = 14, kCFNumberNSIntegerType = 15, kCFNumberCGFloatType = 16 }; namespace { template<typename T> class Optional { bool IsKnown; T Val; public: Optional() : IsKnown(false), Val(0) {} Optional(const T& val) : IsKnown(true), Val(val) {} bool isKnown() const { return IsKnown; } const T& getValue() const { assert (isKnown()); return Val; } operator const T&() const { return getValue(); } }; } static Optional<uint64_t> GetCFNumberSize(ASTContext& Ctx, uint64_t i) { static unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 }; if (i < kCFNumberCharType) return FixedSize[i-1]; QualType T; switch (i) { case kCFNumberCharType: T = Ctx.CharTy; break; case kCFNumberShortType: T = Ctx.ShortTy; break; case kCFNumberIntType: T = Ctx.IntTy; break; case kCFNumberLongType: T = Ctx.LongTy; break; case kCFNumberLongLongType: T = Ctx.LongLongTy; break; case kCFNumberFloatType: T = Ctx.FloatTy; break; case kCFNumberDoubleType: T = Ctx.DoubleTy; break; case kCFNumberCFIndexType: case kCFNumberNSIntegerType: case kCFNumberCGFloatType: // FIXME: We need a way to map from names to Type*. default: return Optional<uint64_t>(); } return Ctx.getTypeSize(T); } #if 0 static const char* GetCFNumberTypeStr(uint64_t i) { static const char* Names[] = { "kCFNumberSInt8Type", "kCFNumberSInt16Type", "kCFNumberSInt32Type", "kCFNumberSInt64Type", "kCFNumberFloat32Type", "kCFNumberFloat64Type", "kCFNumberCharType", "kCFNumberShortType", "kCFNumberIntType", "kCFNumberLongType", "kCFNumberLongLongType", "kCFNumberFloatType", "kCFNumberDoubleType", "kCFNumberCFIndexType", "kCFNumberNSIntegerType", "kCFNumberCGFloatType" }; return i <= kCFNumberCGFloatType ? Names[i-1] : "Invalid CFNumberType"; } #endif bool AuditCFNumberCreate::Audit(ExplodedNode<GRState>* N,GRStateManager&){ CallExpr* CE = cast<CallExpr>(cast<PostStmt>(N->getLocation()).getStmt()); Expr* Callee = CE->getCallee(); SVal CallV = GetSVal(N->getState(), Callee); loc::FuncVal* FuncV = dyn_cast<loc::FuncVal>(&CallV); if (!FuncV || FuncV->getDecl()->getIdentifier() != II || CE->getNumArgs()!=3) return false; // Get the value of the "theType" argument. SVal TheTypeVal = GetSVal(N->getState(), CE->getArg(1)); // FIXME: We really should allow ranges of valid theType values, and // bifurcate the state appropriately. nonloc::ConcreteInt* V = dyn_cast<nonloc::ConcreteInt>(&TheTypeVal); if (!V) return false; uint64_t NumberKind = V->getValue().getLimitedValue(); Optional<uint64_t> TargetSize = GetCFNumberSize(Ctx, NumberKind); // FIXME: In some cases we can emit an error. if (!TargetSize.isKnown()) return false; // Look at the value of the integer being passed by reference. Essentially // we want to catch cases where the value passed in is not equal to the // size of the type being created. SVal TheValueExpr = GetSVal(N->getState(), CE->getArg(2)); // FIXME: Eventually we should handle arbitrary locations. We can do this // by having an enhanced memory model that does low-level typing. loc::MemRegionVal* LV = dyn_cast<loc::MemRegionVal>(&TheValueExpr); if (!LV) return false; const TypedRegion* R = dyn_cast<TypedRegion>(LV->getRegion()); if (!R) return false; while (const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R)) { R = dyn_cast<TypedRegion>(ATR->getSuperRegion()); if (!R) return false; } QualType T = Ctx.getCanonicalType(R->getRValueType(Ctx)); // FIXME: If the pointee isn't an integer type, should we flag a warning? // People can do weird stuff with pointers. if (!T->isIntegerType()) return false; uint64_t SourceSize = Ctx.getTypeSize(T); // CHECK: is SourceSize == TargetSize if (SourceSize == TargetSize) return false; AddError(R, CE->getArg(2), N, SourceSize, TargetSize, NumberKind); // FIXME: We can actually create an abstract "CFNumber" object that has // the bits initialized to the provided values. return SourceSize < TargetSize; } void AuditCFNumberCreate::AddError(const TypedRegion* R, Expr* Ex, ExplodedNode<GRState> *N, uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind) { std::string sbuf; llvm::raw_string_ostream os(sbuf); os << (SourceSize == 8 ? "An " : "A ") << SourceSize << " bit integer is used to initialize a CFNumber " "object that represents " << (TargetSize == 8 ? "an " : "a ") << TargetSize << " bit integer. "; if (SourceSize < TargetSize) os << (TargetSize - SourceSize) << " bits of the CFNumber value will be garbage." ; else os << (SourceSize - TargetSize) << " bits of the input integer will be lost."; // Lazily create the BugType object. This will be owned // by the BugReporter object 'BR' once we call BR.EmitWarning. if (!BT) BT = new APIMisuse("Bad use of CFNumberCreate"); RangedBugReport *report = new RangedBugReport(*BT, os.str().c_str(), N); report->addRange(Ex->getSourceRange()); BR.EmitReport(report); } GRSimpleAPICheck* clang::CreateAuditCFNumberCreate(ASTContext& Ctx, GRStateManager* VMgr, BugReporter& BR) { return new AuditCFNumberCreate(Ctx, VMgr, BR); } //===----------------------------------------------------------------------===// // Check registration. void clang::RegisterAppleChecks(GRExprEngine& Eng) { ASTContext& Ctx = Eng.getContext(); GRStateManager* VMgr = &Eng.getStateManager(); BugReporter &BR = Eng.getBugReporter(); Eng.AddCheck(CreateBasicObjCFoundationChecks(Ctx, VMgr, BR), Stmt::ObjCMessageExprClass); Eng.AddCheck(CreateAuditCFNumberCreate(Ctx, VMgr, BR), Stmt::CallExprClass); RegisterNSErrorChecks(BR, Eng); } <file_sep>/include/clang/Frontend/InitHeaderSearch.h //===--- InitHeaderSearch.h - Initialize header search paths ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the InitHeaderSearch class. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_INIT_HEADER_SEARCH_H_ #define LLVM_CLANG_FRONTEND_INIT_HEADER_SEARCH_H_ #include <string> #include <vector> #include "clang/Lex/DirectoryLookup.h" namespace clang { class HeaderSearch; class LangOptions; /// InitHeaderSearch - This class makes it easier to set the search paths of /// a HeaderSearch object. InitHeaderSearch stores several search path lists /// internally, which can be sent to a HeaderSearch object in one swoop. class InitHeaderSearch { std::vector<DirectoryLookup> IncludeGroup[4]; HeaderSearch& Headers; bool Verbose; std::string isysroot; public: /// InitHeaderSearch::IncludeDirGroup - Identifies the several search path /// lists stored internally. enum IncludeDirGroup { Quoted = 0, //< `#include ""` paths. Thing `gcc -iquote`. Angled, //< Paths for both `#include ""` and `#include <>`. (`-I`) System, //< Like Angled, but marks system directories. After //< Like System, but searched after the system directories. }; InitHeaderSearch(HeaderSearch &HS, bool verbose = false, const std::string &iSysroot = "") : Headers(HS), Verbose(verbose), isysroot(iSysroot) {} /// AddPath - Add the specified path to the specified group list. void AddPath(const std::string &Path, IncludeDirGroup Group, bool isCXXAware, bool isUserSupplied, bool isFramework, bool IgnoreSysRoot = false); /// AddEnvVarPaths - Add a list of paths from an environment variable to a /// header search list. void AddEnvVarPaths(const char *Name); /// AddDefaultEnvVarPaths - Adds list of paths from default environment /// variables such as CPATH. void AddDefaultEnvVarPaths(const LangOptions &Lang); /// AddDefaultSystemIncludePaths - Adds the default system include paths so /// that e.g. stdio.h is found. void AddDefaultSystemIncludePaths(const LangOptions &Lang); /// Realize - Merges all search path lists into one list and send it to /// HeaderSearch. void Realize(); }; } // end namespace clang #endif <file_sep>/include/clang/Analysis/PathSensitive/GRTransferFuncs.h //== GRTransferFuncs.h - Path-Sens. Transfer Functions Interface -*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines GRTransferFuncs, which provides a base-class that // defines an interface for transfer functions used by GRExprEngine. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_GRTF #define LLVM_CLANG_ANALYSIS_GRTF #include "clang/Analysis/PathSensitive/SVals.h" #include "clang/Analysis/PathSensitive/GRCoreEngine.h" #include "clang/Analysis/PathSensitive/GRState.h" #include <vector> namespace clang { class GRExprEngine; class BugReporter; class ObjCMessageExpr; class GRStmtNodeBuilderRef; class GRTransferFuncs { friend class GRExprEngine; protected: virtual SVal DetermEvalBinOpNN(GRExprEngine& Eng, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, QualType T) { return UnknownVal(); } public: GRTransferFuncs() {} virtual ~GRTransferFuncs() {} virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {} virtual void RegisterChecks(BugReporter& BR) {} // Casts. virtual SVal EvalCast(GRExprEngine& Engine, NonLoc V, QualType CastT) =0; virtual SVal EvalCast(GRExprEngine& Engine, Loc V, QualType CastT) = 0; // Unary Operators. virtual SVal EvalMinus(GRExprEngine& Engine, UnaryOperator* U, NonLoc X) = 0; virtual SVal EvalComplement(GRExprEngine& Engine, NonLoc X) = 0; // Binary Operators. // FIXME: We're moving back towards using GREXprEngine directly. No need // for OStates virtual void EvalBinOpNN(GRStateSet& OStates, GRExprEngine& Eng, const GRState* St, Expr* Ex, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, QualType T); virtual SVal EvalBinOp(GRExprEngine& Engine, BinaryOperator::Opcode Op, Loc L, Loc R) = 0; // Pointer arithmetic. virtual SVal EvalBinOp(GRExprEngine& Engine, BinaryOperator::Opcode Op, Loc L, NonLoc R) = 0; // Calls. virtual void EvalCall(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, CallExpr* CE, SVal L, ExplodedNode<GRState>* Pred) {} virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, ObjCMessageExpr* ME, ExplodedNode<GRState>* Pred) {} // Stores. virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {} // End-of-path and dead symbol notification. virtual void EvalEndPath(GRExprEngine& Engine, GREndPathNodeBuilder<GRState>& Builder) {} virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, ExplodedNode<GRState>* Pred, Stmt* S, const GRState* state, SymbolReaper& SymReaper) {} // Return statements. virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, ReturnStmt* S, ExplodedNode<GRState>* Pred) {} // Assumptions. virtual const GRState* EvalAssume(GRStateManager& VMgr, const GRState* St, SVal Cond, bool Assumption, bool& isFeasible) { return St; } }; } // end clang namespace #endif <file_sep>/lib/AST/TemplateName.cpp //===--- TemplateName.h - C++ Template Name Representation-------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the TemplateName interface and subclasses. // //===----------------------------------------------------------------------===// #include "clang/AST/TemplateName.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/NestedNameSpecifier.h" #include "llvm/Support/raw_ostream.h" using namespace clang; TemplateDecl *TemplateName::getAsTemplateDecl() const { if (TemplateDecl *Template = Storage.dyn_cast<TemplateDecl *>()) return Template; if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName()) return QTN->getTemplateDecl(); return 0; } bool TemplateName::isDependent() const { if (TemplateDecl *Template = getAsTemplateDecl()) { // FIXME: We don't yet have a notion of dependent // declarations. When we do, check that. This hack won't last // long!. return isa<TemplateTemplateParmDecl>(Template); } return true; } void TemplateName::print(llvm::raw_ostream &OS, bool SuppressNNS) const { if (TemplateDecl *Template = Storage.dyn_cast<TemplateDecl *>()) OS << Template->getIdentifier()->getName(); else if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName()) { if (!SuppressNNS) QTN->getQualifier()->print(OS); if (QTN->hasTemplateKeyword()) OS << "template "; OS << QTN->getTemplateDecl()->getIdentifier()->getName(); } else if (DependentTemplateName *DTN = getAsDependentTemplateName()) { if (!SuppressNNS) DTN->getQualifier()->print(OS); OS << "template "; OS << DTN->getName()->getName(); } } void TemplateName::dump() const { print(llvm::errs()); } <file_sep>/test/CodeGen/trapv.c // RUN: clang-cc -ftrapv %s -emit-llvm -o %t && // RUN: grep "__overflow_handler" %t | count 2 unsigned int ui, uj, uk; int i, j, k; void foo() { ui = uj + uk; i = j + k; } <file_sep>/include/clang/Analysis/Analyses/UninitializedValues.h //===- UninitializedValues.h - unintialized values analysis ----*- C++ --*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides the interface for the Unintialized Values analysis, // a flow-sensitive analysis that detects when variable values are unintialized. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_UNITVALS_H #define LLVM_CLANG_UNITVALS_H #include "clang/Analysis/Support/BlkExprDeclBitVector.h" #include "clang/Analysis/FlowSensitive/DataflowValues.h" namespace clang { class BlockVarDecl; class Expr; class DeclRefExpr; class VarDecl; /// UninitializedValues_ValueTypes - Utility class to wrap type declarations /// for dataflow values and dataflow analysis state for the /// Unitialized Values analysis. class UninitializedValues_ValueTypes { public: struct ObserverTy; struct AnalysisDataTy : public StmtDeclBitVector_Types::AnalysisDataTy { AnalysisDataTy() : Observer(NULL), FullUninitTaint(true) {} virtual ~AnalysisDataTy() {}; ObserverTy* Observer; bool FullUninitTaint; }; typedef StmtDeclBitVector_Types::ValTy ValTy; //===--------------------------------------------------------------------===// // ObserverTy - Observer for querying DeclRefExprs that use an uninitalized // value. //===--------------------------------------------------------------------===// struct ObserverTy { virtual ~ObserverTy(); virtual void ObserveDeclRefExpr(ValTy& Val, AnalysisDataTy& AD, DeclRefExpr* DR, VarDecl* VD) = 0; }; }; /// UninitializedValues - Objects of this class encapsulate dataflow analysis /// information regarding what variable declarations in a function are /// potentially unintialized. class UninitializedValues : public DataflowValues<UninitializedValues_ValueTypes> { public: typedef UninitializedValues_ValueTypes::ObserverTy ObserverTy; UninitializedValues(CFG &cfg) { getAnalysisData().setCFG(cfg); } /// IntializeValues - Create initial dataflow values and meta data for /// a given CFG. This is intended to be called by the dataflow solver. void InitializeValues(const CFG& cfg); }; } // end namespace clang #endif <file_sep>/test/SemaCXX/overload-member-call.cpp // RUN: clang-cc -fsyntax-only -verify %s struct X { int& f(int) const; // expected-note 2 {{candidate function}} float& f(int); // expected-note 2 {{candidate function}} void test_f(int x) const { int& i = f(x); } void test_f2(int x) { float& f2 = f(x); } int& g(int) const; // expected-note 2 {{candidate function}} float& g(int); // expected-note 2 {{candidate function}} static double& g(double); // expected-note 2 {{candidate function}} void h(int); void test_member() { float& f1 = f(0); float& f2 = g(0); double& d1 = g(0.0); } void test_member_const() const { int &i1 = f(0); int &i2 = g(0); double& d1 = g(0.0); } static void test_member_static() { double& d1 = g(0.0); g(0); // expected-error{{call to 'g' is ambiguous; candidates are:}} } }; void test(X x, const X xc, X* xp, const X* xcp, volatile X xv, volatile X* xvp) { int& i1 = xc.f(0); int& i2 = xcp->f(0); float& f1 = x.f(0); float& f2 = xp->f(0); xv.f(0); // expected-error{{no matching member function for call to 'f'; candidates are:}} xvp->f(0); // expected-error{{no matching member function for call to 'f'; candidates are:}} int& i3 = xc.g(0); int& i4 = xcp->g(0); float& f3 = x.g(0); float& f4 = xp->g(0); double& d1 = xp->g(0.0); double& d2 = X::g(0.0); X::g(0); // expected-error{{call to 'g' is ambiguous; candidates are:}} X::h(0); // expected-error{{call to non-static member function without an object argument}} } <file_sep>/test/CodeGen/tentative-decls.c // RUN: clang-cc -emit-llvm -o %t %s && // RUN: grep '@r = common global \[1 x .*\] zeroinitializer' %t && int r[]; int (*a)[] = &r; struct s0; struct s0 x; // RUN: grep '@x = common global .struct.s0 zeroinitializer' %t && struct s0 y; // RUN: grep '@y = common global .struct.s0 zeroinitializer' %t && struct s0 *f0() { return &y; } struct s0 { int x; }; // RUN: grep '@b = common global \[1 x .*\] zeroinitializer' %t && int b[]; int *f1() { return b; } // RUN: true <file_sep>/test/CodeGen/2008-08-04-void-pointer-arithmetic.c // RUN: clang-cc --emit-llvm -o - %s // <rdar://problem/6122967> int f0(void *a, void *b) { return a - b; } <file_sep>/test/CodeGen/inline.c // RUN: echo "C89 tests:" && // RUN: clang %s -emit-llvm -S -o %t -std=c89 && // RUN: grep "define available_externally i32 @ei()" %t && // RUN: grep "define i32 @foo()" %t && // RUN: grep "define i32 @bar()" %t && // RUN: grep "define void @unreferenced1()" %t && // RUN: not grep unreferenced2 %t && // RUN: grep "define void @gnu_inline()" %t && // RUN: echo "\nC99 tests:" && // RUN: clang %s -emit-llvm -S -o %t -std=c99 && // RUN: grep "define i32 @ei()" %t && // RUN: grep "define available_externally i32 @foo()" %t && // RUN: grep "define i32 @bar()" %t && // RUN: not grep unreferenced1 %t && // RUN: grep "define void @unreferenced2()" %t && // RUN: grep "define void @gnu_inline()" %t && // RUN: echo "\nC++ tests:" && // RUN: clang %s -emit-llvm -S -o %t -std=c++98 && // RUN: grep "define linkonce_odr i32 @_Z2eiv()" %t && // RUN: grep "define linkonce_odr i32 @_Z3foov()" %t && // RUN: grep "define i32 @_Z3barv()" %t && // RUN: not grep unreferenced %t && // RUN: grep "define void @_Z10gnu_inlinev()" %t extern inline int ei() { return 123; } inline int foo() { return ei(); } int bar() { return foo(); } inline void unreferenced1() {} extern inline void unreferenced2() {} __inline __attribute((__gnuc_inline__)) void gnu_inline() {} <file_sep>/lib/Analysis/CFRefCount.cpp // CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the methods for CFRefCount, which implements // a reference count checker for Core Foundation (Mac OS X). // //===----------------------------------------------------------------------===// #include "GRSimpleVals.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceManager.h" #include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h" #include "clang/Analysis/PathSensitive/GRStateTrait.h" #include "clang/Analysis/PathDiagnostic.h" #include "clang/Analysis/LocalCheckers.h" #include "clang/Analysis/PathDiagnostic.h" #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Analysis/PathSensitive/SymbolManager.h" #include "clang/AST/DeclObjC.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/ImmutableList.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/STLExtras.h" #include <ostream> #include <stdarg.h> using namespace clang; //===----------------------------------------------------------------------===// // Utility functions. //===----------------------------------------------------------------------===// // The "fundamental rule" for naming conventions of methods: // (url broken into two lines) // http://developer.apple.com/documentation/Cocoa/Conceptual/ // MemoryMgmt/Tasks/MemoryManagementRules.html // // "You take ownership of an object if you create it using a method whose name // begins with “alloc” or “new” or contains “copy” (for example, alloc, // newObject, or mutableCopy), or if you send it a retain message. You are // responsible for relinquishing ownership of objects you own using release // or autorelease. Any other time you receive an object, you must // not release it." // using llvm::CStrInCStrNoCase; using llvm::StringsEqualNoCase; enum NamingConvention { NoConvention, CreateRule, InitRule }; static inline bool isWordEnd(char ch, char prev, char next) { return ch == '\0' || (islower(prev) && isupper(ch)) // xxxC || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate || !isalpha(ch); } static inline const char* parseWord(const char* s) { char ch = *s, prev = '\0'; assert(ch != '\0'); char next = *(s+1); while (!isWordEnd(ch, prev, next)) { prev = ch; ch = next; next = *((++s)+1); } return s; } static NamingConvention deriveNamingConvention(const char* s) { // A method/function name may contain a prefix. We don't know it is there, // however, until we encounter the first '_'. bool InPossiblePrefix = true; bool AtBeginning = true; NamingConvention C = NoConvention; while (*s != '\0') { // Skip '_'. if (*s == '_') { if (InPossiblePrefix) { InPossiblePrefix = false; AtBeginning = true; // Discard whatever 'convention' we // had already derived since it occurs // in the prefix. C = NoConvention; } ++s; continue; } // Skip numbers, ':', etc. if (!isalpha(*s)) { ++s; continue; } const char *wordEnd = parseWord(s); assert(wordEnd > s); unsigned len = wordEnd - s; switch (len) { default: break; case 3: // Methods starting with 'new' follow the create rule. if (AtBeginning && StringsEqualNoCase("new", s, len)) C = CreateRule; break; case 4: // Methods starting with 'alloc' or contain 'copy' follow the // create rule if (C == NoConvention && StringsEqualNoCase("copy", s, len)) C = CreateRule; else // Methods starting with 'init' follow the init rule. if (AtBeginning && StringsEqualNoCase("init", s, len)) C = InitRule; break; case 5: if (AtBeginning && StringsEqualNoCase("alloc", s, len)) C = CreateRule; break; } // If we aren't in the prefix and have a derived convention then just // return it now. if (!InPossiblePrefix && C != NoConvention) return C; AtBeginning = false; s = wordEnd; } // We will get here if there wasn't more than one word // after the prefix. return C; } static bool followsFundamentalRule(const char* s) { return deriveNamingConvention(s) == CreateRule; } static bool followsReturnRule(const char* s) { NamingConvention C = deriveNamingConvention(s); return C == CreateRule || C == InitRule; } //===----------------------------------------------------------------------===// // Selector creation functions. //===----------------------------------------------------------------------===// static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) { IdentifierInfo* II = &Ctx.Idents.get(name); return Ctx.Selectors.getSelector(0, &II); } static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) { IdentifierInfo* II = &Ctx.Idents.get(name); return Ctx.Selectors.getSelector(1, &II); } //===----------------------------------------------------------------------===// // Type querying functions. //===----------------------------------------------------------------------===// static bool hasPrefix(const char* s, const char* prefix) { if (!prefix) return true; char c = *s; char cP = *prefix; while (c != '\0' && cP != '\0') { if (c != cP) break; c = *(++s); cP = *(++prefix); } return cP == '\0'; } static bool hasSuffix(const char* s, const char* suffix) { const char* loc = strstr(s, suffix); return loc && strcmp(suffix, loc) == 0; } static bool isRefType(QualType RetTy, const char* prefix, ASTContext* Ctx = 0, const char* name = 0) { if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) { const char* TDName = TD->getDecl()->getIdentifier()->getName(); return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"); } if (!Ctx || !name) return false; // Is the type void*? const PointerType* PT = RetTy->getAsPointerType(); if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy)) return false; // Does the name start with the prefix? return hasPrefix(name, prefix); } //===----------------------------------------------------------------------===// // Primitives used for constructing summaries for function/method calls. //===----------------------------------------------------------------------===// namespace { /// ArgEffect is used to summarize a function/method call's effect on a /// particular argument. enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing, DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape, NewAutoreleasePool, SelfOwn, StopTracking }; /// ArgEffects summarizes the effects of a function/method call on all of /// its arguments. typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects; } namespace llvm { template <> struct FoldingSetTrait<ArgEffects> { static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) { for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) { ID.AddInteger(I->first); ID.AddInteger((unsigned) I->second); } } }; } // end llvm namespace namespace { /// RetEffect is used to summarize a function/method call's behavior with /// respect to its return value. class VISIBILITY_HIDDEN RetEffect { public: enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol, NotOwnedSymbol, ReceiverAlias }; enum ObjKind { CF, ObjC, AnyObj }; private: Kind K; ObjKind O; unsigned index; RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {} RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {} public: Kind getKind() const { return K; } ObjKind getObjKind() const { return O; } unsigned getIndex() const { assert(getKind() == Alias); return index; } static RetEffect MakeAlias(unsigned Idx) { return RetEffect(Alias, Idx); } static RetEffect MakeReceiverAlias() { return RetEffect(ReceiverAlias); } static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) { return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o); } static RetEffect MakeNotOwned(ObjKind o) { return RetEffect(NotOwnedSymbol, o); } static RetEffect MakeNoRet() { return RetEffect(NoRet); } void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned)K); ID.AddInteger((unsigned)O); ID.AddInteger(index); } }; class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode { /// Args - an ordered vector of (index, ArgEffect) pairs, where index /// specifies the argument (starting from 0). This can be sparsely /// populated; arguments with no entry in Args use 'DefaultArgEffect'. ArgEffects* Args; /// DefaultArgEffect - The default ArgEffect to apply to arguments that /// do not have an entry in Args. ArgEffect DefaultArgEffect; /// Receiver - If this summary applies to an Objective-C message expression, /// this is the effect applied to the state of the receiver. ArgEffect Receiver; /// Ret - The effect on the return value. Used to indicate if the /// function/method call returns a new tracked symbol, returns an /// alias of one of the arguments in the call, and so on. RetEffect Ret; /// EndPath - Indicates that execution of this method/function should /// terminate the simulation of a path. bool EndPath; public: RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff, ArgEffect ReceiverEff, bool endpath = false) : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R), EndPath(endpath) {} /// getArg - Return the argument effect on the argument specified by /// idx (starting from 0). ArgEffect getArg(unsigned idx) const { if (!Args) return DefaultArgEffect; // If Args is present, it is likely to contain only 1 element. // Just do a linear search. Do it from the back because functions with // large numbers of arguments will be tail heavy with respect to which // argument they actually modify with respect to the reference count. for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend(); I!=E; ++I) { if (idx > I->first) return DefaultArgEffect; if (idx == I->first) return I->second; } return DefaultArgEffect; } /// getRetEffect - Returns the effect on the return value of the call. RetEffect getRetEffect() const { return Ret; } /// isEndPath - Returns true if executing the given method/function should /// terminate the path. bool isEndPath() const { return EndPath; } /// getReceiverEffect - Returns the effect on the receiver of the call. /// This is only meaningful if the summary applies to an ObjCMessageExpr*. ArgEffect getReceiverEffect() const { return Receiver; } typedef ArgEffects::const_iterator ExprIterator; ExprIterator begin_args() const { return Args->begin(); } ExprIterator end_args() const { return Args->end(); } static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A, RetEffect RetEff, ArgEffect DefaultEff, ArgEffect ReceiverEff, bool EndPath) { ID.AddPointer(A); ID.Add(RetEff); ID.AddInteger((unsigned) DefaultEff); ID.AddInteger((unsigned) ReceiverEff); ID.AddInteger((unsigned) EndPath); } void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Data structures for constructing summaries. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN ObjCSummaryKey { IdentifierInfo* II; Selector S; public: ObjCSummaryKey(IdentifierInfo* ii, Selector s) : II(ii), S(s) {} ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s) : II(d ? d->getIdentifier() : 0), S(s) {} ObjCSummaryKey(Selector s) : II(0), S(s) {} IdentifierInfo* getIdentifier() const { return II; } Selector getSelector() const { return S; } }; } namespace llvm { template <> struct DenseMapInfo<ObjCSummaryKey> { static inline ObjCSummaryKey getEmptyKey() { return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(), DenseMapInfo<Selector>::getEmptyKey()); } static inline ObjCSummaryKey getTombstoneKey() { return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(), DenseMapInfo<Selector>::getTombstoneKey()); } static unsigned getHashValue(const ObjCSummaryKey &V) { return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier()) & 0x88888888) | (DenseMapInfo<Selector>::getHashValue(V.getSelector()) & 0x55555555); } static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) { return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(), RHS.getIdentifier()) && DenseMapInfo<Selector>::isEqual(LHS.getSelector(), RHS.getSelector()); } static bool isPod() { return DenseMapInfo<ObjCInterfaceDecl*>::isPod() && DenseMapInfo<Selector>::isPod(); } }; } // end llvm namespace namespace { class VISIBILITY_HIDDEN ObjCSummaryCache { typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy; MapTy M; public: ObjCSummaryCache() {} typedef MapTy::iterator iterator; iterator find(ObjCInterfaceDecl* D, Selector S) { // Do a lookup with the (D,S) pair. If we find a match return // the iterator. ObjCSummaryKey K(D, S); MapTy::iterator I = M.find(K); if (I != M.end() || !D) return I; // Walk the super chain. If we find a hit with a parent, we'll end // up returning that summary. We actually allow that key (null,S), as // we cache summaries for the null ObjCInterfaceDecl* to allow us to // generate initial summaries without having to worry about NSObject // being declared. // FIXME: We may change this at some point. for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) { if ((I = M.find(ObjCSummaryKey(C, S))) != M.end()) break; if (!C) return I; } // Cache the summary with original key to make the next lookup faster // and return the iterator. M[K] = I->second; return I; } iterator find(Expr* Receiver, Selector S) { return find(getReceiverDecl(Receiver), S); } iterator find(IdentifierInfo* II, Selector S) { // FIXME: Class method lookup. Right now we dont' have a good way // of going between IdentifierInfo* and the class hierarchy. iterator I = M.find(ObjCSummaryKey(II, S)); return I == M.end() ? M.find(ObjCSummaryKey(S)) : I; } ObjCInterfaceDecl* getReceiverDecl(Expr* E) { const PointerType* PT = E->getType()->getAsPointerType(); if (!PT) return 0; ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType()); if (!OI) return 0; return OI ? OI->getDecl() : 0; } iterator end() { return M.end(); } RetainSummary*& operator[](ObjCMessageExpr* ME) { Selector S = ME->getSelector(); if (Expr* Receiver = ME->getReceiver()) { ObjCInterfaceDecl* OD = getReceiverDecl(Receiver); return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S]; } return M[ObjCSummaryKey(ME->getClassName(), S)]; } RetainSummary*& operator[](ObjCSummaryKey K) { return M[K]; } RetainSummary*& operator[](Selector S) { return M[ ObjCSummaryKey(S) ]; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Data structures for managing collections of summaries. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN RetainSummaryManager { //==-----------------------------------------------------------------==// // Typedefs. //==-----------------------------------------------------------------==// typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> > ArgEffectsSetTy; typedef llvm::FoldingSet<RetainSummary> SummarySetTy; typedef llvm::DenseMap<FunctionDecl*, RetainSummary*> FuncSummariesTy; typedef ObjCSummaryCache ObjCMethodSummariesTy; //==-----------------------------------------------------------------==// // Data. //==-----------------------------------------------------------------==// /// Ctx - The ASTContext object for the analyzed ASTs. ASTContext& Ctx; /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier /// "CFDictionaryCreate". IdentifierInfo* CFDictionaryCreateII; /// GCEnabled - Records whether or not the analyzed code runs in GC mode. const bool GCEnabled; /// SummarySet - A FoldingSet of uniqued summaries. SummarySetTy SummarySet; /// FuncSummaries - A map from FunctionDecls to summaries. FuncSummariesTy FuncSummaries; /// ObjCClassMethodSummaries - A map from selectors (for instance methods) /// to summaries. ObjCMethodSummariesTy ObjCClassMethodSummaries; /// ObjCMethodSummaries - A map from selectors to summaries. ObjCMethodSummariesTy ObjCMethodSummaries; /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects. ArgEffectsSetTy ArgEffectsSet; /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects, /// and all other data used by the checker. llvm::BumpPtrAllocator BPAlloc; /// ScratchArgs - A holding buffer for construct ArgEffects. ArgEffects ScratchArgs; RetainSummary* StopSummary; //==-----------------------------------------------------------------==// // Methods. //==-----------------------------------------------------------------==// /// getArgEffects - Returns a persistent ArgEffects object based on the /// data in ScratchArgs. ArgEffects* getArgEffects(); enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable }; public: RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func); RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD); RetainSummary* getCFSummaryGetRule(FunctionDecl* FD); RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName); RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff, ArgEffect ReceiverEff = DoNothing, ArgEffect DefaultEff = MayEscape, bool isEndPath = false); RetainSummary* getPersistentSummary(RetEffect RE, ArgEffect ReceiverEff = DoNothing, ArgEffect DefaultEff = MayEscape) { return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff); } RetainSummary* getPersistentStopSummary() { if (StopSummary) return StopSummary; StopSummary = getPersistentSummary(RetEffect::MakeNoRet(), StopTracking, StopTracking); return StopSummary; } RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME); void InitializeClassMethodSummaries(); void InitializeMethodSummaries(); bool isTrackedObjectType(QualType T); private: void addClsMethSummary(IdentifierInfo* ClsII, Selector S, RetainSummary* Summ) { ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) { ObjCClassMethodSummaries[S] = Summ; } void addNSObjectMethSummary(Selector S, RetainSummary *Summ) { ObjCMethodSummaries[S] = Summ; } void addClassMethSummary(const char* Cls, const char* nullaryName, RetainSummary *Summ) { IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); Selector S = GetNullarySelector(nullaryName, Ctx); ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } void addInstMethSummary(const char* Cls, const char* nullaryName, RetainSummary *Summ) { IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); Selector S = GetNullarySelector(nullaryName, Ctx); ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) { IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); llvm::SmallVector<IdentifierInfo*, 10> II; while (const char* s = va_arg(argp, const char*)) II.push_back(&Ctx.Idents.get(s)); Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]); ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) { va_list argp; va_start(argp, Summ); addInstMethSummary(Cls, Summ, argp); va_end(argp); } void addPanicSummary(const char* Cls, ...) { RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(), DoNothing, DoNothing, true); va_list argp; va_start (argp, Cls); addInstMethSummary(Cls, Summ, argp); va_end(argp); } public: RetainSummaryManager(ASTContext& ctx, bool gcenabled) : Ctx(ctx), CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")), GCEnabled(gcenabled), StopSummary(0) { InitializeClassMethodSummaries(); InitializeMethodSummaries(); } ~RetainSummaryManager(); RetainSummary* getSummary(FunctionDecl* FD); RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID); RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S); bool isGCEnabled() const { return GCEnabled; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Implementation of checker data structures. //===----------------------------------------------------------------------===// RetainSummaryManager::~RetainSummaryManager() { // FIXME: The ArgEffects could eventually be allocated from BPAlloc, // mitigating the need to do explicit cleanup of the // Argument-Effect summaries. for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(), E = ArgEffectsSet.end(); I!=E; ++I) I->getValue().~ArgEffects(); } ArgEffects* RetainSummaryManager::getArgEffects() { if (ScratchArgs.empty()) return NULL; // Compute a profile for a non-empty ScratchArgs. llvm::FoldingSetNodeID profile; profile.Add(ScratchArgs); void* InsertPos; // Look up the uniqued copy, or create a new one. llvm::FoldingSetNodeWrapper<ArgEffects>* E = ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos); if (E) { ScratchArgs.clear(); return &E->getValue(); } E = (llvm::FoldingSetNodeWrapper<ArgEffects>*) BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >(); new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs); ArgEffectsSet.InsertNode(E, InsertPos); ScratchArgs.clear(); return &E->getValue(); } RetainSummary* RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff, ArgEffect ReceiverEff, ArgEffect DefaultEff, bool isEndPath) { // Generate a profile for the summary. llvm::FoldingSetNodeID profile; RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff, isEndPath); // Look up the uniqued summary, or create one if it doesn't exist. void* InsertPos; RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos); if (Summ) return Summ; // Create the summary and return it. Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>(); new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath); SummarySet.InsertNode(Summ, InsertPos); return Summ; } //===----------------------------------------------------------------------===// // Predicates. //===----------------------------------------------------------------------===// bool RetainSummaryManager::isTrackedObjectType(QualType T) { if (!Ctx.isObjCObjectPointerType(T)) return false; // Does it subclass NSObject? ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr()); // We assume that id<..>, id, and "Class" all represent tracked objects. if (!OT) return true; // Does the object type subclass NSObject? // FIXME: We can memoize here if this gets too expensive. IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject"); ObjCInterfaceDecl* ID = OT->getDecl(); for ( ; ID ; ID = ID->getSuperClass()) if (ID->getIdentifier() == NSObjectII) return true; return false; } //===----------------------------------------------------------------------===// // Summary creation for functions (largely uses of Core Foundation). //===----------------------------------------------------------------------===// static bool isRetain(FunctionDecl* FD, const char* FName) { const char* loc = strstr(FName, "Retain"); return loc && loc[sizeof("Retain")-1] == '\0'; } static bool isRelease(FunctionDecl* FD, const char* FName) { const char* loc = strstr(FName, "Release"); return loc && loc[sizeof("Release")-1] == '\0'; } RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) { SourceLocation Loc = FD->getLocation(); if (!Loc.isFileID()) return NULL; // Look up a summary in our cache of FunctionDecls -> Summaries. FuncSummariesTy::iterator I = FuncSummaries.find(FD); if (I != FuncSummaries.end()) return I->second; // No summary. Generate one. RetainSummary *S = 0; do { // We generate "stop" summaries for implicitly defined functions. if (FD->isImplicit()) { S = getPersistentStopSummary(); break; } // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the // function's type. const FunctionType* FT = FD->getType()->getAsFunctionType(); const char* FName = FD->getIdentifier()->getName(); // Strip away preceding '_'. Doing this here will effect all the checks // down below. while (*FName == '_') ++FName; // Inspect the result type. QualType RetTy = FT->getResultType(); // FIXME: This should all be refactored into a chain of "summary lookup" // filters. if (strcmp(FName, "IOServiceGetMatchingServices") == 0) { // FIXES: <rdar://problem/6326900> // This should be addressed using a API table. This strcmp is also // a little gross, but there is no need to super optimize here. assert (ScratchArgs.empty()); ScratchArgs.push_back(std::make_pair(1, DecRef)); S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); break; } // Enable this code once the semantics of NSDeallocateObject are resolved // for GC. <rdar://problem/6619988> #if 0 // Handle: NSDeallocateObject(id anObject); // This method does allow 'nil' (although we don't check it now). if (strcmp(FName, "NSDeallocateObject") == 0) { return RetTy == Ctx.VoidTy ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc) : getPersistentStopSummary(); } #endif // Handle: id NSMakeCollectable(CFTypeRef) if (strcmp(FName, "NSMakeCollectable") == 0) { S = (RetTy == Ctx.getObjCIdType()) ? getUnarySummary(FT, cfmakecollectable) : getPersistentStopSummary(); break; } if (RetTy->isPointerType()) { // For CoreFoundation ('CF') types. if (isRefType(RetTy, "CF", &Ctx, FName)) { if (isRetain(FD, FName)) S = getUnarySummary(FT, cfretain); else if (strstr(FName, "MakeCollectable")) S = getUnarySummary(FT, cfmakecollectable); else S = getCFCreateGetRuleSummary(FD, FName); break; } // For CoreGraphics ('CG') types. if (isRefType(RetTy, "CG", &Ctx, FName)) { if (isRetain(FD, FName)) S = getUnarySummary(FT, cfretain); else S = getCFCreateGetRuleSummary(FD, FName); break; } // For the Disk Arbitration API (DiskArbitration/DADisk.h) if (isRefType(RetTy, "DADisk") || isRefType(RetTy, "DADissenter") || isRefType(RetTy, "DASessionRef")) { S = getCFCreateGetRuleSummary(FD, FName); break; } break; } // Check for release functions, the only kind of functions that we care // about that don't return a pointer type. if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) { // Test for 'CGCF'. if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F') FName += 4; else FName += 2; if (isRelease(FD, FName)) S = getUnarySummary(FT, cfrelease); else { assert (ScratchArgs.empty()); // Remaining CoreFoundation and CoreGraphics functions. // We use to assume that they all strictly followed the ownership idiom // and that ownership cannot be transferred. While this is technically // correct, many methods allow a tracked object to escape. For example: // // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...); // CFDictionaryAddValue(y, key, x); // CFRelease(x); // ... it is okay to use 'x' since 'y' has a reference to it // // We handle this and similar cases with the follow heuristic. If the // function name contains "InsertValue", "SetValue" or "AddValue" then // we assume that arguments may "escape." // ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") || CStrInCStrNoCase(FName, "AddValue") || CStrInCStrNoCase(FName, "SetValue") || CStrInCStrNoCase(FName, "AppendValue")) ? MayEscape : DoNothing; S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E); } } } while (0); FuncSummaries[FD] = S; return S; } RetainSummary* RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName) { if (strstr(FName, "Create") || strstr(FName, "Copy")) return getCFSummaryCreateRule(FD); if (strstr(FName, "Get")) return getCFSummaryGetRule(FD); return 0; } RetainSummary* RetainSummaryManager::getUnarySummary(const FunctionType* FT, UnaryFuncKind func) { // Sanity check that this is *really* a unary function. This can // happen if people do weird things. const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT); if (!FTP || FTP->getNumArgs() != 1) return getPersistentStopSummary(); assert (ScratchArgs.empty()); switch (func) { case cfretain: { ScratchArgs.push_back(std::make_pair(0, IncRef)); return getPersistentSummary(RetEffect::MakeAlias(0), DoNothing, DoNothing); } case cfrelease: { ScratchArgs.push_back(std::make_pair(0, DecRef)); return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing); } case cfmakecollectable: { ScratchArgs.push_back(std::make_pair(0, MakeCollectable)); return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing); } default: assert (false && "Not a supported unary function."); return 0; } } RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) { assert (ScratchArgs.empty()); if (FD->getIdentifier() == CFDictionaryCreateII) { ScratchArgs.push_back(std::make_pair(1, DoNothingByRef)); ScratchArgs.push_back(std::make_pair(2, DoNothingByRef)); } return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true)); } RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) { assert (ScratchArgs.empty()); return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF), DoNothing, DoNothing); } //===----------------------------------------------------------------------===// // Summary creation for Selectors. //===----------------------------------------------------------------------===// RetainSummary* RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) { assert(ScratchArgs.empty()); // 'init' methods only return an alias if the return type is a location type. QualType T = ME->getType(); RetainSummary* Summ = getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias() : RetEffect::MakeNoRet()); ObjCMethodSummaries[ME] = Summ; return Summ; } RetainSummary* RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID) { Selector S = ME->getSelector(); // Look up a summary in our summary cache. ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S); if (I != ObjCMethodSummaries.end()) return I->second; // "initXXX": pass-through for receiver. const char* s = S.getIdentifierInfoForSlot(0)->getName(); assert (ScratchArgs.empty()); if (deriveNamingConvention(s) == InitRule) return getInitMethodSummary(ME); // Look for methods that return an owned object. if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType()))) return 0; if (followsFundamentalRule(s)) { RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet() : RetEffect::MakeOwned(RetEffect::ObjC, true); RetainSummary* Summ = getPersistentSummary(E); ObjCMethodSummaries[ME] = Summ; return Summ; } return 0; } RetainSummary* RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName, Selector S) { // FIXME: Eventually we should properly do class method summaries, but // it requires us being able to walk the type hierarchy. Unfortunately, // we cannot do this with just an IdentifierInfo* for the class name. // Look up a summary in our cache of Selectors -> Summaries. ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S); if (I != ObjCClassMethodSummaries.end()) return I->second; return 0; } void RetainSummaryManager::InitializeClassMethodSummaries() { assert (ScratchArgs.empty()); RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet() : RetEffect::MakeOwned(RetEffect::ObjC, true); RetainSummary* Summ = getPersistentSummary(E); // Create the summaries for "alloc", "new", and "allocWithZone:" for // NSObject and its derivatives. addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ); addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ); addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ); // Create the [NSAssertionHandler currentHander] summary. addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"), GetNullarySelector("currentHandler", Ctx), getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC))); // Create the [NSAutoreleasePool addObject:] summary. ScratchArgs.push_back(std::make_pair(0, Autorelease)); addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"), GetUnarySelector("addObject", Ctx), getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Autorelease)); } void RetainSummaryManager::InitializeMethodSummaries() { assert (ScratchArgs.empty()); // Create the "init" selector. It just acts as a pass-through for the // receiver. RetainSummary* InitSumm = getPersistentSummary(RetEffect::MakeReceiverAlias()); addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm); // The next methods are allocators. RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet() : RetEffect::MakeOwned(RetEffect::ObjC, true); RetainSummary* Summ = getPersistentSummary(E); // Create the "copy" selector. addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ); // Create the "mutableCopy" selector. addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ); // Create the "retain" selector. E = RetEffect::MakeReceiverAlias(); Summ = getPersistentSummary(E, IncRefMsg); addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ); // Create the "release" selector. Summ = getPersistentSummary(E, DecRefMsg); addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ); // Create the "drain" selector. Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef); addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ); // Create the -dealloc summary. Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc); addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ); // Create the "autorelease" selector. Summ = getPersistentSummary(E, Autorelease); addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ); // Specially handle NSAutoreleasePool. addInstMethSummary("NSAutoreleasePool", "init", getPersistentSummary(RetEffect::MakeReceiverAlias(), NewAutoreleasePool)); // For NSWindow, allocated objects are (initially) self-owned. // FIXME: For now we opt for false negatives with NSWindow, as these objects // self-own themselves. However, they only do this once they are displayed. // Thus, we need to track an NSWindow's display status. // This is tracked in <rdar://problem/6062711>. // See also http://llvm.org/bugs/show_bug.cgi?id=3714. RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet()); addClassMethSummary("NSWindow", "alloc", NoTrackYet); #if 0 RetainSummary *NSWindowSumm = getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking); addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect", "styleMask", "backing", "defer", NULL); addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect", "styleMask", "backing", "defer", "screen", NULL); #endif // For NSPanel (which subclasses NSWindow), allocated objects are not // self-owned. // FIXME: For now we don't track NSPanels. object for the same reason // as for NSWindow objects. addClassMethSummary("NSPanel", "alloc", NoTrackYet); addInstMethSummary("NSPanel", InitSumm, "initWithContentRect", "styleMask", "backing", "defer", NULL); addInstMethSummary("NSPanel", InitSumm, "initWithContentRect", "styleMask", "backing", "defer", "screen", NULL); // Create NSAssertionHandler summaries. addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file", "lineNumber", "description", NULL); addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object", "file", "lineNumber", "description", NULL); } //===----------------------------------------------------------------------===// // Reference-counting logic (typestate + counts). //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN RefVal { public: enum Kind { Owned = 0, // Owning reference. NotOwned, // Reference is not owned by still valid (not freed). Released, // Object has been released. ReturnedOwned, // Returned object passes ownership to caller. ReturnedNotOwned, // Return object does not pass ownership to caller. ERROR_START, ErrorDeallocNotOwned, // -dealloc called on non-owned object. ErrorDeallocGC, // Calling -dealloc with GC enabled. ErrorUseAfterRelease, // Object used after released. ErrorReleaseNotOwned, // Release of an object that was not owned. ERROR_LEAK_START, ErrorLeak, // A memory leak due to excessive reference counts. ErrorLeakReturned // A memory leak due to the returning method not having // the correct naming conventions. }; private: Kind kind; RetEffect::ObjKind okind; unsigned Cnt; QualType T; RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t) : kind(k), okind(o), Cnt(cnt), T(t) {} RefVal(Kind k, unsigned cnt = 0) : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {} public: Kind getKind() const { return kind; } RetEffect::ObjKind getObjKind() const { return okind; } unsigned getCount() const { return Cnt; } void clearCounts() { Cnt = 0; } QualType getType() const { return T; } // Useful predicates. static bool isError(Kind k) { return k >= ERROR_START; } static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; } bool isOwned() const { return getKind() == Owned; } bool isNotOwned() const { return getKind() == NotOwned; } bool isReturnedOwned() const { return getKind() == ReturnedOwned; } bool isReturnedNotOwned() const { return getKind() == ReturnedNotOwned; } bool isNonLeakError() const { Kind k = getKind(); return isError(k) && !isLeak(k); } static RefVal makeOwned(RetEffect::ObjKind o, QualType t, unsigned Count = 1) { return RefVal(Owned, o, Count, t); } static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t, unsigned Count = 0) { return RefVal(NotOwned, o, Count, t); } static RefVal makeReturnedOwned(unsigned Count) { return RefVal(ReturnedOwned, Count); } static RefVal makeReturnedNotOwned() { return RefVal(ReturnedNotOwned); } // Comparison, profiling, and pretty-printing. bool operator==(const RefVal& X) const { return kind == X.kind && Cnt == X.Cnt && T == X.T; } RefVal operator-(size_t i) const { return RefVal(getKind(), getObjKind(), getCount() - i, getType()); } RefVal operator+(size_t i) const { return RefVal(getKind(), getObjKind(), getCount() + i, getType()); } RefVal operator^(Kind k) const { return RefVal(k, getObjKind(), getCount(), getType()); } void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned) kind); ID.AddInteger(Cnt); ID.Add(T); } void print(std::ostream& Out) const; }; void RefVal::print(std::ostream& Out) const { if (!T.isNull()) Out << "Tracked Type:" << T.getAsString() << '\n'; switch (getKind()) { default: assert(false); case Owned: { Out << "Owned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } case NotOwned: { Out << "NotOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } case ReturnedOwned: { Out << "ReturnedOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } case ReturnedNotOwned: { Out << "ReturnedNotOwned"; unsigned cnt = getCount(); if (cnt) Out << " (+ " << cnt << ")"; break; } case Released: Out << "Released"; break; case ErrorDeallocGC: Out << "-dealloc (GC)"; break; case ErrorDeallocNotOwned: Out << "-dealloc (not-owned)"; break; case ErrorLeak: Out << "Leaked"; break; case ErrorLeakReturned: Out << "Leaked (Bad naming)"; break; case ErrorUseAfterRelease: Out << "Use-After-Release [ERROR]"; break; case ErrorReleaseNotOwned: Out << "Release of Not-Owned [ERROR]"; break; } } } // end anonymous namespace //===----------------------------------------------------------------------===// // RefBindings - State used to track object reference counts. //===----------------------------------------------------------------------===// typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings; static int RefBIndex = 0; static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0); namespace clang { template<> struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> { static inline void* GDMIndex() { return &RefBIndex; } }; } //===----------------------------------------------------------------------===// // AutoreleaseBindings - State used to track objects in autorelease pools. //===----------------------------------------------------------------------===// typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts; typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents; typedef llvm::ImmutableList<SymbolRef> ARStack; static int AutoRCIndex = 0; static int AutoRBIndex = 0; namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; } namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; } namespace clang { template<> struct GRStateTrait<AutoreleaseStack> : public GRStatePartialTrait<ARStack> { static inline void* GDMIndex() { return &AutoRBIndex; } }; template<> struct GRStateTrait<AutoreleasePoolContents> : public GRStatePartialTrait<ARPoolContents> { static inline void* GDMIndex() { return &AutoRCIndex; } }; } // end clang namespace static SymbolRef GetCurrentAutoreleasePool(const GRState* state) { ARStack stack = state->get<AutoreleaseStack>(); return stack.isEmpty() ? SymbolRef() : stack.getHead(); } static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F, SymbolRef sym) { SymbolRef pool = GetCurrentAutoreleasePool(state); const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool); ARCounts newCnts(0); if (cnts) { const unsigned *cnt = (*cnts).lookup(sym); newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1); } else newCnts = F.Add(F.GetEmptyMap(), sym, 1); return state.set<AutoreleasePoolContents>(pool, newCnts); } //===----------------------------------------------------------------------===// // Transfer functions. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals { public: class BindingsPrinter : public GRState::Printer { public: virtual void Print(std::ostream& Out, const GRState* state, const char* nl, const char* sep); }; private: typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*> SummaryLogTy; RetainSummaryManager Summaries; SummaryLogTy SummaryLog; const LangOptions& LOpts; ARCounts::Factory ARCountFactory; BugType *useAfterRelease, *releaseNotOwned; BugType *deallocGC, *deallocNotOwned; BugType *leakWithinFunction, *leakAtReturn; BugReporter *BR; GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E, RefVal::Kind& hasErr); void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst, GRStmtNodeBuilder<GRState>& Builder, Expr* NodeExpr, Expr* ErrorExpr, ExplodedNode<GRState>* Pred, const GRState* St, RefVal::Kind hasErr, SymbolRef Sym); std::pair<GRStateRef, bool> HandleSymbolDeath(GRStateManager& VMgr, const GRState* St, const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak); public: CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts) : Summaries(Ctx, gcenabled), LOpts(lopts), useAfterRelease(0), releaseNotOwned(0), deallocGC(0), deallocNotOwned(0), leakWithinFunction(0), leakAtReturn(0), BR(0) {} virtual ~CFRefCount() {} void RegisterChecks(BugReporter &BR); virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) { Printers.push_back(new BindingsPrinter()); } bool isGCEnabled() const { return Summaries.isGCEnabled(); } const LangOptions& getLangOptions() const { return LOpts; } const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const { SummaryLogTy::const_iterator I = SummaryLog.find(N); return I == SummaryLog.end() ? 0 : I->second; } // Calls. void EvalSummary(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, Expr* Ex, Expr* Receiver, RetainSummary* Summ, ExprIterator arg_beg, ExprIterator arg_end, ExplodedNode<GRState>* Pred); virtual void EvalCall(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, CallExpr* CE, SVal L, ExplodedNode<GRState>* Pred); virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, ObjCMessageExpr* ME, ExplodedNode<GRState>* Pred); bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, ObjCMessageExpr* ME, ExplodedNode<GRState>* Pred); // Stores. virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val); // End-of-path. virtual void EvalEndPath(GRExprEngine& Engine, GREndPathNodeBuilder<GRState>& Builder); virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, ExplodedNode<GRState>* Pred, Stmt* S, const GRState* state, SymbolReaper& SymReaper); // Return statements. virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, ReturnStmt* S, ExplodedNode<GRState>* Pred); // Assumptions. virtual const GRState* EvalAssume(GRStateManager& VMgr, const GRState* St, SVal Cond, bool Assumption, bool& isFeasible); }; } // end anonymous namespace static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) { Out << ' '; if (Sym) Out << Sym->getSymbolID(); else Out << "<pool>"; Out << ":{"; // Get the contents of the pool. if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym)) for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J) Out << '(' << J.getKey() << ',' << J.getData() << ')'; Out << '}'; } void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state, const char* nl, const char* sep) { RefBindings B = state->get<RefBindings>(); if (!B.isEmpty()) Out << sep << nl; for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) { Out << (*I).first << " : "; (*I).second.print(Out); Out << nl; } // Print the autorelease stack. Out << sep << nl << "AR pool stack:"; ARStack stack = state->get<AutoreleaseStack>(); PrintPool(Out, SymbolRef(), state); // Print the caller's pool. for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I) PrintPool(Out, *I, state); Out << nl; } static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) { return Summ ? Summ->getArg(idx) : MayEscape; } static inline RetEffect GetRetEffect(RetainSummary* Summ) { return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet(); } static inline ArgEffect GetReceiverE(RetainSummary* Summ) { return Summ ? Summ->getReceiverEffect() : DoNothing; } static inline bool IsEndPath(RetainSummary* Summ) { return Summ ? Summ->isEndPath() : false; } /// GetReturnType - Used to get the return type of a message expression or /// function call with the intention of affixing that type to a tracked symbol. /// While the the return type can be queried directly from RetEx, when /// invoking class methods we augment to the return type to be that of /// a pointer to the class (as opposed it just being id). static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) { QualType RetTy = RetE->getType(); // FIXME: We aren't handling id<...>. const PointerType* PT = RetTy->getAsPointerType(); if (!PT) return RetTy; // If RetEx is not a message expression just return its type. // If RetEx is a message expression, return its types if it is something /// more specific than id. ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE); if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType())) return RetTy; ObjCInterfaceDecl* D = ME->getClassInfo().first; // At this point we know the return type of the message expression is id. // If we have an ObjCInterceDecl, we know this is a call to a class method // whose type we can resolve. In such cases, promote the return type to // Class*. return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D)); } void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, Expr* Ex, Expr* Receiver, RetainSummary* Summ, ExprIterator arg_beg, ExprIterator arg_end, ExplodedNode<GRState>* Pred) { // Get the state. GRStateRef state(Builder.GetState(Pred), Eng.getStateManager()); ASTContext& Ctx = Eng.getStateManager().getContext(); // Evaluate the effect of the arguments. RefVal::Kind hasErr = (RefVal::Kind) 0; unsigned idx = 0; Expr* ErrorExpr = NULL; SymbolRef ErrorSym = 0; for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) { SVal V = state.GetSValAsScalarOrLoc(*I); SymbolRef Sym = V.getAsLocSymbol(); if (Sym) if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) { state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr); if (hasErr) { ErrorExpr = *I; ErrorSym = Sym; break; } continue; } if (isa<Loc>(V)) { if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) { if (GetArgE(Summ, idx) == DoNothingByRef) continue; // Invalidate the value of the variable passed by reference. // FIXME: Either this logic should also be replicated in GRSimpleVals // or should be pulled into a separate "constraint engine." // FIXME: We can have collisions on the conjured symbol if the // expression *I also creates conjured symbols. We probably want // to identify conjured symbols by an expression pair: the enclosing // expression (the context) and the expression itself. This should // disambiguate conjured symbols. const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion()); // Blast through TypedViewRegions to get the original region type. while (R) { const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R); if (!ATR) break; R = dyn_cast<TypedRegion>(ATR->getSuperRegion()); } if (R) { // Is the invalidated variable something that we were tracking? SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol(); // Remove any existing reference-count binding. if (Sym) state = state.remove<RefBindings>(Sym); if (R->isBoundable(Ctx)) { // Set the value of the variable to be a conjured symbol. unsigned Count = Builder.getCurrentBlockCount(); QualType T = R->getRValueType(Ctx); if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){ ValueManager &ValMgr = Eng.getValueManager(); SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count); state = state.BindLoc(Loc::MakeVal(R), V); } else if (const RecordType *RT = T->getAsStructureType()) { // Handle structs in a not so awesome way. Here we just // eagerly bind new symbols to the fields. In reality we // should have the store manager handle this. The idea is just // to prototype some basic functionality here. All of this logic // should one day soon just go away. const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx); // No record definition. There is nothing we can do. if (!RD) continue; MemRegionManager &MRMgr = state.getManager().getRegionManager(); // Iterate through the fields and construct new symbols. for (RecordDecl::field_iterator FI=RD->field_begin(Ctx), FE=RD->field_end(Ctx); FI!=FE; ++FI) { // For now just handle scalar fields. FieldDecl *FD = *FI; QualType FT = FD->getType(); if (Loc::IsLocType(FT) || (FT->isIntegerType() && FT->isScalarType())) { const FieldRegion* FR = MRMgr.getFieldRegion(FD, R); ValueManager &ValMgr = Eng.getValueManager(); SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count); state = state.BindLoc(Loc::MakeVal(FR), V); } } } else { // Just blast away other values. state = state.BindLoc(*MR, UnknownVal()); } } } else state = state.BindLoc(*MR, UnknownVal()); } else { // Nuke all other arguments passed by reference. state = state.Unbind(cast<Loc>(V)); } } else if (isa<nonloc::LocAsInteger>(V)) state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc()); } // Evaluate the effect on the message receiver. if (!ErrorExpr && Receiver) { SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol(); if (Sym) { if (const RefVal* T = state.get<RefBindings>(Sym)) { state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr); if (hasErr) { ErrorExpr = Receiver; ErrorSym = Sym; } } } } // Process any errors. if (hasErr) { ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state, hasErr, ErrorSym); return; } // Consult the summary for the return value. RetEffect RE = GetRetEffect(Summ); switch (RE.getKind()) { default: assert (false && "Unhandled RetEffect."); break; case RetEffect::NoRet: { // Make up a symbol for the return value (not reference counted). // FIXME: This is basically copy-and-paste from GRSimpleVals. We // should compose behavior, not copy it. // FIXME: We eventually should handle structs and other compound types // that are returned by value. QualType T = Ex->getType(); if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) { unsigned Count = Builder.getCurrentBlockCount(); ValueManager &ValMgr = Eng.getValueManager(); SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count); state = state.BindExpr(Ex, X, false); } break; } case RetEffect::Alias: { unsigned idx = RE.getIndex(); assert (arg_end >= arg_beg); assert (idx < (unsigned) (arg_end - arg_beg)); SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx)); state = state.BindExpr(Ex, V, false); break; } case RetEffect::ReceiverAlias: { assert (Receiver); SVal V = state.GetSValAsScalarOrLoc(Receiver); state = state.BindExpr(Ex, V, false); break; } case RetEffect::OwnedAllocatedSymbol: case RetEffect::OwnedSymbol: { unsigned Count = Builder.getCurrentBlockCount(); ValueManager &ValMgr = Eng.getValueManager(); SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count); QualType RetT = GetReturnType(Ex, ValMgr.getContext()); state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT)); state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false); // FIXME: Add a flag to the checker where allocations are assumed to // *not fail. #if 0 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) { bool isFeasible; state = state.Assume(loc::SymbolVal(Sym), true, isFeasible); assert(isFeasible && "Cannot assume fresh symbol is non-null."); } #endif break; } case RetEffect::NotOwnedSymbol: { unsigned Count = Builder.getCurrentBlockCount(); ValueManager &ValMgr = Eng.getValueManager(); SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count); QualType RetT = GetReturnType(Ex, ValMgr.getContext()); state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(), RetT)); state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false); break; } } // Generate a sink node if we are at the end of a path. GRExprEngine::NodeTy *NewNode = IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state) : Builder.MakeNode(Dst, Ex, Pred, state); // Annotate the edge with summary we used. // FIXME: This assumes that we always use the same summary when generating // this node. if (NewNode) SummaryLog[NewNode] = Summ; } void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, CallExpr* CE, SVal L, ExplodedNode<GRState>* Pred) { RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl()); EvalSummary(Dst, Eng, Builder, CE, 0, Summ, CE->arg_begin(), CE->arg_end(), Pred); } void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, ObjCMessageExpr* ME, ExplodedNode<GRState>* Pred) { RetainSummary* Summ; if (Expr* Receiver = ME->getReceiver()) { // We need the type-information of the tracked receiver object // Retrieve it from the state. ObjCInterfaceDecl* ID = 0; // FIXME: Wouldn't it be great if this code could be reduced? It's just // a chain of lookups. const GRState* St = Builder.GetState(Pred); SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver); SymbolRef Sym = V.getAsLocSymbol(); if (Sym) { if (const RefVal* T = St->get<RefBindings>(Sym)) { QualType Ty = T->getType(); if (const PointerType* PT = Ty->getAsPointerType()) { QualType PointeeTy = PT->getPointeeType(); if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy)) ID = IT->getDecl(); } } } Summ = Summaries.getMethodSummary(ME, ID); // Special-case: are we sending a mesage to "self"? // This is a hack. When we have full-IP this should be removed. if (!Summ) { ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl()); if (MD) { if (Expr* Receiver = ME->getReceiver()) { SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver); if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X)) if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) { // Create a summmary where all of the arguments "StopTracking". Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking); } } } } } else Summ = Summaries.getClassMethodSummary(ME->getClassName(), ME->getSelector()); EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ, ME->arg_begin(), ME->arg_end(), Pred); } namespace { class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor { GRStateRef state; public: StopTrackingCallback(GRStateRef st) : state(st) {} GRStateRef getState() { return state; } bool VisitSymbol(SymbolRef sym) { state = state.remove<RefBindings>(sym); return true; } const GRState* getState() const { return state.getState(); } }; } // end anonymous namespace void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) { // Are we storing to something that causes the value to "escape"? bool escapes = false; // A value escapes in three possible cases (this may change): // // (1) we are binding to something that is not a memory region. // (2) we are binding to a memregion that does not have stack storage // (3) we are binding to a memregion with stack storage that the store // does not understand. GRStateRef state = B.getState(); if (!isa<loc::MemRegionVal>(location)) escapes = true; else { const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion(); escapes = !B.getStateManager().hasStackStorage(R); if (!escapes) { // To test (3), generate a new state with the binding removed. If it is // the same state, then it escapes (since the store cannot represent // the binding). escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal()))); } } // If our store can represent the binding and we aren't storing to something // that doesn't have local storage then just return and have the simulation // state continue as is. if (!escapes) return; // Otherwise, find all symbols referenced by 'val' that we are tracking // and stop tracking them. B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState()); } std::pair<GRStateRef,bool> CFRefCount::HandleSymbolDeath(GRStateManager& VMgr, const GRState* St, const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak) { GRStateRef state(St, VMgr); assert ((!V.isReturnedOwned() || CD) && "CodeDecl must be available for reporting ReturnOwned errors."); if (V.isReturnedOwned() && V.getCount() == 0) if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) { std::string s = MD->getSelector().getAsString(); if (!followsReturnRule(s.c_str())) { hasLeak = true; state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned); return std::make_pair(state, true); } } // All other cases. hasLeak = V.isOwned() || ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0); if (!hasLeak) return std::make_pair(state.remove<RefBindings>(sid), false); return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak), false); } // Dead symbols. // Return statements. void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, ReturnStmt* S, ExplodedNode<GRState>* Pred) { Expr* RetE = S->getRetValue(); if (!RetE) return; GRStateRef state(Builder.GetState(Pred), Eng.getStateManager()); SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol(); if (!Sym) return; // Get the reference count binding (if any). const RefVal* T = state.get<RefBindings>(Sym); if (!T) return; // Change the reference count. RefVal X = *T; switch (X.getKind()) { case RefVal::Owned: { unsigned cnt = X.getCount(); assert (cnt > 0); X = RefVal::makeReturnedOwned(cnt - 1); break; } case RefVal::NotOwned: { unsigned cnt = X.getCount(); X = cnt ? RefVal::makeReturnedOwned(cnt - 1) : RefVal::makeReturnedNotOwned(); break; } default: return; } // Update the binding. state = state.set<RefBindings>(Sym, X); Builder.MakeNode(Dst, S, Pred, state); } // Assumptions. const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr, const GRState* St, SVal Cond, bool Assumption, bool& isFeasible) { // FIXME: We may add to the interface of EvalAssume the list of symbols // whose assumptions have changed. For now we just iterate through the // bindings and check if any of the tracked symbols are NULL. This isn't // too bad since the number of symbols we will track in practice are // probably small and EvalAssume is only called at branches and a few // other places. RefBindings B = St->get<RefBindings>(); if (B.isEmpty()) return St; bool changed = false; GRStateRef state(St, VMgr); RefBindings::Factory& RefBFactory = state.get_context<RefBindings>(); for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) { // Check if the symbol is null (or equal to any constant). // If this is the case, stop tracking the symbol. if (VMgr.getSymVal(St, I.getKey())) { changed = true; B = RefBFactory.Remove(B, I.getKey()); } } if (changed) state = state.set<RefBindings>(B); return state; } GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E, RefVal::Kind& hasErr) { // In GC mode [... release] and [... retain] do nothing. switch (E) { default: break; case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break; case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break; case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break; case NewAutoreleasePool: E = isGCEnabled() ? DoNothing : NewAutoreleasePool; break; } // Handle all use-after-releases. if (!isGCEnabled() && V.getKind() == RefVal::Released) { V = V ^ RefVal::ErrorUseAfterRelease; hasErr = V.getKind(); return state.set<RefBindings>(sym, V); } switch (E) { default: assert (false && "Unhandled CFRef transition."); case Dealloc: // Any use of -dealloc in GC is *bad*. if (isGCEnabled()) { V = V ^ RefVal::ErrorDeallocGC; hasErr = V.getKind(); break; } switch (V.getKind()) { default: assert(false && "Invalid case."); case RefVal::Owned: // The object immediately transitions to the released state. V = V ^ RefVal::Released; V.clearCounts(); return state.set<RefBindings>(sym, V); case RefVal::NotOwned: V = V ^ RefVal::ErrorDeallocNotOwned; hasErr = V.getKind(); break; } break; case NewAutoreleasePool: assert(!isGCEnabled()); return state.add<AutoreleaseStack>(sym); case MayEscape: if (V.getKind() == RefVal::Owned) { V = V ^ RefVal::NotOwned; break; } // Fall-through. case DoNothingByRef: case DoNothing: return state; case Autorelease: if (isGCEnabled()) return state; // Update the autorelease counts. state = SendAutorelease(state, ARCountFactory, sym); // Fall-through. case StopTracking: return state.remove<RefBindings>(sym); case IncRef: switch (V.getKind()) { default: assert(false); case RefVal::Owned: case RefVal::NotOwned: V = V + 1; break; case RefVal::Released: // Non-GC cases are handled above. assert(isGCEnabled()); V = (V ^ RefVal::Owned) + 1; break; } break; case SelfOwn: V = V ^ RefVal::NotOwned; // Fall-through. case DecRef: switch (V.getKind()) { default: // case 'RefVal::Released' handled above. assert (false); case RefVal::Owned: assert(V.getCount() > 0); if (V.getCount() == 1) V = V ^ RefVal::Released; V = V - 1; break; case RefVal::NotOwned: if (V.getCount() > 0) V = V - 1; else { V = V ^ RefVal::ErrorReleaseNotOwned; hasErr = V.getKind(); } break; case RefVal::Released: // Non-GC cases are handled above. assert(isGCEnabled()); V = V ^ RefVal::ErrorUseAfterRelease; hasErr = V.getKind(); break; } break; } return state.set<RefBindings>(sym, V); } //===----------------------------------------------------------------------===// // Error reporting. //===----------------------------------------------------------------------===// namespace { //===-------------===// // Bug Descriptions. // //===-------------===// class VISIBILITY_HIDDEN CFRefBug : public BugType { protected: CFRefCount& TF; CFRefBug(CFRefCount* tf, const char* name) : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {} public: CFRefCount& getTF() { return TF; } const CFRefCount& getTF() const { return TF; } // FIXME: Eventually remove. virtual const char* getDescription() const = 0; virtual bool isLeak() const { return false; } }; class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug { public: UseAfterRelease(CFRefCount* tf) : CFRefBug(tf, "Use-after-release") {} const char* getDescription() const { return "Reference-counted object is used after it is released"; } }; class VISIBILITY_HIDDEN BadRelease : public CFRefBug { public: BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {} const char* getDescription() const { return "Incorrect decrement of the reference count of a " "Core Foundation object (" "the object is not owned at this point by the caller)"; } }; class VISIBILITY_HIDDEN DeallocGC : public CFRefBug { public: DeallocGC(CFRefCount *tf) : CFRefBug(tf, "-dealloc called while using GC") {} const char *getDescription() const { return "-dealloc called while using GC"; } }; class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug { public: DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {} const char *getDescription() const { return "-dealloc sent to object that may be referenced elsewhere"; } }; class VISIBILITY_HIDDEN Leak : public CFRefBug { const bool isReturn; protected: Leak(CFRefCount* tf, const char* name, bool isRet) : CFRefBug(tf, name), isReturn(isRet) {} public: const char* getDescription() const { return ""; } bool isLeak() const { return true; } }; class VISIBILITY_HIDDEN LeakAtReturn : public Leak { public: LeakAtReturn(CFRefCount* tf, const char* name) : Leak(tf, name, true) {} }; class VISIBILITY_HIDDEN LeakWithinFunction : public Leak { public: LeakWithinFunction(CFRefCount* tf, const char* name) : Leak(tf, name, false) {} }; //===---------===// // Bug Reports. // //===---------===// class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport { protected: SymbolRef Sym; const CFRefCount &TF; public: CFRefReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode<GRState> *n, SymbolRef sym) : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {} virtual ~CFRefReport() {} CFRefBug& getBugType() { return (CFRefBug&) RangedBugReport::getBugType(); } const CFRefBug& getBugType() const { return (const CFRefBug&) RangedBugReport::getBugType(); } virtual void getRanges(BugReporter& BR, const SourceRange*& beg, const SourceRange*& end) { if (!getBugType().isLeak()) RangedBugReport::getRanges(BR, beg, end); else beg = end = 0; } SymbolRef getSymbol() const { return Sym; } PathDiagnosticPiece* getEndPath(BugReporter& BR, const ExplodedNode<GRState>* N); std::pair<const char**,const char**> getExtraDescriptiveText(); PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N, const ExplodedNode<GRState>* PrevN, const ExplodedGraph<GRState>& G, BugReporter& BR, NodeResolver& NR); }; class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport { SourceLocation AllocSite; const MemRegion* AllocBinding; public: CFRefLeakReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode<GRState> *n, SymbolRef sym, GRExprEngine& Eng); PathDiagnosticPiece* getEndPath(BugReporter& BR, const ExplodedNode<GRState>* N); SourceLocation getLocation() const { return AllocSite; } }; } // end anonymous namespace void CFRefCount::RegisterChecks(BugReporter& BR) { useAfterRelease = new UseAfterRelease(this); BR.Register(useAfterRelease); releaseNotOwned = new BadRelease(this); BR.Register(releaseNotOwned); deallocGC = new DeallocGC(this); BR.Register(deallocGC); deallocNotOwned = new DeallocNotOwned(this); BR.Register(deallocNotOwned); // First register "return" leaks. const char* name = 0; if (isGCEnabled()) name = "Leak of returned object when using garbage collection"; else if (getLangOptions().getGCMode() == LangOptions::HybridGC) name = "Leak of returned object when not using garbage collection (GC) in " "dual GC/non-GC code"; else { assert(getLangOptions().getGCMode() == LangOptions::NonGC); name = "Leak of returned object"; } leakAtReturn = new LeakAtReturn(this, name); BR.Register(leakAtReturn); // Second, register leaks within a function/method. if (isGCEnabled()) name = "Leak of object when using garbage collection"; else if (getLangOptions().getGCMode() == LangOptions::HybridGC) name = "Leak of object when not using garbage collection (GC) in " "dual GC/non-GC code"; else { assert(getLangOptions().getGCMode() == LangOptions::NonGC); name = "Leak"; } leakWithinFunction = new LeakWithinFunction(this, name); BR.Register(leakWithinFunction); // Save the reference to the BugReporter. this->BR = &BR; } static const char* Msgs[] = { // GC only "Code is compiled to only use garbage collection", // No GC. "Code is compiled to use reference counts", // Hybrid, with GC. "Code is compiled to use either garbage collection (GC) or reference counts" " (non-GC). The bug occurs with GC enabled", // Hybrid, without GC "Code is compiled to use either garbage collection (GC) or reference counts" " (non-GC). The bug occurs in non-GC mode" }; std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() { CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF(); switch (TF.getLangOptions().getGCMode()) { default: assert(false); case LangOptions::GCOnly: assert (TF.isGCEnabled()); return std::make_pair(&Msgs[0], &Msgs[0]+1); case LangOptions::NonGC: assert (!TF.isGCEnabled()); return std::make_pair(&Msgs[1], &Msgs[1]+1); case LangOptions::HybridGC: if (TF.isGCEnabled()) return std::make_pair(&Msgs[2], &Msgs[2]+1); else return std::make_pair(&Msgs[3], &Msgs[3]+1); } } static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V, ArgEffect X) { for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end(); I!=E; ++I) if (*I == X) return true; return false; } PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N, const ExplodedNode<GRState>* PrevN, const ExplodedGraph<GRState>& G, BugReporter& BR, NodeResolver& NR) { // Check if the type state has changed. GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager(); GRStateRef PrevSt(PrevN->getState(), StMgr); GRStateRef CurrSt(N->getState(), StMgr); const RefVal* CurrT = CurrSt.get<RefBindings>(Sym); if (!CurrT) return NULL; const RefVal& CurrV = *CurrT; const RefVal* PrevT = PrevSt.get<RefBindings>(Sym); // Create a string buffer to constain all the useful things we want // to tell the user. std::string sbuf; llvm::raw_string_ostream os(sbuf); // This is the allocation site since the previous node had no bindings // for this symbol. if (!PrevT) { Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); if (CallExpr *CE = dyn_cast<CallExpr>(S)) { // Get the name of the callee (if it is available). SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee()); if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X)) os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\''; else os << "function call"; } else { assert (isa<ObjCMessageExpr>(S)); os << "Method"; } if (CurrV.getObjKind() == RetEffect::CF) { os << " returns a Core Foundation object with a "; } else { assert (CurrV.getObjKind() == RetEffect::ObjC); os << " returns an Objective-C object with a "; } if (CurrV.isOwned()) { os << "+1 retain count (owning reference)."; if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) { assert(CurrV.getObjKind() == RetEffect::CF); os << " " "Core Foundation objects are not automatically garbage collected."; } } else { assert (CurrV.isNotOwned()); os << "+0 retain count (non-owning reference)."; } PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager()); return new PathDiagnosticEventPiece(Pos, os.str()); } // Gather up the effects that were performed on the object at this // program point llvm::SmallVector<ArgEffect, 2> AEffects; if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) { // We only have summaries attached to nodes after evaluating CallExpr and // ObjCMessageExprs. Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); if (CallExpr *CE = dyn_cast<CallExpr>(S)) { // Iterate through the parameter expressions and see if the symbol // was ever passed as an argument. unsigned i = 0; for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end(); AI!=AE; ++AI, ++i) { // Retrieve the value of the argument. Is it the symbol // we are interested in? if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym) continue; // We have an argument. Get the effect! AEffects.push_back(Summ->getArg(i)); } } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) { if (Expr *receiver = ME->getReceiver()) if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) { // The symbol we are tracking is the receiver. AEffects.push_back(Summ->getReceiverEffect()); } } } do { // Get the previous type state. RefVal PrevV = *PrevT; // Specially handle -dealloc. if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) { // Determine if the object's reference count was pushed to zero. assert(!(PrevV == CurrV) && "The typestate *must* have changed."); // We may not have transitioned to 'release' if we hit an error. // This case is handled elsewhere. if (CurrV.getKind() == RefVal::Released) { assert(CurrV.getCount() == 0); os << "Object released by directly sending the '-dealloc' message"; break; } } // Specially handle CFMakeCollectable and friends. if (contains(AEffects, MakeCollectable)) { // Get the name of the function. Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); loc::FuncVal FV = cast<loc::FuncVal>(CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee())); const std::string& FName = FV.getDecl()->getNameAsString(); if (TF.isGCEnabled()) { // Determine if the object's reference count was pushed to zero. assert(!(PrevV == CurrV) && "The typestate *must* have changed."); os << "In GC mode a call to '" << FName << "' decrements an object's retain count and registers the " "object with the garbage collector. "; if (CurrV.getKind() == RefVal::Released) { assert(CurrV.getCount() == 0); os << "Since it now has a 0 retain count the object can be " "automatically collected by the garbage collector."; } else os << "An object must have a 0 retain count to be garbage collected. " "After this call its retain count is +" << CurrV.getCount() << '.'; } else os << "When GC is not enabled a call to '" << FName << "' has no effect on its argument."; // Nothing more to say. break; } // Determine if the typestate has changed. if (!(PrevV == CurrV)) switch (CurrV.getKind()) { case RefVal::Owned: case RefVal::NotOwned: if (PrevV.getCount() == CurrV.getCount()) return 0; if (PrevV.getCount() > CurrV.getCount()) os << "Reference count decremented."; else os << "Reference count incremented."; if (unsigned Count = CurrV.getCount()) os << " The object now has a +" << Count << " retain count."; if (PrevV.getKind() == RefVal::Released) { assert(TF.isGCEnabled() && CurrV.getCount() > 0); os << " The object is not eligible for garbage collection until the " "retain count reaches 0 again."; } break; case RefVal::Released: os << "Object released."; break; case RefVal::ReturnedOwned: os << "Object returned to caller as an owning reference (single retain " "count transferred to caller)."; break; case RefVal::ReturnedNotOwned: os << "Object returned to caller with a +0 (non-owning) retain count."; break; default: return NULL; } // Emit any remaining diagnostics for the argument effects (if any). for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(), E=AEffects.end(); I != E; ++I) { // A bunch of things have alternate behavior under GC. if (TF.isGCEnabled()) switch (*I) { default: break; case Autorelease: os << "In GC mode an 'autorelease' has no effect."; continue; case IncRefMsg: os << "In GC mode the 'retain' message has no effect."; continue; case DecRefMsg: os << "In GC mode the 'release' message has no effect."; continue; } } } while(0); if (os.str().empty()) return 0; // We have nothing to say! Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager()); PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str()); // Add the range by scanning the children of the statement for any bindings // to Sym. for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I) if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) { P->addRange(Exp->getSourceRange()); break; } return P; } namespace { class VISIBILITY_HIDDEN FindUniqueBinding : public StoreManager::BindingsHandler { SymbolRef Sym; const MemRegion* Binding; bool First; public: FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {} bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R, SVal val) { SymbolRef SymV = val.getAsSymbol(); if (!SymV || SymV != Sym) return true; if (Binding) { First = false; return false; } else Binding = R; return true; } operator bool() { return First && Binding; } const MemRegion* getRegion() { return Binding; } }; } static std::pair<const ExplodedNode<GRState>*,const MemRegion*> GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N, SymbolRef Sym) { // Find both first node that referred to the tracked symbol and the // memory location that value was store to. const ExplodedNode<GRState>* Last = N; const MemRegion* FirstBinding = 0; while (N) { const GRState* St = N->getState(); RefBindings B = St->get<RefBindings>(); if (!B.lookup(Sym)) break; FindUniqueBinding FB(Sym); StateMgr.iterBindings(St, FB); if (FB) FirstBinding = FB.getRegion(); Last = N; N = N->pred_empty() ? NULL : *(N->pred_begin()); } return std::make_pair(Last, FirstBinding); } PathDiagnosticPiece* CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) { // Tell the BugReporter to report cases when the tracked symbol is // assigned to different variables, etc. GRBugReporter& BR = cast<GRBugReporter>(br); cast<GRBugReporter>(BR).addNotableSymbol(Sym); return RangedBugReport::getEndPath(BR, EndN); } PathDiagnosticPiece* CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){ GRBugReporter& BR = cast<GRBugReporter>(br); // Tell the BugReporter to report cases when the tracked symbol is // assigned to different variables, etc. cast<GRBugReporter>(BR).addNotableSymbol(Sym); // We are reporting a leak. Walk up the graph to get to the first node where // the symbol appeared, and also get the first VarDecl that tracked object // is stored to. const ExplodedNode<GRState>* AllocNode = 0; const MemRegion* FirstBinding = 0; llvm::tie(AllocNode, FirstBinding) = GetAllocationSite(BR.getStateManager(), EndN, Sym); // Get the allocate site. assert(AllocNode); Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt(); SourceManager& SMgr = BR.getContext().getSourceManager(); unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart()); // Compute an actual location for the leak. Sometimes a leak doesn't // occur at an actual statement (e.g., transition between blocks; end // of function) so we need to walk the graph and compute a real location. const ExplodedNode<GRState>* LeakN = EndN; PathDiagnosticLocation L; while (LeakN) { ProgramPoint P = LeakN->getLocation(); if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) { L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr); break; } else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) { if (const Stmt* Term = BE->getSrc()->getTerminator()) { L = PathDiagnosticLocation(Term->getLocStart(), SMgr); break; } } LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin()); } if (!L.isValid()) { CompoundStmt *CS = BR.getStateManager().getCodeDecl().getBody(); L = PathDiagnosticLocation(CS->getRBracLoc(), SMgr); } std::string sbuf; llvm::raw_string_ostream os(sbuf); os << "Object allocated on line " << AllocLine; if (FirstBinding) os << " and stored into '" << FirstBinding->getString() << '\''; // Get the retain count. const RefVal* RV = EndN->getState()->get<RefBindings>(Sym); if (RV->getKind() == RefVal::ErrorLeakReturned) { // FIXME: Per comments in rdar://6320065, "create" only applies to CF // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership // to the caller for NS objects. ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl()); os << " is returned from a method whose name ('" << MD.getSelector().getAsString() << "') does not contain 'copy' or otherwise starts with" " 'new' or 'alloc'. This violates the naming convention rules given" " in the Memory Management Guide for Cocoa (object leaked)."; } else os << " is no longer referenced after this point and has a retain count of" " +" << RV->getCount() << " (object leaked)."; return new PathDiagnosticEventPiece(L, os.str()); } CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf, ExplodedNode<GRState> *n, SymbolRef sym, GRExprEngine& Eng) : CFRefReport(D, tf, n, sym) { // Most bug reports are cached at the location where they occured. // With leaks, we want to unique them by the location where they were // allocated, and only report a single path. To do this, we need to find // the allocation site of a piece of tracked memory, which we do via a // call to GetAllocationSite. This will walk the ExplodedGraph backwards. // Note that this is *not* the trimmed graph; we are guaranteed, however, // that all ancestor nodes that represent the allocation site have the // same SourceLocation. const ExplodedNode<GRState>* AllocNode = 0; llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding. GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol()); // Get the SourceLocation for the allocation site. ProgramPoint P = AllocNode->getLocation(); AllocSite = cast<PostStmt>(P).getStmt()->getLocStart(); // Fill in the description of the bug. Description.clear(); llvm::raw_string_ostream os(Description); SourceManager& SMgr = Eng.getContext().getSourceManager(); unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite); os << "Potential leak of object allocated on line " << AllocLine; // FIXME: AllocBinding doesn't get populated for RegionStore yet. if (AllocBinding) os << " and stored into '" << AllocBinding->getString() << '\''; } //===----------------------------------------------------------------------===// // Handle dead symbols and end-of-path. //===----------------------------------------------------------------------===// void CFRefCount::EvalEndPath(GRExprEngine& Eng, GREndPathNodeBuilder<GRState>& Builder) { const GRState* St = Builder.getState(); RefBindings B = St->get<RefBindings>(); llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked; const Decl* CodeDecl = &Eng.getGraph().getCodeDecl(); for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) { bool hasLeak = false; std::pair<GRStateRef, bool> X = HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl, (*I).first, (*I).second, hasLeak); St = X.first; if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second)); } if (Leaked.empty()) return; ExplodedNode<GRState>* N = Builder.MakeNode(St); if (!N) return; for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn : leakWithinFunction); assert(BT && "BugType not initialized."); CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng); BR->EmitReport(report); } } void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, ExplodedNode<GRState>* Pred, Stmt* S, const GRState* St, SymbolReaper& SymReaper) { // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor. RefBindings B = St->get<RefBindings>(); llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked; for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I != E; ++I) { const RefVal* T = B.lookup(*I); if (!T) continue; bool hasLeak = false; std::pair<GRStateRef, bool> X = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak); St = X.first; if (hasLeak) Leaked.push_back(std::make_pair(*I,X.second)); } if (!Leaked.empty()) { // Create a new intermediate node representing the leak point. We // use a special program point that represents this checker-specific // transition. We use the address of RefBIndex as a unique tag for this // checker. We will create another node (if we don't cache out) that // removes the retain-count bindings from the state. // NOTE: We use 'generateNode' so that it does interplay with the // auto-transition logic. ExplodedNode<GRState>* N = Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred); if (!N) return; // Generate the bug reports. for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator I = Leaked.begin(), E = Leaked.end(); I != E; ++I) { CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn : leakWithinFunction); assert(BT && "BugType not initialized."); CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng); BR->EmitReport(report); } Pred = N; } // Now generate a new node that nukes the old bindings. GRStateRef state(St, Eng.getStateManager()); RefBindings::Factory& F = state.get_context<RefBindings>(); for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(), E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I); state = state.set<RefBindings>(B); Builder.MakeNode(Dst, S, Pred, state); } void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst, GRStmtNodeBuilder<GRState>& Builder, Expr* NodeExpr, Expr* ErrorExpr, ExplodedNode<GRState>* Pred, const GRState* St, RefVal::Kind hasErr, SymbolRef Sym) { Builder.BuildSinks = true; GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St); if (!N) return; CFRefBug *BT = 0; switch (hasErr) { default: assert(false && "Unhandled error."); return; case RefVal::ErrorUseAfterRelease: BT = static_cast<CFRefBug*>(useAfterRelease); break; case RefVal::ErrorReleaseNotOwned: BT = static_cast<CFRefBug*>(releaseNotOwned); break; case RefVal::ErrorDeallocGC: BT = static_cast<CFRefBug*>(deallocGC); break; case RefVal::ErrorDeallocNotOwned: BT = static_cast<CFRefBug*>(deallocNotOwned); break; } CFRefReport *report = new CFRefReport(*BT, *this, N, Sym); report->addRange(ErrorExpr->getSourceRange()); BR->EmitReport(report); } //===----------------------------------------------------------------------===// // Transfer function creation for external clients. //===----------------------------------------------------------------------===// GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled, const LangOptions& lopts) { return new CFRefCount(Ctx, GCEnabled, lopts); } <file_sep>/test/SemaTemplate/instantiate-method.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T> class X { public: void f(T x); // expected-error{{argument may not have 'void' type}} void g(T*); static int h(T, T); // expected-error 2{{argument may not have 'void' type}} }; int identity(int x) { return x; } void test(X<int> *xi, int *ip, X<int(int)> *xf) { xi->f(17); xi->g(ip); xf->f(&identity); xf->g(identity); X<int>::h(17, 25); X<int(int)>::h(identity, &identity); } void test_bad() { X<void> xv; // expected-note{{in instantiation of template class 'class X<void>' requested here}} } template<typename T, typename U> class Overloading { public: int& f(T, T); // expected-note{{previous declaration is here}} float& f(T, U); // expected-error{{functions that differ only in their return type cannot be overloaded}} }; void test_ovl(Overloading<int, long> *oil, int i, long l) { int &ir = oil->f(i, i); float &fr = oil->f(i, l); } void test_ovl_bad() { Overloading<float, float> off; // expected-note{{in instantiation of template class 'class Overloading<float, float>' requested here}} } template<typename T> class HasDestructor { public: virtual ~HasDestructor() = 0; }; int i = sizeof(HasDestructor<int>); // FIXME: forces instantiation, but // the code below should probably instantiate by itself. int abstract_destructor[__is_abstract(HasDestructor<int>)? 1 : -1]; template<typename T> class Constructors { public: Constructors(const T&); Constructors(const Constructors &other); }; void test_constructors() { Constructors<int> ci1(17); Constructors<int> ci2 = ci1; } template<typename T> struct ConvertsTo { operator T(); }; void test_converts_to(ConvertsTo<int> ci, ConvertsTo<int *> cip) { int i = ci; int *ip = cip; } <file_sep>/tools/ccc/test/ccc/Xclang.c // RUN: xcc -fsyntax-only -Xclang --help %s | grep "OVERVIEW: LLVM 'Clang' Compiler" <file_sep>/test/Frontend/rewrite-macros.c // RUN: clang-cc -verify --rewrite-macros -o %t %s && #define A(a,b) a ## b // RUN: grep '12 */\*A\*/ /\*(1,2)\*/' %t && A(1,2) // RUN: grep '/\*_Pragma("mark")\*/' %t && _Pragma("mark") // RUN: grep "//#warning eek" %t && /* expected-warning {{#warning eek}} */ #warning eek // RUN: grep "//#pragma mark mark" %t && #pragma mark mark // RUN: true <file_sep>/lib/CodeGen/ABIInfo.h //===----- ABIInfo.h - ABI information access & encapsulation ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef CLANG_CODEGEN_ABIINFO_H #define CLANG_CODEGEN_ABIINFO_H namespace llvm { class Type; } namespace clang { class ASTContext; // FIXME: This is a layering issue if we want to move ABIInfo // down. Fortunately CGFunctionInfo has no real tie to CodeGen. namespace CodeGen { class CGFunctionInfo; class CodeGenFunction; } /* FIXME: All of this stuff should be part of the target interface somehow. It is currently here because it is not clear how to factor the targets to support this, since the Targets currently live in a layer below types n'stuff. */ /// ABIArgInfo - Helper class to encapsulate information about how a /// specific C type should be passed to or returned from a function. class ABIArgInfo { public: enum Kind { Direct, /// Pass the argument directly using the normal /// converted LLVM type. Complex and structure types /// are passed using first class aggregates. Indirect, /// Pass the argument indirectly via a hidden pointer /// with the specified alignment (0 indicates default /// alignment). Ignore, /// Ignore the argument (treat as void). Useful for /// void and empty structs. Coerce, /// Only valid for aggregate return types, the argument /// should be accessed by coercion to a provided type. Expand, /// Only valid for aggregate argument types. The /// structure should be expanded into consecutive /// arguments for its constituent fields. Currently /// expand is only allowed on structures whose fields /// are all scalar types or are themselves expandable /// types. KindFirst=Direct, KindLast=Expand }; private: Kind TheKind; const llvm::Type *TypeData; unsigned UIntData; ABIArgInfo(Kind K, const llvm::Type *TD=0, unsigned UI=0) : TheKind(K), TypeData(TD), UIntData(UI) {} public: ABIArgInfo() : TheKind(Direct), TypeData(0), UIntData(0) {} static ABIArgInfo getDirect() { return ABIArgInfo(Direct); } static ABIArgInfo getIgnore() { return ABIArgInfo(Ignore); } static ABIArgInfo getCoerce(const llvm::Type *T) { return ABIArgInfo(Coerce, T); } static ABIArgInfo getIndirect(unsigned Alignment) { return ABIArgInfo(Indirect, 0, Alignment); } static ABIArgInfo getExpand() { return ABIArgInfo(Expand); } Kind getKind() const { return TheKind; } bool isDirect() const { return TheKind == Direct; } bool isIgnore() const { return TheKind == Ignore; } bool isCoerce() const { return TheKind == Coerce; } bool isIndirect() const { return TheKind == Indirect; } bool isExpand() const { return TheKind == Expand; } // Coerce accessors const llvm::Type *getCoerceToType() const { assert(TheKind == Coerce && "Invalid kind!"); return TypeData; } // ByVal accessors unsigned getIndirectAlign() const { assert(TheKind == Indirect && "Invalid kind!"); return UIntData; } void dump() const; }; /// ABIInfo - Target specific hooks for defining how a type should be /// passed or returned from functions. class ABIInfo { public: virtual ~ABIInfo(); virtual void computeInfo(CodeGen::CGFunctionInfo &FI, ASTContext &Ctx) const = 0; /// EmitVAArg - Emit the target dependent code to load a value of /// \arg Ty from the va_list pointed to by \arg VAListAddr. // FIXME: This is a gaping layering violation if we wanted to drop // the ABI information any lower than CodeGen. Of course, for // VAArg handling it has to be at this level; there is no way to // abstract this out. virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty, CodeGen::CodeGenFunction &CGF) const = 0; }; } // end namespace clang #endif <file_sep>/test/CodeGen/2008-07-21-mixed-var-fn-decl.c // RUN: clang-cc -emit-llvm -o - %s | grep -e "@g[0-9] " | count 2 int g0, f0(); int f1(), g1; <file_sep>/test/Preprocessor/cxx_oper_keyword.cpp // RUN: not clang-cc %s -E && // RUN: clang-cc %s -E -fno-operator-names // Not valid in C++ unless -fno-operator-names is passed. #define and foo <file_sep>/test/Preprocessor/macro_paste_bad.c // RUN: clang-cc -Eonly %s 2>&1 | grep error // pasting ""x"" and ""+"" does not give a valid preprocessing token #define XYZ x ## + XYZ <file_sep>/test/CodeGen/struct.c // RUN: clang-cc -triple i386-unknown-unknown %s -emit-llvm -o - struct { int x; int y; } point; void fn1() { point.x = 42; } /* Nested member */ struct { struct { int a; int b; } p1; } point2; void fn2() { point2.p1.a = 42; } /* Indirect reference */ typedef struct __sf { unsigned char *c; short flags; } F; typedef struct __sf2 { F *ff; } F2; int fn3(F2 *c) { if (c->ff->c >= 0) return 1; else return 0; } /* Nested structs */ typedef struct NA { int data; struct NA *next; } NA; void f1() { NA a; } typedef struct NB { int d1; struct _B2 { int d2; struct NB *n2; } B2; } NB; void f2() { NB b; } extern NB *f3(); void f4() { f3()->d1 = 42; } void f5() { (f3())->d1 = 42; } /* Function calls */ typedef struct { int location; int length; } range; extern range f6(); void f7() { range r = f6(); } /* Member expressions */ typedef struct { range range1; range range2; } rangepair; void f8() { rangepair p; range r = p.range1; } void f9(range *p) { range r = *p; } void f10(range *p) { range r = p[0]; } /* _Bool types */ struct _w { short a,b; short c,d; short e,f; short g; unsigned int h,i; _Bool j,k; } ws; /* Implicit casts (due to typedefs) */ typedef struct _a { int a; } a; void f11() { struct _a a1; a a2; a1 = a2; a2 = a1; } /* Implicit casts (due to const) */ void f12() { struct _a a1; const struct _a a2; a1 = a2; } /* struct initialization */ struct a13 {int b; int c;}; struct a13 c13 = {5}; typedef struct a13 a13; struct a14 { short a; int b; } x = {1, 1}; /* flexible array members */ struct a15 {char a; int b[];} c15; int a16(void) {c15.a = 1;} /* compound literals */ void f13() { a13 x; x = (a13){1,2}; } /* va_arg */ int f14(int i, ...) { __builtin_va_list l; __builtin_va_start(l,i); a13 b = __builtin_va_arg(l, a13); int c = __builtin_va_arg(l, a13).c; return b.b; } /* Attribute packed */ struct __attribute__((packed)) S2839 { double a[19]; signed char b; } s2839[5]; struct __attribute__((packed)) SS { long double a; char b; } SS; /* As lvalue */ int f15() { extern range f15_ext(); return f15_ext().location; } range f16() { extern rangepair f16_ext(); return f16_ext().range1; } int f17() { extern range f17_ext(); range r; return (r = f17_ext()).location; } range f18() { extern rangepair f18_ext(); rangepair rp; return (rp = f18_ext()).range1; } <file_sep>/test/Analysis/func.c // RUN: clang-cc -analyze -checker-simple -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -verify %s void f(void) { void (*p)(void); p = f; p = &f; p(); (*p)(); } void g(void (*fp)(void)); void f2() { g(f); } <file_sep>/include/clang/Analysis/LocalCheckers.h //==- LocalCheckers.h - Intra-Procedural+Flow-Sensitive Checkers -*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface to call a set of intra-procedural (local) // checkers that use flow/path-sensitive analyses to find bugs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_LOCALCHECKERS_H #define LLVM_CLANG_ANALYSIS_LOCALCHECKERS_H namespace clang { class CFG; class Decl; class Diagnostic; class ASTContext; class PathDiagnosticClient; class GRTransferFuncs; class BugType; class LangOptions; class ParentMap; class LiveVariables; class BugReporter; class ObjCImplementationDecl; class LangOptions; class GRExprEngine; void CheckDeadStores(LiveVariables& L, BugReporter& BR); void CheckUninitializedValues(CFG& cfg, ASTContext& Ctx, Diagnostic& Diags, bool FullUninitTaint=false); GRTransferFuncs* MakeGRSimpleValsTF(); GRTransferFuncs* MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled, const LangOptions& lopts); void CheckObjCDealloc(ObjCImplementationDecl* D, const LangOptions& L, BugReporter& BR); void CheckObjCInstMethSignature(ObjCImplementationDecl* ID, BugReporter& BR); void CheckObjCUnusedIvar(ObjCImplementationDecl* D, BugReporter& BR); void RegisterAppleChecks(GRExprEngine& Eng); } // end namespace clang #endif <file_sep>/test/CodeGen/private-extern.c // RUN: clang-cc -emit-llvm -o %t %s && // RUN: grep '@g0 = external hidden constant i32' %t && // RUN: grep '@g1 = hidden constant i32 1' %t __private_extern__ const int g0; __private_extern__ const int g1 = 1; int f0(void) { return g0; } <file_sep>/test/SemaTemplate/default-arguments.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T, int N = 2> struct X; // expected-note{{template is declared here}} X<int, 1> *x1; X<int> *x2; X<> *x3; // expected-error{{too few template arguments for class template 'X'}} template<typename U = float, int M> struct X; X<> *x4; <file_sep>/lib/AST/DeclObjC.cpp //===--- DeclObjC.cpp - ObjC Declaration AST Node Implementation ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Objective-C related Decl classes. // //===----------------------------------------------------------------------===// #include "clang/AST/DeclObjC.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Stmt.h" #include "llvm/ADT/STLExtras.h" using namespace clang; //===----------------------------------------------------------------------===// // ObjCListBase //===----------------------------------------------------------------------===// void ObjCListBase::Destroy(ASTContext &Ctx) { Ctx.Deallocate(List); NumElts = 0; List = 0; } void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) { assert(List == 0 && "Elements already set!"); if (Elts == 0) return; // Setting to an empty list is a noop. List = new (Ctx) void*[Elts]; NumElts = Elts; memcpy(List, InList, sizeof(void*)*Elts); } //===----------------------------------------------------------------------===// // ObjCInterfaceDecl //===----------------------------------------------------------------------===// // Get the local instance method declared in this interface. ObjCMethodDecl * ObjCContainerDecl::getInstanceMethod(ASTContext &Context, Selector Sel) const { // Since instance & class methods can have the same name, the loop below // ensures we get the correct method. // // @interface Whatever // - (int) class_method; // + (float) class_method; // @end // lookup_const_iterator Meth, MethEnd; for (llvm::tie(Meth, MethEnd) = lookup(Context, Sel); Meth != MethEnd; ++Meth) { ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth); if (MD && MD->isInstanceMethod()) return MD; } return 0; } // Get the local class method declared in this interface. ObjCMethodDecl * ObjCContainerDecl::getClassMethod(ASTContext &Context, Selector Sel) const { // Since instance & class methods can have the same name, the loop below // ensures we get the correct method. // // @interface Whatever // - (int) class_method; // + (float) class_method; // @end // lookup_const_iterator Meth, MethEnd; for (llvm::tie(Meth, MethEnd) = lookup(Context, Sel); Meth != MethEnd; ++Meth) { ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth); if (MD && MD->isClassMethod()) return MD; } return 0; } /// FindPropertyDeclaration - Finds declaration of the property given its name /// in 'PropertyId' and returns it. It returns 0, if not found. /// FIXME: Convert to DeclContext lookup... /// ObjCPropertyDecl * ObjCContainerDecl::FindPropertyDeclaration(ASTContext &Context, IdentifierInfo *PropertyId) const { for (prop_iterator I = prop_begin(Context), E = prop_end(Context); I != E; ++I) if ((*I)->getIdentifier() == PropertyId) return *I; const ObjCProtocolDecl *PID = dyn_cast<ObjCProtocolDecl>(this); if (PID) { for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), E = PID->protocol_end(); I != E; ++I) if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(Context, PropertyId)) return P; } if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(this)) { // Look through categories. for (ObjCCategoryDecl *Category = OID->getCategoryList(); Category; Category = Category->getNextClassCategory()) { if (ObjCPropertyDecl *P = Category->FindPropertyDeclaration(Context, PropertyId)) return P; } // Look through protocols. for (ObjCInterfaceDecl::protocol_iterator I = OID->protocol_begin(), E = OID->protocol_end(); I != E; ++I) { if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(Context, PropertyId)) return P; } if (OID->getSuperClass()) return OID->getSuperClass()->FindPropertyDeclaration(Context, PropertyId); } else if (const ObjCCategoryDecl *OCD = dyn_cast<ObjCCategoryDecl>(this)) { // Look through protocols. for (ObjCInterfaceDecl::protocol_iterator I = OCD->protocol_begin(), E = OCD->protocol_end(); I != E; ++I) { if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(Context, PropertyId)) return P; } } return 0; } ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable( ASTContext &Context, IdentifierInfo *ID, ObjCInterfaceDecl *&clsDeclared) { ObjCInterfaceDecl* ClassDecl = this; while (ClassDecl != NULL) { for (ivar_iterator I = ClassDecl->ivar_begin(), E = ClassDecl->ivar_end(); I != E; ++I) { if ((*I)->getIdentifier() == ID) { clsDeclared = ClassDecl; return *I; } } // look into properties. for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(Context), E = ClassDecl->prop_end(Context); I != E; ++I) { ObjCPropertyDecl *PDecl = (*I); if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) if (IV->getIdentifier() == ID) { clsDeclared = ClassDecl; return IV; } } ClassDecl = ClassDecl->getSuperClass(); } return NULL; } /// lookupInstanceMethod - This method returns an instance method by looking in /// the class, its categories, and its super classes (using a linear search). ObjCMethodDecl *ObjCInterfaceDecl::lookupInstanceMethod(ASTContext &Context, Selector Sel) { ObjCInterfaceDecl* ClassDecl = this; ObjCMethodDecl *MethodDecl = 0; while (ClassDecl != NULL) { if ((MethodDecl = ClassDecl->getInstanceMethod(Context, Sel))) return MethodDecl; // Didn't find one yet - look through protocols. const ObjCList<ObjCProtocolDecl> &Protocols = ClassDecl->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), E = Protocols.end(); I != E; ++I) if ((MethodDecl = (*I)->lookupInstanceMethod(Context, Sel))) return MethodDecl; // Didn't find one yet - now look through categories. ObjCCategoryDecl *CatDecl = ClassDecl->getCategoryList(); while (CatDecl) { if ((MethodDecl = CatDecl->getInstanceMethod(Context, Sel))) return MethodDecl; // Didn't find one yet - look through protocols. const ObjCList<ObjCProtocolDecl> &Protocols = CatDecl->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), E = Protocols.end(); I != E; ++I) if ((MethodDecl = (*I)->lookupInstanceMethod(Context, Sel))) return MethodDecl; CatDecl = CatDecl->getNextClassCategory(); } ClassDecl = ClassDecl->getSuperClass(); } return NULL; } // lookupClassMethod - This method returns a class method by looking in the // class, its categories, and its super classes (using a linear search). ObjCMethodDecl *ObjCInterfaceDecl::lookupClassMethod(ASTContext &Context, Selector Sel) { ObjCInterfaceDecl* ClassDecl = this; ObjCMethodDecl *MethodDecl = 0; while (ClassDecl != NULL) { if ((MethodDecl = ClassDecl->getClassMethod(Context, Sel))) return MethodDecl; // Didn't find one yet - look through protocols. for (ObjCInterfaceDecl::protocol_iterator I = ClassDecl->protocol_begin(), E = ClassDecl->protocol_end(); I != E; ++I) if ((MethodDecl = (*I)->lookupClassMethod(Context, Sel))) return MethodDecl; // Didn't find one yet - now look through categories. ObjCCategoryDecl *CatDecl = ClassDecl->getCategoryList(); while (CatDecl) { if ((MethodDecl = CatDecl->getClassMethod(Context, Sel))) return MethodDecl; // Didn't find one yet - look through protocols. const ObjCList<ObjCProtocolDecl> &Protocols = CatDecl->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), E = Protocols.end(); I != E; ++I) if ((MethodDecl = (*I)->lookupClassMethod(Context, Sel))) return MethodDecl; CatDecl = CatDecl->getNextClassCategory(); } ClassDecl = ClassDecl->getSuperClass(); } return NULL; } //===----------------------------------------------------------------------===// // ObjCMethodDecl //===----------------------------------------------------------------------===// ObjCMethodDecl *ObjCMethodDecl::Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, DeclContext *contextDecl, bool isInstance, bool isVariadic, bool isSynthesized, ImplementationControl impControl) { return new (C) ObjCMethodDecl(beginLoc, endLoc, SelInfo, T, contextDecl, isInstance, isVariadic, isSynthesized, impControl); } void ObjCMethodDecl::Destroy(ASTContext &C) { if (Body) Body->Destroy(C); if (SelfDecl) SelfDecl->Destroy(C); for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I) if (*I) (*I)->Destroy(C); ParamInfo.Destroy(C); Decl::Destroy(C); } void ObjCMethodDecl::createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *OID) { QualType selfTy; if (isInstanceMethod()) { // There may be no interface context due to error in declaration // of the interface (which has been reported). Recover gracefully. if (OID) { selfTy =Context.getObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(OID)); selfTy = Context.getPointerType(selfTy); } else { selfTy = Context.getObjCIdType(); } } else // we have a factory method. selfTy = Context.getObjCClassType(); SelfDecl = ImplicitParamDecl::Create(Context, this, SourceLocation(), &Context.Idents.get("self"), selfTy); CmdDecl = ImplicitParamDecl::Create(Context, this, SourceLocation(), &Context.Idents.get("_cmd"), Context.getObjCSelType()); } /// getSynthesizedMethodSize - Compute size of synthesized method name /// as done be the rewrite. /// unsigned ObjCMethodDecl::getSynthesizedMethodSize() const { // syntesized method name is a concatenation of -/+[class-name selector] // Get length of this name. unsigned length = 3; // _I_ or _C_ length += getClassInterface()->getNameAsString().size()+1; // extra for _ if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(getDeclContext())) length += CID->getNameAsString().size()+1; length += getSelector().getAsString().size(); // selector name return length; } ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() { if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext())) return ID; if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext())) return CD->getClassInterface(); if (ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(getDeclContext())) return IMD->getClassInterface(); if (ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(getDeclContext())) return CID->getClassInterface(); assert(false && "unknown method context"); return 0; } //===----------------------------------------------------------------------===// // ObjCInterfaceDecl //===----------------------------------------------------------------------===// ObjCInterfaceDecl *ObjCInterfaceDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, SourceLocation ClassLoc, bool ForwardDecl, bool isInternal){ return new (C) ObjCInterfaceDecl(DC, atLoc, Id, ClassLoc, ForwardDecl, isInternal); } ObjCInterfaceDecl:: ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, SourceLocation CLoc, bool FD, bool isInternal) : ObjCContainerDecl(ObjCInterface, DC, atLoc, Id), TypeForDecl(0), SuperClass(0), CategoryList(0), ForwardDecl(FD), InternalInterface(isInternal), ClassLoc(CLoc) { } void ObjCInterfaceDecl::Destroy(ASTContext &C) { for (ivar_iterator I = ivar_begin(), E = ivar_end(); I != E; ++I) if (*I) (*I)->Destroy(C); IVars.Destroy(C); // FIXME: CategoryList? // FIXME: Because there is no clear ownership // role between ObjCInterfaceDecls and the ObjCPropertyDecls that they // reference, we destroy ObjCPropertyDecls in ~TranslationUnit. Decl::Destroy(C); } /// FindCategoryDeclaration - Finds category declaration in the list of /// categories for this class and returns it. Name of the category is passed /// in 'CategoryId'. If category not found, return 0; /// ObjCCategoryDecl * ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const { for (ObjCCategoryDecl *Category = getCategoryList(); Category; Category = Category->getNextClassCategory()) if (Category->getIdentifier() == CategoryId) return Category; return 0; } /// lookupFieldDeclForIvar - looks up a field decl' in the laid out /// storage which matches this 'ivar'. /// FieldDecl *ObjCInterfaceDecl::lookupFieldDeclForIvar(ASTContext &Context, const ObjCIvarDecl *IVar) { const RecordDecl *RecordForDecl = Context.addRecordToClass(this); assert(RecordForDecl && "lookupFieldDeclForIvar no storage for class"); DeclContext::lookup_const_result Lookup = RecordForDecl->lookup(Context, IVar->getDeclName()); assert((Lookup.first != Lookup.second) && "field decl not found"); return cast<FieldDecl>(*Lookup.first); } //===----------------------------------------------------------------------===// // ObjCIvarDecl //===----------------------------------------------------------------------===// ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, AccessControl ac, Expr *BW) { return new (C) ObjCIvarDecl(DC, L, Id, T, ac, BW); } //===----------------------------------------------------------------------===// // ObjCAtDefsFieldDecl //===----------------------------------------------------------------------===// ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *BW) { return new (C) ObjCAtDefsFieldDecl(DC, L, Id, T, BW); } void ObjCAtDefsFieldDecl::Destroy(ASTContext& C) { this->~ObjCAtDefsFieldDecl(); C.Deallocate((void *)this); } //===----------------------------------------------------------------------===// // ObjCProtocolDecl //===----------------------------------------------------------------------===// ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id) { return new (C) ObjCProtocolDecl(DC, L, Id); } void ObjCProtocolDecl::Destroy(ASTContext &C) { ReferencedProtocols.Destroy(C); ObjCContainerDecl::Destroy(C); } ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) { ObjCProtocolDecl *PDecl = this; if (Name == getIdentifier()) return PDecl; for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I) if ((PDecl = (*I)->lookupProtocolNamed(Name))) return PDecl; return NULL; } // lookupInstanceMethod - Lookup a instance method in the protocol and protocols // it inherited. ObjCMethodDecl *ObjCProtocolDecl::lookupInstanceMethod(ASTContext &Context, Selector Sel) { ObjCMethodDecl *MethodDecl = NULL; if ((MethodDecl = getInstanceMethod(Context, Sel))) return MethodDecl; for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I) if ((MethodDecl = (*I)->lookupInstanceMethod(Context, Sel))) return MethodDecl; return NULL; } // lookupInstanceMethod - Lookup a class method in the protocol and protocols // it inherited. ObjCMethodDecl *ObjCProtocolDecl::lookupClassMethod(ASTContext &Context, Selector Sel) { ObjCMethodDecl *MethodDecl = NULL; if ((MethodDecl = getClassMethod(Context, Sel))) return MethodDecl; for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I) if ((MethodDecl = (*I)->lookupClassMethod(Context, Sel))) return MethodDecl; return NULL; } //===----------------------------------------------------------------------===// // ObjCClassDecl //===----------------------------------------------------------------------===// ObjCClassDecl::ObjCClassDecl(DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *const *Elts, unsigned nElts, ASTContext &C) : Decl(ObjCClass, DC, L) { ForwardDecls.set(Elts, nElts, C); } ObjCClassDecl *ObjCClassDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *const *Elts, unsigned nElts) { return new (C) ObjCClassDecl(DC, L, Elts, nElts, C); } void ObjCClassDecl::Destroy(ASTContext &C) { // FIXME: There is no clear ownership policy now for referenced // ObjCInterfaceDecls. Some of them can be forward declarations that // are never later defined (in which case the ObjCClassDecl owns them) // or the ObjCInterfaceDecl later becomes a real definition later. Ideally // we should have separate objects for forward declarations and definitions, // obviating this problem. Because of this situation, referenced // ObjCInterfaceDecls are destroyed in ~TranslationUnit. ForwardDecls.Destroy(C); Decl::Destroy(C); } //===----------------------------------------------------------------------===// // ObjCForwardProtocolDecl //===----------------------------------------------------------------------===// ObjCForwardProtocolDecl:: ObjCForwardProtocolDecl(DeclContext *DC, SourceLocation L, ObjCProtocolDecl *const *Elts, unsigned nElts, ASTContext &C) : Decl(ObjCForwardProtocol, DC, L) { ReferencedProtocols.set(Elts, nElts, C); } ObjCForwardProtocolDecl * ObjCForwardProtocolDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, ObjCProtocolDecl *const *Elts, unsigned NumElts) { return new (C) ObjCForwardProtocolDecl(DC, L, Elts, NumElts, C); } void ObjCForwardProtocolDecl::Destroy(ASTContext &C) { ReferencedProtocols.Destroy(C); Decl::Destroy(C); } //===----------------------------------------------------------------------===// // ObjCCategoryDecl //===----------------------------------------------------------------------===// ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id) { return new (C) ObjCCategoryDecl(DC, L, Id); } //===----------------------------------------------------------------------===// // ObjCCategoryImplDecl //===----------------------------------------------------------------------===// ObjCCategoryImplDecl * ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,IdentifierInfo *Id, ObjCInterfaceDecl *ClassInterface) { return new (C) ObjCCategoryImplDecl(DC, L, Id, ClassInterface); } /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of /// properties implemented in this category @implementation block and returns /// the implemented property that uses it. /// ObjCPropertyImplDecl *ObjCImplDecl:: FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const { for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){ ObjCPropertyImplDecl *PID = *i; if (PID->getPropertyIvarDecl() && PID->getPropertyIvarDecl()->getIdentifier() == ivarId) return PID; } return 0; } /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl /// added to the list of those properties @synthesized/@dynamic in this /// category @implementation block. /// ObjCPropertyImplDecl *ObjCImplDecl:: FindPropertyImplDecl(IdentifierInfo *Id) const { for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){ ObjCPropertyImplDecl *PID = *i; if (PID->getPropertyDecl()->getIdentifier() == Id) return PID; } return 0; } // getInstanceMethod - This method returns an instance method by looking in // the class implementation. Unlike interfaces, we don't look outside the // implementation. ObjCMethodDecl *ObjCImplDecl::getInstanceMethod(Selector Sel) const { for (instmeth_iterator I = instmeth_begin(), E = instmeth_end(); I != E; ++I) if ((*I)->getSelector() == Sel) return *I; return NULL; } // getClassMethod - This method returns an instance method by looking in // the class implementation. Unlike interfaces, we don't look outside the // implementation. ObjCMethodDecl *ObjCImplDecl::getClassMethod(Selector Sel) const { for (classmeth_iterator I = classmeth_begin(), E = classmeth_end(); I != E; ++I) if ((*I)->getSelector() == Sel) return *I; return NULL; } //===----------------------------------------------------------------------===// // ObjCImplementationDecl //===----------------------------------------------------------------------===// ObjCImplementationDecl * ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, ObjCInterfaceDecl *ClassInterface, ObjCInterfaceDecl *SuperDecl) { return new (C) ObjCImplementationDecl(DC, L, ClassInterface, SuperDecl); } /// Destroy - Call destructors and release memory. void ObjCImplementationDecl::Destroy(ASTContext &C) { IVars.Destroy(C); Decl::Destroy(C); } //===----------------------------------------------------------------------===// // ObjCCompatibleAliasDecl //===----------------------------------------------------------------------===// ObjCCompatibleAliasDecl * ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, ObjCInterfaceDecl* AliasedClass) { return new (C) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass); } //===----------------------------------------------------------------------===// // ObjCPropertyDecl //===----------------------------------------------------------------------===// ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, PropertyControl propControl) { return new (C) ObjCPropertyDecl(DC, L, Id, T); } //===----------------------------------------------------------------------===// // ObjCPropertyImplDecl //===----------------------------------------------------------------------===// ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation atLoc, SourceLocation L, ObjCPropertyDecl *property, Kind PK, ObjCIvarDecl *ivar) { return new (C) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar); } <file_sep>/test/CodeGen/2008-02-08-bitfield-bug.c // RUN: clang-cc %s -emit-llvm -o %t struct test { unsigned a:1; unsigned b:1; }; struct test *t; <file_sep>/test/CodeGen/cleanup-stack.c // RUN: clang-cc -emit-llvm %s -o %t && // RUN: grep "store i32 0, i32\* %cleanup" %t | count 2 void f(int n) { int a[n]; { int b[n]; if (n) return; } if (n) return; } <file_sep>/include/clang/Frontend/PathDiagnosticClients.h //===--- PathDiagnosticClients.h - Path Diagnostic Clients ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface to create different path diagostic clients. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_PATH_DIAGNOSTIC_CLIENTS_H #define LLVM_CLANG_FRONTEND_PATH_DIAGNOSTIC_CLiENTS_H #include <string> namespace clang { class PathDiagnosticClient; class Preprocessor; class PreprocessorFactory; PathDiagnosticClient* CreateHTMLDiagnosticClient(const std::string& prefix, Preprocessor* PP, PreprocessorFactory* PPF); PathDiagnosticClient* CreatePlistDiagnosticClient(const std::string& prefix, Preprocessor* PP, PreprocessorFactory* PPF); } #endif <file_sep>/lib/CodeGen/CGDebugInfo.cpp //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This coordinates the debug information generation while generating code. // //===----------------------------------------------------------------------===// #include "CGDebugInfo.h" #include "CodeGenModule.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Expr.h" #include "clang/AST/RecordLayout.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/FileManager.h" #include "clang/Frontend/CompileOptions.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Module.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Dwarf.h" #include "llvm/Target/TargetMachine.h" using namespace clang; using namespace clang::CodeGen; CGDebugInfo::CGDebugInfo(CodeGenModule *m) : M(m), DebugFactory(M->getModule()) { } CGDebugInfo::~CGDebugInfo() { assert(RegionStack.empty() && "Region stack mismatch, stack not empty!"); } void CGDebugInfo::setLocation(SourceLocation Loc) { if (Loc.isValid()) CurLoc = M->getContext().getSourceManager().getInstantiationLoc(Loc); } /// getOrCreateCompileUnit - Get the compile unit from the cache or create a new /// one if necessary. This returns null for invalid source locations. llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) { // FIXME: Until we do a complete job of emitting debug information, // we need to support making dummy compile units so that we generate // "well formed" debug info. const FileEntry *FE = 0; SourceManager &SM = M->getContext().getSourceManager(); bool isMain; if (Loc.isValid()) { Loc = SM.getInstantiationLoc(Loc); FE = SM.getFileEntryForID(SM.getFileID(Loc)); isMain = SM.getFileID(Loc) == SM.getMainFileID(); } else { // If Loc is not valid then use main file id. FE = SM.getFileEntryForID(SM.getMainFileID()); isMain = true; } // See if this compile unit has been used before. llvm::DICompileUnit &Unit = CompileUnitCache[FE]; if (!Unit.isNull()) return Unit; // Get source file information. const char *FileName = FE ? FE->getName() : "<unknown>"; const char *DirName = FE ? FE->getDir()->getName() : "<unknown>"; const LangOptions &LO = M->getLangOptions(); // If this is the main file, use the user provided main file name if // specified. if (isMain && LO.getMainFileName()) FileName = LO.getMainFileName(); unsigned LangTag; if (LO.CPlusPlus) { if (LO.ObjC1) LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; else LangTag = llvm::dwarf::DW_LANG_C_plus_plus; } else if (LO.ObjC1) { LangTag = llvm::dwarf::DW_LANG_ObjC; } else if (LO.C99) { LangTag = llvm::dwarf::DW_LANG_C99; } else { LangTag = llvm::dwarf::DW_LANG_C89; } // Create new compile unit. // FIXME: Do not know how to get clang version yet. // FIXME: Encode command line options. // FIXME: Encode optimization level. return Unit = DebugFactory.CreateCompileUnit(LangTag, FileName, DirName, "clang", isMain); } /// CreateType - Get the Basic type from the cache or create a new /// one if necessary. llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT, llvm::DICompileUnit Unit) { unsigned Encoding = 0; switch (BT->getKind()) { default: case BuiltinType::Void: return llvm::DIType(); case BuiltinType::UChar: case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break; case BuiltinType::Char_S: case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break; case BuiltinType::UShort: case BuiltinType::UInt: case BuiltinType::ULong: case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break; case BuiltinType::Short: case BuiltinType::Int: case BuiltinType::Long: case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break; case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break; case BuiltinType::Float: case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break; } // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(BT); uint64_t Align = M->getContext().getTypeAlign(BT); uint64_t Offset = 0; return DebugFactory.CreateBasicType(Unit, BT->getName(), Unit, 0, Size, Align, Offset, /*flags*/ 0, Encoding); } /// getOrCreateCVRType - Get the CVR qualified type from the cache or create /// a new one if necessary. llvm::DIType CGDebugInfo::CreateCVRType(QualType Ty, llvm::DICompileUnit Unit) { // We will create one Derived type for one qualifier and recurse to handle any // additional ones. llvm::DIType FromTy; unsigned Tag; if (Ty.isConstQualified()) { Tag = llvm::dwarf::DW_TAG_const_type; Ty.removeConst(); FromTy = getOrCreateType(Ty, Unit); } else if (Ty.isVolatileQualified()) { Tag = llvm::dwarf::DW_TAG_volatile_type; Ty.removeVolatile(); FromTy = getOrCreateType(Ty, Unit); } else { assert(Ty.isRestrictQualified() && "Unknown type qualifier for debug info"); Tag = llvm::dwarf::DW_TAG_restrict_type; Ty.removeRestrict(); FromTy = getOrCreateType(Ty, Unit); } // No need to fill in the Name, Line, Size, Alignment, Offset in case of // CVR derived types. return DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(), 0, 0, 0, 0, 0, FromTy); } llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty, llvm::DICompileUnit Unit) { llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit); // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit, "", llvm::DICompileUnit(), 0, Size, Align, 0, 0, EltTy); } llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DICompileUnit Unit) { // Typedefs are derived from some other type. If we have a typedef of a // typedef, make sure to emit the whole chain. llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit); // We don't set size information, but do specify where the typedef was // declared. std::string TyName = Ty->getDecl()->getNameAsString(); SourceLocation DefLoc = Ty->getDecl()->getLocation(); llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc); SourceManager &SM = M->getContext().getSourceManager(); uint64_t Line = SM.getInstantiationLineNumber(DefLoc); return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, Unit, TyName, DefUnit, Line, 0, 0, 0, 0, Src); } llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty, llvm::DICompileUnit Unit) { llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; // Add the result type at least. EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit)); // Set up remainder of arguments if there is a prototype. // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'! if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) { for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i) EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit)); } else { // FIXME: Handle () case in C. llvm-gcc doesn't do it either. } llvm::DIArray EltTypeArray = DebugFactory.GetOrCreateArray(&EltTys[0], EltTys.size()); return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type, Unit, "", llvm::DICompileUnit(), 0, 0, 0, 0, 0, llvm::DIType(), EltTypeArray); } /// CreateType - get structure or union type. llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, llvm::DICompileUnit Unit) { RecordDecl *Decl = Ty->getDecl(); unsigned Tag; if (Decl->isStruct()) Tag = llvm::dwarf::DW_TAG_structure_type; else if (Decl->isUnion()) Tag = llvm::dwarf::DW_TAG_union_type; else { assert(Decl->isClass() && "Unknown RecordType!"); Tag = llvm::dwarf::DW_TAG_class_type; } SourceManager &SM = M->getContext().getSourceManager(); // Get overall information about the record type for the debug info. std::string Name = Decl->getNameAsString(); llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation()); unsigned Line = SM.getInstantiationLineNumber(Decl->getLocation()); // Records and classes and unions can all be recursive. To handle them, we // first generate a debug descriptor for the struct as a forward declaration. // Then (if it is a definition) we go through and get debug info for all of // its members. Finally, we create a descriptor for the complete type (which // may refer to the forward decl if the struct is recursive) and replace all // uses of the forward declaration with the final definition. llvm::DIType FwdDecl = DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0, llvm::DIType(), llvm::DIArray()); // If this is just a forward declaration, return it. if (!Decl->getDefinition(M->getContext())) return FwdDecl; // Otherwise, insert it into the TypeCache so that recursive uses will find // it. TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; // Convert all the elements. llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; const ASTRecordLayout &RL = M->getContext().getASTRecordLayout(Decl); unsigned FieldNo = 0; for (RecordDecl::field_iterator I = Decl->field_begin(M->getContext()), E = Decl->field_end(M->getContext()); I != E; ++I, ++FieldNo) { FieldDecl *Field = *I; llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); std::string FieldName = Field->getNameAsString(); // Get the location for the field. SourceLocation FieldDefLoc = Field->getLocation(); llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc); unsigned FieldLine = SM.getInstantiationLineNumber(FieldDefLoc); QualType FType = Field->getType(); uint64_t FieldSize = 0; unsigned FieldAlign = 0; if (!FType->isIncompleteArrayType()) { // Bit size, align and offset of the type. FieldSize = M->getContext().getTypeSize(FType); Expr *BitWidth = Field->getBitWidth(); if (BitWidth) FieldSize = BitWidth->getIntegerConstantExprValue(M->getContext()).getZExtValue(); FieldAlign = M->getContext().getTypeAlign(FType); } uint64_t FieldOffset = RL.getFieldOffset(FieldNo); // Create a DW_TAG_member node to remember the offset of this field in the // struct. FIXME: This is an absolutely insane way to capture this // information. When we gut debug info, this should be fixed. FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, FieldName, FieldDefUnit, FieldLine, FieldSize, FieldAlign, FieldOffset, 0, FieldTy); EltTys.push_back(FieldTy); } llvm::DIArray Elements = DebugFactory.GetOrCreateArray(&EltTys[0], EltTys.size()); // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); llvm::DIType RealDecl = DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size, Align, 0, 0, llvm::DIType(), Elements); // Now that we have a real decl for the struct, replace anything using the // old decl with the new one. This will recursively update the debug info. FwdDecl.getGV()->replaceAllUsesWith(RealDecl.getGV()); FwdDecl.getGV()->eraseFromParent(); return RealDecl; } /// CreateType - get objective-c interface type. llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, llvm::DICompileUnit Unit) { ObjCInterfaceDecl *Decl = Ty->getDecl(); unsigned Tag = llvm::dwarf::DW_TAG_structure_type; SourceManager &SM = M->getContext().getSourceManager(); // Get overall information about the record type for the debug info. std::string Name = Decl->getNameAsString(); llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation()); unsigned Line = SM.getInstantiationLineNumber(Decl->getLocation()); // To handle recursive interface, we // first generate a debug descriptor for the struct as a forward declaration. // Then (if it is a definition) we go through and get debug info for all of // its members. Finally, we create a descriptor for the complete type (which // may refer to the forward decl if the struct is recursive) and replace all // uses of the forward declaration with the final definition. llvm::DIType FwdDecl = DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0, llvm::DIType(), llvm::DIArray()); // If this is just a forward declaration, return it. if (Decl->isForwardDecl()) return FwdDecl; // Otherwise, insert it into the TypeCache so that recursive uses will find // it. TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl; // Convert all the elements. llvm::SmallVector<llvm::DIDescriptor, 16> EltTys; ObjCInterfaceDecl *SClass = Decl->getSuperClass(); if (SClass) { llvm::DIType SClassTy = getOrCreateType(M->getContext().getObjCInterfaceType(SClass), Unit); llvm::DIType InhTag = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance, Unit, "", Unit, 0, 0, 0, 0 /* offset */, 0, SClassTy); EltTys.push_back(InhTag); } const ASTRecordLayout &RL = M->getContext().getASTObjCInterfaceLayout(Decl); unsigned FieldNo = 0; for (ObjCInterfaceDecl::ivar_iterator I = Decl->ivar_begin(), E = Decl->ivar_end(); I != E; ++I, ++FieldNo) { ObjCIvarDecl *Field = *I; llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit); std::string FieldName = Field->getNameAsString(); // Get the location for the field. SourceLocation FieldDefLoc = Field->getLocation(); llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc); unsigned FieldLine = SM.getInstantiationLineNumber(FieldDefLoc); QualType FType = Field->getType(); uint64_t FieldSize = 0; unsigned FieldAlign = 0; if (!FType->isIncompleteArrayType()) { // Bit size, align and offset of the type. FieldSize = M->getContext().getTypeSize(FType); Expr *BitWidth = Field->getBitWidth(); if (BitWidth) FieldSize = BitWidth->getIntegerConstantExprValue(M->getContext()).getZExtValue(); FieldAlign = M->getContext().getTypeAlign(FType); } uint64_t FieldOffset = RL.getFieldOffset(FieldNo); unsigned Flags = 0; if (Field->getAccessControl() == ObjCIvarDecl::Protected) Flags = llvm::DIType::FlagProtected; else if (Field->getAccessControl() == ObjCIvarDecl::Private) Flags = llvm::DIType::FlagPrivate; // Create a DW_TAG_member node to remember the offset of this field in the // struct. FIXME: This is an absolutely insane way to capture this // information. When we gut debug info, this should be fixed. FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit, FieldName, FieldDefUnit, FieldLine, FieldSize, FieldAlign, FieldOffset, Flags, FieldTy); EltTys.push_back(FieldTy); } llvm::DIArray Elements = DebugFactory.GetOrCreateArray(&EltTys[0], EltTys.size()); // Bit size, align and offset of the type. uint64_t Size = M->getContext().getTypeSize(Ty); uint64_t Align = M->getContext().getTypeAlign(Ty); llvm::DIType RealDecl = DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size, Align, 0, 0, llvm::DIType(), Elements); // Now that we have a real decl for the struct, replace anything using the // old decl with the new one. This will recursively update the debug info. FwdDecl.getGV()->replaceAllUsesWith(RealDecl.getGV()); FwdDecl.getGV()->eraseFromParent(); return RealDecl; } llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty, llvm::DICompileUnit Unit) { EnumDecl *Decl = Ty->getDecl(); llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators; // Create DIEnumerator elements for each enumerator. for (EnumDecl::enumerator_iterator Enum = Decl->enumerator_begin(M->getContext()), EnumEnd = Decl->enumerator_end(M->getContext()); Enum != EnumEnd; ++Enum) { Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getNameAsString(), Enum->getInitVal().getZExtValue())); } // Return a CompositeType for the enum itself. llvm::DIArray EltArray = DebugFactory.GetOrCreateArray(&Enumerators[0], Enumerators.size()); std::string EnumName = Decl->getNameAsString(); SourceLocation DefLoc = Decl->getLocation(); llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc); SourceManager &SM = M->getContext().getSourceManager(); unsigned Line = SM.getInstantiationLineNumber(DefLoc); // Size and align of the type. uint64_t Size = M->getContext().getTypeSize(Ty); unsigned Align = M->getContext().getTypeAlign(Ty); return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type, Unit, EnumName, DefUnit, Line, Size, Align, 0, 0, llvm::DIType(), EltArray); } llvm::DIType CGDebugInfo::CreateType(const TagType *Ty, llvm::DICompileUnit Unit) { if (const RecordType *RT = dyn_cast<RecordType>(Ty)) return CreateType(RT, Unit); else if (const EnumType *ET = dyn_cast<EnumType>(Ty)) return CreateType(ET, Unit); return llvm::DIType(); } llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DICompileUnit Unit) { uint64_t Size; uint64_t Align; // FIXME: make getTypeAlign() aware of VLAs and incomplete array types if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) { Size = 0; Align = M->getContext().getTypeAlign(M->getContext().getBaseElementType(VAT)); } else if (Ty->isIncompleteArrayType()) { Size = 0; Align = M->getContext().getTypeAlign(Ty->getElementType()); } else { // Size and align of the whole array, not the element type. Size = M->getContext().getTypeSize(Ty); Align = M->getContext().getTypeAlign(Ty); } // Add the dimensions of the array. FIXME: This loses CV qualifiers from // interior arrays, do we care? Why aren't nested arrays represented the // obvious/recursive way? llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts; QualType EltTy(Ty, 0); while ((Ty = dyn_cast<ArrayType>(EltTy))) { uint64_t Upper = 0; if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) Upper = CAT->getSize().getZExtValue() - 1; // FIXME: Verify this is right for VLAs. Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper)); EltTy = Ty->getElementType(); } llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(&Subscripts[0], Subscripts.size()); return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type, Unit, "", llvm::DICompileUnit(), 0, Size, Align, 0, 0, getOrCreateType(EltTy, Unit), SubscriptArray); } /// getOrCreateType - Get the type from the cache or create a new /// one if necessary. llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DICompileUnit Unit) { if (Ty.isNull()) return llvm::DIType(); // Check to see if the compile unit already has created this type. llvm::DIType &Slot = TypeCache[Ty.getAsOpaquePtr()]; if (!Slot.isNull()) return Slot; // Handle CVR qualifiers, which recursively handles what they refer to. if (Ty.getCVRQualifiers()) return Slot = CreateCVRType(Ty, Unit); // Work out details of type. switch (Ty->getTypeClass()) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) #define NON_CANONICAL_TYPE(Class, Base) #define DEPENDENT_TYPE(Class, Base) case Type::Class: #include "clang/AST/TypeNodes.def" assert(false && "Dependent types cannot show up in debug information"); case Type::Complex: case Type::LValueReference: case Type::RValueReference: case Type::Vector: case Type::ExtVector: case Type::ExtQual: case Type::ObjCQualifiedInterface: case Type::ObjCQualifiedId: case Type::FixedWidthInt: case Type::BlockPointer: case Type::MemberPointer: case Type::TemplateSpecialization: case Type::QualifiedName: case Type::ObjCQualifiedClass: // Unsupported types return llvm::DIType(); case Type::ObjCInterface: Slot = CreateType(cast<ObjCInterfaceType>(Ty), Unit); break; case Type::Builtin: Slot = CreateType(cast<BuiltinType>(Ty), Unit); break; case Type::Pointer: Slot = CreateType(cast<PointerType>(Ty), Unit); break; case Type::Typedef: Slot = CreateType(cast<TypedefType>(Ty), Unit); break; case Type::Record: case Type::Enum: Slot = CreateType(cast<TagType>(Ty), Unit); break; case Type::FunctionProto: case Type::FunctionNoProto: return Slot = CreateType(cast<FunctionType>(Ty), Unit); case Type::ConstantArray: case Type::VariableArray: case Type::IncompleteArray: return Slot = CreateType(cast<ArrayType>(Ty), Unit); case Type::TypeOfExpr: return Slot = getOrCreateType(cast<TypeOfExprType>(Ty)->getUnderlyingExpr() ->getType(), Unit); case Type::TypeOf: return Slot = getOrCreateType(cast<TypeOfType>(Ty)->getUnderlyingType(), Unit); } return Slot; } /// EmitFunctionStart - Constructs the debug code for entering a function - /// "llvm.dbg.func.start.". void CGDebugInfo::EmitFunctionStart(const char *Name, QualType ReturnType, llvm::Function *Fn, CGBuilderTy &Builder) { // FIXME: Why is this using CurLoc??? llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc); SourceManager &SM = M->getContext().getSourceManager(); unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine(); llvm::DISubprogram SP = DebugFactory.CreateSubprogram(Unit, Name, Name, "", Unit, LineNo, getOrCreateType(ReturnType, Unit), Fn->hasInternalLinkage(), true/*definition*/); DebugFactory.InsertSubprogramStart(SP, Builder.GetInsertBlock()); // Push function on region stack. RegionStack.push_back(SP); } void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) { if (CurLoc.isInvalid() || CurLoc.isMacroID()) return; // Don't bother if things are the same as last time. SourceManager &SM = M->getContext().getSourceManager(); if (CurLoc == PrevLoc || (SM.getInstantiationLineNumber(CurLoc) == SM.getInstantiationLineNumber(PrevLoc) && SM.isFromSameFile(CurLoc, PrevLoc))) return; // Update last state. PrevLoc = CurLoc; // Get the appropriate compile unit. llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc); PresumedLoc PLoc = SM.getPresumedLoc(CurLoc); DebugFactory.InsertStopPoint(Unit, PLoc.getLine(), PLoc.getColumn(), Builder.GetInsertBlock()); } /// EmitRegionStart- Constructs the debug code for entering a declarative /// region - "llvm.dbg.region.start.". void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) { llvm::DIDescriptor D; if (!RegionStack.empty()) D = RegionStack.back(); D = DebugFactory.CreateBlock(D); RegionStack.push_back(D); DebugFactory.InsertRegionStart(D, Builder.GetInsertBlock()); } /// EmitRegionEnd - Constructs the debug code for exiting a declarative /// region - "llvm.dbg.region.end." void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) { assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); // Provide an region stop point. EmitStopPoint(Fn, Builder); DebugFactory.InsertRegionEnd(RegionStack.back(), Builder.GetInsertBlock()); RegionStack.pop_back(); } /// EmitDeclare - Emit local variable declaration debug info. void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag, llvm::Value *Storage, CGBuilderTy &Builder) { assert(!RegionStack.empty() && "Region stack mismatch, stack empty!"); // Do not emit variable debug information while generating optimized code. // The llvm optimizer and code generator are not yet ready to support // optimized code debugging. const CompileOptions &CO = M->getCompileOpts(); if (CO.OptimizationLevel) return; // Get location information. SourceManager &SM = M->getContext().getSourceManager(); unsigned Line = SM.getInstantiationLineNumber(Decl->getLocation()); llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation()); // Create the descriptor for the variable. llvm::DIVariable D = DebugFactory.CreateVariable(Tag, RegionStack.back(),Decl->getNameAsString(), Unit, Line, getOrCreateType(Decl->getType(), Unit)); // Insert an llvm.dbg.declare into the current block. DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock()); } void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *Storage, CGBuilderTy &Builder) { EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder); } /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument /// variable declaration. void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder) { EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder); } /// EmitGlobalVariable - Emit information about a global variable. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, const VarDecl *Decl) { // Do not emit variable debug information while generating optimized code. // The llvm optimizer and code generator are not yet ready to support // optimized code debugging. const CompileOptions &CO = M->getCompileOpts(); if (CO.OptimizationLevel) return; // Create global variable debug descriptor. llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation()); SourceManager &SM = M->getContext().getSourceManager(); unsigned LineNo = SM.getInstantiationLineNumber(Decl->getLocation()); std::string Name = Decl->getNameAsString(); QualType T = Decl->getType(); if (T->isIncompleteArrayType()) { // CodeGen turns int[] into int[1] so we'll do the same here. llvm::APSInt ConstVal(32); ConstVal = 1; QualType ET = M->getContext().getAsArrayType(T)->getElementType(); T = M->getContext().getConstantArrayType(ET, ConstVal, ArrayType::Normal, 0); } DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo, getOrCreateType(T, Unit), Var->hasInternalLinkage(), true/*definition*/, Var); } /// EmitGlobalVariable - Emit information about an objective-c interface. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, ObjCInterfaceDecl *Decl) { // Create global variable debug descriptor. llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation()); SourceManager &SM = M->getContext().getSourceManager(); unsigned LineNo = SM.getInstantiationLineNumber(Decl->getLocation()); std::string Name = Decl->getNameAsString(); QualType T = M->getContext().getObjCInterfaceType(Decl); if (T->isIncompleteArrayType()) { // CodeGen turns int[] into int[1] so we'll do the same here. llvm::APSInt ConstVal(32); ConstVal = 1; QualType ET = M->getContext().getAsArrayType(T)->getElementType(); T = M->getContext().getConstantArrayType(ET, ConstVal, ArrayType::Normal, 0); } DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo, getOrCreateType(T, Unit), Var->hasInternalLinkage(), true/*definition*/, Var); } <file_sep>/test/Frontend/darwin-version.c // RUN: clang-cc -triple armv6-apple-darwin9 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | grep '10000' | count 1 && // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | count 0 && // RUN: clang-cc -triple armv6-apple-darwin9 -miphoneos-version-min=2.0 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | grep '20000' | count 1 && // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | count 0 && // RUN: clang-cc -triple armv6-apple-darwin9 -miphoneos-version-min=2.2 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | grep '20200' | count 1 && // RUN: clang-cc -triple i686-apple-darwin8 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | count 0 && // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1040' | count 1 && // RUN: clang-cc -triple i686-apple-darwin9 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1050' | count 1 && // RUN: clang-cc -triple i686-apple-darwin10 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1060' | count 1 && // RUN: clang-cc -triple i686-apple-darwin9 -mmacosx-version-min=10.4 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | count 0 && // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1040' | count 1 && // RUN: clang-cc -triple i686-apple-darwin9 -mmacosx-version-min=10.5 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1050' | count 1 && // RUN: clang-cc -triple i686-apple-darwin9 -mmacosx-version-min=10.6 -dM -E -o %t - < /dev/null && // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1060' | count 1 && // RUN: true <file_sep>/test/CodeGen/init-with-member-expr.c // RUN: clang-cc < %s -emit-llvm struct test { int a; }; extern struct test t; int *b=&t.a; // PR2049 typedef struct mark_header_tag { unsigned char mark[7]; } mark_header_t; int is_rar_archive(int fd) { const mark_header_t rar_hdr[2] = {{0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00}, {'U', 'n', 'i', 'q', 'u', 'E', '!'}}; foo(rar_hdr); return 0; } <file_sep>/test/SemaTemplate/instantiate-expr-1.cpp // RUN: clang-cc -fsyntax-only -verify %s template<int I, int J> struct Bitfields { int simple : I; // expected-error{{bit-field 'simple' has zero width}} int parens : (J); }; void test_Bitfields(Bitfields<0, 5> *b) { (void)sizeof(Bitfields<10, 5>); (void)sizeof(Bitfields<0, 1>); // expected-note{{in instantiation of template class 'struct Bitfields<0, 1>' requested here}} } template<int I, int J> struct BitfieldPlus { int bitfield : I + J; // expected-error{{bit-field 'bitfield' has zero width}} }; void test_BitfieldPlus() { (void)sizeof(BitfieldPlus<0, 1>); (void)sizeof(BitfieldPlus<-5, 5>); // expected-note{{in instantiation of template class 'struct BitfieldPlus<-5, 5>' requested here}} } template<int I, int J> struct BitfieldMinus { int bitfield : I - J; // expected-error{{bit-field 'bitfield' has negative width (-1)}} \ // expected-error{{bit-field 'bitfield' has zero width}} }; void test_BitfieldMinus() { (void)sizeof(BitfieldMinus<5, 1>); (void)sizeof(BitfieldMinus<0, 1>); // expected-note{{in instantiation of template class 'struct BitfieldMinus<0, 1>' requested here}} (void)sizeof(BitfieldMinus<5, 5>); // expected-note{{in instantiation of template class 'struct BitfieldMinus<5, 5>' requested here}} } template<int I, int J> struct BitfieldDivide { int bitfield : I / J; // expected-error{{expression is not an integer constant expression}} \ // expected-note{{division by zero}} }; void test_BitfieldDivide() { (void)sizeof(BitfieldDivide<5, 1>); (void)sizeof(BitfieldDivide<5, 0>); // expected-note{{in instantiation of template class 'struct BitfieldDivide<5, 0>' requested here}} } template<typename T, T I, int J> struct BitfieldDep { int bitfield : I + J; }; void test_BitfieldDep() { (void)sizeof(BitfieldDep<int, 1, 5>); } template<int I> struct BitfieldNeg { int bitfield : (-I); // expected-error{{bit-field 'bitfield' has negative width (-5)}} }; template<typename T, T I> struct BitfieldNeg2 { int bitfield : (-I); // expected-error{{bit-field 'bitfield' has negative width (-5)}} }; void test_BitfieldNeg() { (void)sizeof(BitfieldNeg<-5>); // okay (void)sizeof(BitfieldNeg<5>); // expected-note{{in instantiation of template class 'struct BitfieldNeg<5>' requested here}} (void)sizeof(BitfieldNeg2<int, -5>); // okay (void)sizeof(BitfieldNeg2<int, 5>); // expected-note{{in instantiation of template class 'struct BitfieldNeg2<int, 5>' requested here}} } <file_sep>/test/SemaCXX/destructor.cpp // RUN: clang-cc -fsyntax-only -verify %s class A { public: ~A(); }; class B { public: ~B() { } }; class C { public: (~C)() { } }; struct D { static void ~D(int, ...) const { } // \ // expected-error{{type qualifier is not allowed on this function}} \ // expected-error{{destructor cannot be declared 'static'}} \ // expected-error{{destructor cannot have a return type}} \ // expected-error{{destructor cannot have any parameters}} \ // expected-error{{destructor cannot be variadic}} }; struct E; typedef E E_typedef; struct E { ~E_typedef(); // expected-error{{destructor cannot be declared using a typedef 'E_typedef' (aka 'struct E') of the class name}} }; struct F { (~F)(); // expected-note {{previous declaration is here}} ~F(); // expected-error {{destructor cannot be redeclared}} }; ~; // expected-error {{expected class name}} ~undef(); // expected-error {{expected class name}} ~F(){} // expected-error {{destructor must be a non-static member function}} struct G { ~G(); }; G::~G() { } <file_sep>/test/CodeGen/builtin-memfns.c // RUN: clang-cc -arch i386 -emit-llvm -o %t %s && // RUN: grep '@llvm.memset.i32' %t && // RUN: grep '@llvm.memcpy.i32' %t && // RUN: grep '@llvm.memmove.i32' %t && // RUN: grep __builtin %t | count 0 int main(int argc, char **argv) { unsigned char a = 0x11223344; unsigned char b = 0x11223344; __builtin_bzero(&a, sizeof(a)); __builtin_memset(&a, 0, sizeof(a)); __builtin_memcpy(&a, &b, sizeof(a)); __builtin_memmove(&a, &b, sizeof(a)); return 0; } <file_sep>/include/clang/Driver/ArgList.h //===--- ArgList.h - Argument List Management ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef CLANG_DRIVER_ARGLIST_H_ #define CLANG_DRIVER_ARGLIST_H_ #include "clang/Driver/Options.h" #include "clang/Driver/Util.h" #include "llvm/ADT/SmallVector.h" #include <list> namespace clang { namespace driver { class Arg; /// ArgList - Ordered collection of driver arguments. /// /// The ArgList class manages a list of Arg instances as well as /// auxiliary data and convenience methods to allow Tools to quickly /// check for the presence of Arg instances for a particular Option /// and to iterate over groups of arguments. class ArgList { public: typedef llvm::SmallVector<Arg*, 16> arglist_type; typedef arglist_type::iterator iterator; typedef arglist_type::const_iterator const_iterator; typedef arglist_type::reverse_iterator reverse_iterator; typedef arglist_type::const_reverse_iterator const_reverse_iterator; private: /// The full list of arguments. arglist_type &Args; protected: ArgList(arglist_type &Args); public: virtual ~ArgList(); /// @name Arg Access /// @{ /// append - Append \arg A to the arg list. void append(Arg *A); arglist_type &getArgs() { return Args; } const arglist_type &getArgs() const { return Args; } unsigned size() const { return Args.size(); } iterator begin() { return Args.begin(); } iterator end() { return Args.end(); } reverse_iterator rbegin() { return Args.rbegin(); } reverse_iterator rend() { return Args.rend(); } const_iterator begin() const { return Args.begin(); } const_iterator end() const { return Args.end(); } const_reverse_iterator rbegin() const { return Args.rbegin(); } const_reverse_iterator rend() const { return Args.rend(); } /// hasArg - Does the arg list contain any option matching \arg Id. /// /// \arg Claim Whether the argument should be claimed, if it exists. bool hasArg(options::ID Id, bool Claim=true) const { return getLastArg(Id, Claim) != 0; } /// getLastArg - Return the last argument matching \arg Id, or null. /// /// \arg Claim Whether the argument should be claimed, if it exists. Arg *getLastArg(options::ID Id, bool Claim=true) const; Arg *getLastArg(options::ID Id0, options::ID Id1, bool Claim=true) const; /// getArgString - Return the input argument string at \arg Index. virtual const char *getArgString(unsigned Index) const = 0; /// @name Translation Utilities /// @{ /// hasFlag - Given an option \arg Pos and its negative form \arg /// Neg, return true if the option is present, false if the /// negation is present, and \arg Default if neither option is /// given. If both the option and its negation are present, the /// last one wins. bool hasFlag(options::ID Pos, options::ID Neg, bool Default=true) const; /// AddLastArg - Render only the last argument match \arg Id0, if /// present. void AddLastArg(ArgStringList &Output, options::ID Id0) const; /// AddAllArgs - Render all arguments matching the given ids. void AddAllArgs(ArgStringList &Output, options::ID Id0) const; void AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1) const; void AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1, options::ID Id2) const; /// AddAllArgValues - Render the argument values of all arguments /// matching the given ids. void AddAllArgValues(ArgStringList &Output, options::ID Id0) const; void AddAllArgValues(ArgStringList &Output, options::ID Id0, options::ID Id1) const; // AddAllArgsTranslated - Render all the arguments matching the // given ids, but forced to separate args and using the provided // name instead of the first option value. void AddAllArgsTranslated(ArgStringList &Output, options::ID Id0, const char *Translation) const; /// ClaimAllArgs - Claim all arguments which match the given /// option id. void ClaimAllArgs(options::ID Id0) const; /// @} /// @name Arg Synthesis /// @{ /// MakeArgString - Construct a constant string pointer whose /// lifetime will match that of the ArgList. virtual const char *MakeArgString(const char *Str) const = 0; /// @} }; class InputArgList : public ArgList { private: /// The internal list of arguments. arglist_type ActualArgs; /// List of argument strings used by the contained Args. /// /// This is mutable since we treat the ArgList as being the list /// of Args, and allow routines to add new strings (to have a /// convenient place to store the memory) via MakeIndex. mutable ArgStringList ArgStrings; /// Strings for synthesized arguments. /// /// This is mutable since we treat the ArgList as being the list /// of Args, and allow routines to add new strings (to have a /// convenient place to store the memory) via MakeIndex. mutable std::list<std::string> SynthesizedStrings; /// The number of original input argument strings. unsigned NumInputArgStrings; public: InputArgList(const char **ArgBegin, const char **ArgEnd); InputArgList(const ArgList &); ~InputArgList(); virtual const char *getArgString(unsigned Index) const { return ArgStrings[Index]; } /// getNumInputArgStrings - Return the number of original input /// argument strings. unsigned getNumInputArgStrings() const { return NumInputArgStrings; } /// @name Arg Synthesis /// @{ public: /// MakeIndex - Get an index for the given string(s). unsigned MakeIndex(const char *String0) const; unsigned MakeIndex(const char *String0, const char *String1) const; virtual const char *MakeArgString(const char *Str) const; /// @} }; /// DerivedArgList - An ordered collection of driver arguments, /// whose storage may be in another argument list. class DerivedArgList : public ArgList { InputArgList &BaseArgs; /// The internal list of arguments. arglist_type ActualArgs; /// The list of arguments we synthesized. arglist_type SynthesizedArgs; /// Is this only a proxy for the base ArgList? bool OnlyProxy; public: /// Construct a new derived arg list from \arg BaseArgs. /// /// \param OnlyProxy - If true, this is only a proxy for the base /// list (to adapt the type), and it's Args list is unused. DerivedArgList(InputArgList &BaseArgs, bool OnlyProxy); ~DerivedArgList(); virtual const char *getArgString(unsigned Index) const { return BaseArgs.getArgString(Index); } /// @name Arg Synthesis /// @{ virtual const char *MakeArgString(const char *Str) const; /// MakeFlagArg - Construct a new FlagArg for the given option /// \arg Id. Arg *MakeFlagArg(const Arg *BaseArg, const Option *Opt) const; /// MakePositionalArg - Construct a new Positional arg for the /// given option \arg Id, with the provided \arg Value. Arg *MakePositionalArg(const Arg *BaseArg, const Option *Opt, const char *Value) const; /// MakeSeparateArg - Construct a new Positional arg for the /// given option \arg Id, with the provided \arg Value. Arg *MakeSeparateArg(const Arg *BaseArg, const Option *Opt, const char *Value) const; /// MakeJoinedArg - Construct a new Positional arg for the /// given option \arg Id, with the provided \arg Value. Arg *MakeJoinedArg(const Arg *BaseArg, const Option *Opt, const char *Value) const; /// @} }; } // end namespace driver } // end namespace clang #endif <file_sep>/test/SemaCXX/carbon.cpp // RUN: clang-cc %s -fsyntax-only -print-stats #ifdef __APPLE__ #include <Carbon/Carbon.h> #endif <file_sep>/lib/CodeGen/Mangle.h //===--- Mangle.h - Mangle C++ Names ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements C++ name mangling according to the Itanium C++ ABI, // which is used in GCC 3.2 and newer (and many compilers that are // ABI-compatible with GCC): // // http://www.codesourcery.com/public/cxx-abi/abi.html // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_CODEGEN_MANGLE_H #define LLVM_CLANG_CODEGEN_MANGLE_H #include "CGCXX.h" namespace llvm { class raw_ostream; } namespace clang { class ASTContext; class CXXConstructorDecl; class NamedDecl; class VarDecl; bool mangleName(const NamedDecl *D, ASTContext &Context, llvm::raw_ostream &os); void mangleGuardVariable(const VarDecl *D, ASTContext &Context, llvm::raw_ostream &os); void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, ASTContext &Context, llvm::raw_ostream &os); } #endif <file_sep>/tools/clang-cc/Backend.cpp //===--- Backend.cpp - Interface to LLVM backend technologies -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ASTConsumers.h" #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Frontend/CompileOptions.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/DeclGroup.h" #include "clang/Basic/TargetInfo.h" #include "llvm/Module.h" #include "llvm/ModuleProvider.h" #include "llvm/PassManager.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/CodeGen/RegAllocRegistry.h" #include "llvm/CodeGen/SchedulerRegistry.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Timer.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" #include "llvm/Target/SubtargetFeature.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/IPO.h" using namespace clang; using namespace llvm; namespace { class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer { BackendAction Action; CompileOptions CompileOpts; const std::string &InputFile; std::string OutputFile; ASTContext *Context; Timer LLVMIRGeneration; Timer CodeGenerationTime; llvm::OwningPtr<CodeGenerator> Gen; llvm::Module *TheModule; llvm::TargetData *TheTargetData; llvm::raw_ostream *AsmOutStream; mutable llvm::ModuleProvider *ModuleProvider; mutable FunctionPassManager *CodeGenPasses; mutable PassManager *PerModulePasses; mutable FunctionPassManager *PerFunctionPasses; FunctionPassManager *getCodeGenPasses() const; PassManager *getPerModulePasses() const; FunctionPassManager *getPerFunctionPasses() const; void CreatePasses(); /// AddEmitPasses - Add passes necessary to emit assembly or LLVM /// IR. /// /// \return True on success. On failure \arg Error will be set to /// a user readable error message. bool AddEmitPasses(std::string &Error); void EmitAssembly(); public: BackendConsumer(BackendAction action, Diagnostic &Diags, const LangOptions &langopts, const CompileOptions &compopts, const std::string &infile, const std::string &outfile) : Action(action), CompileOpts(compopts), InputFile(infile), OutputFile(outfile), LLVMIRGeneration("LLVM IR Generation Time"), CodeGenerationTime("Code Generation Time"), Gen(CreateLLVMCodeGen(Diags, InputFile, compopts)), TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0), CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) { // Enable -time-passes if -ftime-report is enabled. llvm::TimePassesIsEnabled = CompileOpts.TimePasses; } ~BackendConsumer() { delete AsmOutStream; delete TheTargetData; delete ModuleProvider; delete CodeGenPasses; delete PerModulePasses; delete PerFunctionPasses; } virtual void Initialize(ASTContext &Ctx) { Context = &Ctx; if (CompileOpts.TimePasses) LLVMIRGeneration.startTimer(); Gen->Initialize(Ctx); TheModule = Gen->GetModule(); ModuleProvider = new ExistingModuleProvider(TheModule); TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription()); if (CompileOpts.TimePasses) LLVMIRGeneration.stopTimer(); } virtual void HandleTopLevelDecl(DeclGroupRef D) { PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), Context->getSourceManager(), "LLVM IR generation of declaration"); if (CompileOpts.TimePasses) LLVMIRGeneration.startTimer(); Gen->HandleTopLevelDecl(D); if (CompileOpts.TimePasses) LLVMIRGeneration.stopTimer(); } virtual void HandleTranslationUnit(ASTContext &C) { { PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); if (CompileOpts.TimePasses) LLVMIRGeneration.startTimer(); Gen->HandleTranslationUnit(C); if (CompileOpts.TimePasses) LLVMIRGeneration.stopTimer(); } // EmitAssembly times and registers crash info itself. EmitAssembly(); // Force a flush here in case we never get released. if (AsmOutStream) AsmOutStream->flush(); } virtual void HandleTagDeclDefinition(TagDecl *D) { PrettyStackTraceDecl CrashInfo(D, SourceLocation(), Context->getSourceManager(), "LLVM IR generation of declaration"); Gen->HandleTagDeclDefinition(D); } }; } FunctionPassManager *BackendConsumer::getCodeGenPasses() const { if (!CodeGenPasses) { CodeGenPasses = new FunctionPassManager(ModuleProvider); CodeGenPasses->add(new TargetData(*TheTargetData)); } return CodeGenPasses; } PassManager *BackendConsumer::getPerModulePasses() const { if (!PerModulePasses) { PerModulePasses = new PassManager(); PerModulePasses->add(new TargetData(*TheTargetData)); } return PerModulePasses; } FunctionPassManager *BackendConsumer::getPerFunctionPasses() const { if (!PerFunctionPasses) { PerFunctionPasses = new FunctionPassManager(ModuleProvider); PerFunctionPasses->add(new TargetData(*TheTargetData)); } return PerFunctionPasses; } bool BackendConsumer::AddEmitPasses(std::string &Error) { if (Action == Backend_EmitNothing) return true; if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) { AsmOutStream = new raw_stdout_ostream(); sys::Program::ChangeStdoutToBinary(); } else { if (OutputFile.empty()) { llvm::sys::Path Path(InputFile); Path.eraseSuffix(); if (Action == Backend_EmitBC) { Path.appendSuffix("bc"); } else if (Action == Backend_EmitLL) { Path.appendSuffix("ll"); } else { Path.appendSuffix("s"); } OutputFile = Path.toString(); } AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error); if (!Error.empty()) return false; } if (Action == Backend_EmitBC) { getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream)); } else if (Action == Backend_EmitLL) { getPerModulePasses()->add(createPrintModulePass(AsmOutStream)); } else { bool Fast = CompileOpts.OptimizationLevel == 0; // Create the TargetMachine for generating code. const TargetMachineRegistry::entry *TME = TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error); if (!TME) { Error = std::string("Unable to get target machine: ") + Error; return false; } std::string FeaturesStr; if (CompileOpts.CPU.size() || CompileOpts.Features.size()) { SubtargetFeatures Features; Features.setCPU(CompileOpts.CPU); for (std::vector<std::string>::iterator it = CompileOpts.Features.begin(), ie = CompileOpts.Features.end(); it != ie; ++it) Features.AddFeature(*it); FeaturesStr = Features.getString(); } TargetMachine *TM = TME->CtorFn(*TheModule, FeaturesStr); // Set register scheduler & allocation policy. RegisterScheduler::setDefault(createDefaultScheduler); RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator : createLinearScanRegisterAllocator); // From llvm-gcc: // If there are passes we have to run on the entire module, we do codegen // as a separate "pass" after that happens. // FIXME: This is disabled right now until bugs can be worked out. Reenable // this for fast -O0 compiles! FunctionPassManager *PM = getCodeGenPasses(); // Normal mode, emit a .s file by running the code generator. // Note, this also adds codegenerator level optimization passes. switch (TM->addPassesToEmitFile(*PM, *AsmOutStream, TargetMachine::AssemblyFile, Fast)) { default: case FileModel::Error: Error = "Unable to interface with target machine!\n"; return false; case FileModel::AsmFile: break; } if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) { Error = "Unable to interface with target machine!\n"; return false; } } return true; } void BackendConsumer::CreatePasses() { // In -O0 if checking is disabled, we don't even have per-function passes. if (CompileOpts.VerifyModule) getPerFunctionPasses()->add(createVerifierPass()); if (CompileOpts.OptimizationLevel > 0) { FunctionPassManager *PM = getPerFunctionPasses(); PM->add(createCFGSimplificationPass()); if (CompileOpts.OptimizationLevel == 1) PM->add(createPromoteMemoryToRegisterPass()); else PM->add(createScalarReplAggregatesPass()); PM->add(createInstructionCombiningPass()); } // For now we always create per module passes. PassManager *PM = getPerModulePasses(); if (CompileOpts.OptimizationLevel > 0) { if (CompileOpts.UnitAtATime) PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst PM->add(createCFGSimplificationPass()); // Clean up disgusting code PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas if (CompileOpts.UnitAtATime) { PM->add(createGlobalOptimizerPass()); // Optimize out global vars PM->add(createGlobalDCEPass()); // Remove unused fns and globs PM->add(createIPConstantPropagationPass()); // IP Constant Propagation PM->add(createDeadArgEliminationPass()); // Dead argument elimination } PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE if (CompileOpts.UnitAtATime) { PM->add(createPruneEHPass()); // Remove dead EH info PM->add(createFunctionAttrsPass()); // Set readonly/readnone attrs } if (CompileOpts.InlineFunctions) PM->add(createFunctionInliningPass()); // Inline small functions else PM->add(createAlwaysInlinerPass()); // Respect always_inline if (CompileOpts.OptimizationLevel > 2) PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args if (CompileOpts.SimplifyLibCalls) PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl. PM->add(createJumpThreadingPass()); // Thread jumps. PM->add(createCFGSimplificationPass()); // Merge & remove BBs PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas PM->add(createInstructionCombiningPass()); // Combine silly seq's PM->add(createCondPropagationPass()); // Propagate conditionals PM->add(createTailCallEliminationPass()); // Eliminate tail calls PM->add(createCFGSimplificationPass()); // Merge & remove BBs PM->add(createReassociatePass()); // Reassociate expressions PM->add(createLoopRotatePass()); // Rotate Loop PM->add(createLICMPass()); // Hoist loop invariants PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false)); // PM->add(createLoopIndexSplitPass()); // Split loop index PM->add(createInstructionCombiningPass()); PM->add(createIndVarSimplifyPass()); // Canonicalize indvars PM->add(createLoopDeletionPass()); // Delete dead loops if (CompileOpts.UnrollLoops) PM->add(createLoopUnrollPass()); // Unroll small loops PM->add(createInstructionCombiningPass()); // Clean up after the unroller PM->add(createGVNPass()); // Remove redundancies PM->add(createMemCpyOptPass()); // Remove memcpy / form memset PM->add(createSCCPPass()); // Constant prop with SCCP // Run instcombine after redundancy elimination to exploit opportunities // opened up by them. PM->add(createInstructionCombiningPass()); PM->add(createCondPropagationPass()); // Propagate conditionals PM->add(createDeadStoreEliminationPass()); // Delete dead stores PM->add(createAggressiveDCEPass()); // Delete dead instructions PM->add(createCFGSimplificationPass()); // Merge & remove BBs if (CompileOpts.UnitAtATime) { PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes PM->add(createDeadTypeEliminationPass()); // Eliminate dead types } if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime) PM->add(createConstantMergePass()); // Merge dup global constants } else { PM->add(createAlwaysInlinerPass()); } } /// EmitAssembly - Handle interaction with LLVM backend to generate /// actual machine code. void BackendConsumer::EmitAssembly() { // Silently ignore if we weren't initialized for some reason. if (!TheModule || !TheTargetData) return; TimeRegion Region(CompileOpts.TimePasses ? &CodeGenerationTime : 0); // Make sure IR generation is happy with the module. This is // released by the module provider. Module *M = Gen->ReleaseModule(); if (!M) { // The module has been released by IR gen on failures, do not // double free. ModuleProvider->releaseModule(); TheModule = 0; return; } assert(TheModule == M && "Unexpected module change during IR generation"); CreatePasses(); std::string Error; if (!AddEmitPasses(Error)) { // FIXME: Don't fail this way. llvm::cerr << "ERROR: " << Error << "\n"; ::exit(1); } // Run passes. For now we do all passes at once, but eventually we // would like to have the option of streaming code generation. if (PerFunctionPasses) { PrettyStackTraceString CrashInfo("Per-function optimization"); PerFunctionPasses->doInitialization(); for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) if (!I->isDeclaration()) PerFunctionPasses->run(*I); PerFunctionPasses->doFinalization(); } if (PerModulePasses) { PrettyStackTraceString CrashInfo("Per-module optimization passes"); PerModulePasses->run(*M); } if (CodeGenPasses) { PrettyStackTraceString CrashInfo("Code generation"); CodeGenPasses->doInitialization(); for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) if (!I->isDeclaration()) CodeGenPasses->run(*I); CodeGenPasses->doFinalization(); } } ASTConsumer *clang::CreateBackendConsumer(BackendAction Action, Diagnostic &Diags, const LangOptions &LangOpts, const CompileOptions &CompileOpts, const std::string& InFile, const std::string& OutFile) { return new BackendConsumer(Action, Diags, LangOpts, CompileOpts, InFile, OutFile); } <file_sep>/include/clang/AST/TargetBuiltins.h //===--- TargetBuiltins.h - Target specific builtin IDs -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_TARGET_BUILTINS_H #define LLVM_CLANG_AST_TARGET_BUILTINS_H #include "clang/AST/Builtins.h" #undef PPC namespace clang { /// X86 builtins namespace X86 { enum { LastTIBuiltin = clang::Builtin::FirstTSBuiltin-1, #define BUILTIN(ID, TYPE, ATTRS) BI##ID, #include "X86Builtins.def" LastTSBuiltin }; } /// PPC builtins namespace PPC { enum { LastTIBuiltin = clang::Builtin::FirstTSBuiltin-1, #define BUILTIN(ID, TYPE, ATTRS) BI##ID, #include "PPCBuiltins.def" LastTSBuiltin }; } } // end namespace clang. #endif <file_sep>/test/Sema/c89-2.c /* RUN: not clang-cc %s -std=c89 -pedantic-errors */ /* We can't put expected-warning lines on #if lines. */ #if 1LL /* expected-warning {{long long}} */ #endif <file_sep>/lib/Parse/ParsePragma.cpp //===--- ParsePragma.cpp - Language specific pragma parsing ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the language specific #pragma handlers. // //===----------------------------------------------------------------------===// #include "ParsePragma.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Lex/Preprocessor.h" #include "clang/Parse/Action.h" #include "clang/Parse/Parser.h" using namespace clang; // #pragma pack(...) comes in the following delicious flavors: // pack '(' [integer] ')' // pack '(' 'show' ')' // pack '(' ('push' | 'pop') [',' identifier] [, integer] ')' void PragmaPackHandler::HandlePragma(Preprocessor &PP, Token &PackTok) { // FIXME: Should we be expanding macros here? My guess is no. SourceLocation PackLoc = PackTok.getLocation(); Token Tok; PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack"; return; } Action::PragmaPackKind Kind = Action::PPK_Default; IdentifierInfo *Name = 0; Action::OwningExprResult Alignment(Actions); SourceLocation LParenLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.is(tok::numeric_constant)) { Alignment = Actions.ActOnNumericConstant(Tok); if (Alignment.isInvalid()) return; PP.Lex(Tok); } else if (Tok.is(tok::identifier)) { const IdentifierInfo *II = Tok.getIdentifierInfo(); if (II->isStr("show")) { Kind = Action::PPK_Show; PP.Lex(Tok); } else { if (II->isStr("push")) { Kind = Action::PPK_Push; } else if (II->isStr("pop")) { Kind = Action::PPK_Pop; } else { PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_invalid_action); return; } PP.Lex(Tok); if (Tok.is(tok::comma)) { PP.Lex(Tok); if (Tok.is(tok::numeric_constant)) { Alignment = Actions.ActOnNumericConstant(Tok); if (Alignment.isInvalid()) return; PP.Lex(Tok); } else if (Tok.is(tok::identifier)) { Name = Tok.getIdentifierInfo(); PP.Lex(Tok); if (Tok.is(tok::comma)) { PP.Lex(Tok); if (Tok.isNot(tok::numeric_constant)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed); return; } Alignment = Actions.ActOnNumericConstant(Tok); if (Alignment.isInvalid()) return; PP.Lex(Tok); } } else { PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed); return; } } } } if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack"; return; } SourceLocation RParenLoc = Tok.getLocation(); Actions.ActOnPragmaPack(Kind, Name, Alignment.release(), PackLoc, LParenLoc, RParenLoc); } // #pragma unused(identifier) void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, Token &UnusedTok) { // FIXME: Should we be expanding macros here? My guess is no. SourceLocation UnusedLoc = UnusedTok.getLocation(); // Lex the left '('. Token Tok; PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused"; return; } SourceLocation LParenLoc = Tok.getLocation(); // Lex the declaration reference(s). llvm::SmallVector<Action::ExprTy*, 5> Ex; SourceLocation RParenLoc; bool LexID = true; while (true) { PP.Lex(Tok); if (LexID) { if (Tok.is(tok::identifier)) { Action::OwningExprResult Name = Actions.ActOnIdentifierExpr(parser.CurScope, Tok.getLocation(), *Tok.getIdentifierInfo(), false); if (Name.isInvalid()) { if (!Ex.empty()) Action::MultiExprArg Release(Actions, &Ex[0], Ex.size()); return; } Ex.push_back(Name.release()); LexID = false; continue; } // Illegal token! Release the parsed expressions (if any) and emit // a warning. if (!Ex.empty()) Action::MultiExprArg Release(Actions, &Ex[0], Ex.size()); PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var); return; } // We are execting a ')' or a ','. if (Tok.is(tok::comma)) { LexID = true; continue; } if (Tok.is(tok::r_paren)) { RParenLoc = Tok.getLocation(); break; } // Illegal token! Release the parsed expressions (if any) and emit // a warning. if (!Ex.empty()) Action::MultiExprArg Release(Actions, &Ex[0], Ex.size()); PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_punc); return; } // Verify that we have a location for the right parenthesis. assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'"); assert(!Ex.empty() && "Valid '#pragma unused' must have arguments"); // Perform the action to handle the pragma. Actions.ActOnPragmaUnused(&Ex[0], Ex.size(), UnusedLoc, LParenLoc, RParenLoc); } <file_sep>/test/Makefile LEVEL = ../../.. include $(LEVEL)/Makefile.common # Test in all immediate subdirectories if unset. TESTDIRS ?= $(shell echo $(PROJ_SRC_DIR)/*/) # Only run rewriter tests on darwin. ifeq ($(OS),Darwin) TESTDIRS += endif ifdef VERBOSE ifeq ($(VERBOSE),0) PROGRESS = : REPORTFAIL = echo 'FAIL: clang' $(TARGET_TRIPLE) $(subst $(LLVM_SRC_ROOT)/tools/clang/,,$<) DONE = $(LLVMToolDir)/clang -v else PROGRESS = echo $< REPORTFAIL = cat $@ DONE = true endif else PROGRESS = printf '.' REPORTFAIL = (echo; echo '----' $< 'failed ----') DONE = echo endif TESTS := $(addprefix Output/, $(addsuffix .testresults, $(shell find $(TESTDIRS) \( -name '*.c' -or -name '*.cpp' -or -name '*.m' -or -name '*.mm' -or -name '*.S' \) | grep -v "Output/"))) Output/%.testresults: % @ $(PROGRESS) @ PATH=$(ToolDir):$(LLVM_SRC_ROOT)/test/Scripts:$$PATH VG=$(VG) $(PROJ_SRC_DIR)/TestRunner.sh $< > $@ || $(REPORTFAIL) all:: @ mkdir -p $(addprefix Output/, $(TESTDIRS)) @ rm -f $(TESTS) @ echo '--- Running clang tests for $(TARGET_TRIPLE) ---' @ $(MAKE) $(TESTS) @ $(DONE) @ !(cat $(TESTS) | grep -q " FAILED! ") report: $(TESTS) @ cat $^ clean:: @ rm -rf Output/ .PHONY: all report clean <file_sep>/tools/ccc/ccclib/Types.py class InputType(object): """InputType - Information about various classes of files which the driver recognizes and control processing.""" def __init__(self, name, preprocess=None, onlyAssemble=False, onlyPrecompile=False, tempSuffix=None, canBeUserSpecified=False, appendSuffix=False): assert preprocess is None or isinstance(preprocess, InputType) self.name = name self.preprocess = preprocess self.onlyAssemble = onlyAssemble self.onlyPrecompile = onlyPrecompile self.tempSuffix = tempSuffix self.canBeUserSpecified = canBeUserSpecified self.appendSuffix = appendSuffix def __repr__(self): return '%s(%r, %r, %r, %r, %r, %r)' % (self.__class__.__name__, self.name, self.preprocess, self.onlyAssemble, self.onlyPrecompile, self.tempSuffix, self.canBeUserSpecified) # C family source language (with and without preprocessing). CTypeNoPP = InputType('cpp-output', tempSuffix='i', canBeUserSpecified=True) CType = InputType('c', CTypeNoPP, canBeUserSpecified=True) ObjCTypeNoPP = InputType('objective-c-cpp-output', tempSuffix='mi', canBeUserSpecified=True) ObjCType = InputType('objective-c', ObjCTypeNoPP, canBeUserSpecified=True) CXXTypeNoPP = InputType('c++-cpp-output', tempSuffix='ii', canBeUserSpecified=True) CXXType = InputType('c++', CXXTypeNoPP, canBeUserSpecified=True) ObjCXXTypeNoPP = InputType('objective-c++-cpp-output', tempSuffix='mii', canBeUserSpecified=True) ObjCXXType = InputType('objective-c++', ObjCXXTypeNoPP, canBeUserSpecified=True) # C family input files to precompile. CHeaderNoPPType = InputType('c-header-cpp-output', tempSuffix='i', onlyPrecompile=True) CHeaderType = InputType('c-header', CHeaderNoPPType, onlyPrecompile=True, canBeUserSpecified=True) ObjCHeaderNoPPType = InputType('objective-c-header-cpp-output', tempSuffix='mi', onlyPrecompile=True) ObjCHeaderType = InputType('objective-c-header', ObjCHeaderNoPPType, onlyPrecompile=True, canBeUserSpecified=True) CXXHeaderNoPPType = InputType('c++-header-cpp-output', tempSuffix='ii', onlyPrecompile=True) CXXHeaderType = InputType('c++-header', CXXHeaderNoPPType, onlyPrecompile=True, canBeUserSpecified=True) ObjCXXHeaderNoPPType = InputType('objective-c++-header-cpp-output', tempSuffix='mii', onlyPrecompile=True) ObjCXXHeaderType = InputType('objective-c++-header', ObjCXXHeaderNoPPType, onlyPrecompile=True, canBeUserSpecified=True) # Other languages. AdaType = InputType('ada', canBeUserSpecified=True) AsmTypeNoPP = InputType('assembler', onlyAssemble=True, tempSuffix='s', canBeUserSpecified=True) AsmType = InputType('assembler-with-cpp', AsmTypeNoPP, onlyAssemble=True, canBeUserSpecified=True) FortranTypeNoPP = InputType('f95', canBeUserSpecified=True) FortranType = InputType('f95-cpp-input', FortranTypeNoPP, canBeUserSpecified=True) JavaType = InputType('java', canBeUserSpecified=True) # Misc. LLVMAsmType = InputType('llvm-asm', tempSuffix='ll') LLVMBCType = InputType('llvm-bc', tempSuffix='bc') PlistType = InputType('plist', tempSuffix='plist') PCHType = InputType('precompiled-header', tempSuffix='gch', appendSuffix=True) ObjectType = InputType('object', tempSuffix='o') TreelangType = InputType('treelang', canBeUserSpecified=True) ImageType = InputType('image', tempSuffix='out') NothingType = InputType('nothing') ### kDefaultOutput = "a.out" kTypeSuffixMap = { '.c' : CType, '.i' : CTypeNoPP, '.ii' : CXXTypeNoPP, '.m' : ObjCType, '.mi' : ObjCTypeNoPP, '.mm' : ObjCXXType, '.M' : ObjCXXType, '.mii' : ObjCXXTypeNoPP, '.h' : CHeaderType, '.cc' : CXXType, '.cc' : CXXType, '.cp' : CXXType, '.cxx' : CXXType, '.cpp' : CXXType, '.CPP' : CXXType, '.cXX' : CXXType, '.C' : CXXType, '.hh' : CXXHeaderType, '.H' : CXXHeaderType, '.f' : FortranTypeNoPP, '.for' : FortranTypeNoPP, '.FOR' : FortranTypeNoPP, '.F' : FortranType, '.fpp' : FortranType, '.FPP' : FortranType, '.f90' : FortranTypeNoPP, '.f95' : FortranTypeNoPP, '.F90' : FortranType, '.F95' : FortranType, # Apparently the Ada F-E hardcodes these suffixes in many # places. This explains why there is only one -x option for ada. '.ads' : AdaType, '.adb' : AdaType, # FIXME: Darwin always uses a preprocessor for asm input. Where # does this fit? '.s' : AsmTypeNoPP, '.S' : AsmType, } kTypeSpecifierMap = { 'none' : None, 'c' : CType, 'c-header' : CHeaderType, # NOTE: gcc.info claims c-cpp-output works but the actual spelling # is cpp-output. Nice. 'cpp-output' : CTypeNoPP, 'c++' : CXXType, 'c++-header' : CXXHeaderType, 'c++-cpp-output' : CXXTypeNoPP, 'objective-c' : ObjCType, 'objective-c-header' : ObjCHeaderType, 'objective-c-cpp-output' : ObjCTypeNoPP, 'objective-c++' : ObjCXXType, 'objective-c++-header' : ObjCXXHeaderType, 'objective-c++-cpp-output' : ObjCXXTypeNoPP, 'assembler' : AsmTypeNoPP, 'assembler-with-cpp' : AsmType, 'ada' : AdaType, 'f95-cpp-input' : FortranType, 'f95' : FortranTypeNoPP, 'java' : JavaType, 'treelang' : TreelangType, } # Set of C family types. clangableTypesSet = set([AsmType, # Assembler to preprocess CType, CTypeNoPP, ObjCType, ObjCTypeNoPP, CXXType, CXXTypeNoPP, ObjCXXType, ObjCXXTypeNoPP, CHeaderType, CHeaderNoPPType, ObjCHeaderType, ObjCHeaderNoPPType, CXXHeaderType, CXXHeaderNoPPType, ObjCXXHeaderType, ObjCXXHeaderNoPPType]) # Set of C++ family types. cxxTypesSet = set([CXXType, CXXTypeNoPP, ObjCXXType, ObjCXXTypeNoPP, CXXHeaderType, CXXHeaderNoPPType, ObjCXXHeaderType, ObjCXXHeaderNoPPType]) # Check that the type specifier map at least matches what the types # believe to be true. assert not [name for name,type in kTypeSpecifierMap.items() if type and (type.name != name or not type.canBeUserSpecified)] <file_sep>/tools/ccc/test/ccc/aliases.c // RUN: xcc -ccc-no-clang -### -S --all-warnings %s &> %t && // RUN: grep -- '"-Wall"' %t && // RUN: xcc -ccc-no-clang -### -S --ansi %s &> %t && // RUN: grep -- '"-ansi"' %t && // RUN: xcc -ccc-no-clang -### -S --assert foo --assert=foo %s &> %t && // RUN: grep -- '"-A" "foo" "-A" "foo"' %t && // RUN: xcc -ccc-no-clang -### -S --classpath foo --classpath=foo %s &> %t && // RUN: grep -- '"-fclasspath=foo" "-fclasspath=foo"' %t && // RUN: true <file_sep>/tools/clang-cc/CMakeLists.txt set(LLVM_NO_RTTI 1) set( LLVM_USED_LIBS clangCodeGen clangAnalysis clangRewrite clangSema clangFrontend clangAST clangParse clangLex clangBasic ) set( LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} bitreader bitwriter codegen ipo selectiondag ) add_clang_executable(clang-cc AnalysisConsumer.cpp ASTConsumers.cpp Backend.cpp CacheTokens.cpp clang-cc.cpp DependencyFile.cpp DiagChecker.cpp GeneratePCH.cpp HTMLPrint.cpp PrintParserCallbacks.cpp PrintPreprocessedOutput.cpp RewriteBlocks.cpp RewriteMacros.cpp RewriteObjC.cpp RewriteTest.cpp SerializationTest.cpp Warnings.cpp ) <file_sep>/test/SemaCXX/member-expr.cpp // RUN: clang-cc -fsyntax-only -verify %s class X{ public: enum E {Enumerator}; int f(); static int mem; static float g(); }; void test(X* xp, X x) { int i1 = x.f(); int i2 = xp->f(); x.E; // expected-error{{cannot refer to type member 'E' with '.'}} xp->E; // expected-error{{cannot refer to type member 'E' with '->'}} int i3 = x.Enumerator; int i4 = xp->Enumerator; x.mem = 1; xp->mem = 2; float f1 = x.g(); float f2 = xp->g(); } struct A { int f0; }; struct B { A *f0(); }; int f0(B *b) { return b->f0->f0; // expected-error{{member reference base type 'struct A *(void)' is not a structure or union}} \ // expected-note{{perhaps you meant to call this function}} } <file_sep>/test/SemaCXX/functional-cast.cpp // RUN: clang-cc -fsyntax-only -verify %s struct SimpleValueInit { int i; }; struct InitViaConstructor { InitViaConstructor(int i = 7); }; // FIXME: error messages for implicitly-declared special member // function candidates are very poor struct NoValueInit { // expected-note 2 {{candidate function}} NoValueInit(int i, int j); // expected-note 2 {{candidate function}} }; void test_cxx_functional_value_init() { (void)SimpleValueInit(); (void)InitViaConstructor(); (void)NoValueInit(); // expected-error{{no matching constructor for initialization}} } void test_cxx_function_cast_multi() { (void)NoValueInit(0, 0); (void)NoValueInit(0, 0, 0); // expected-error{{no matching constructor for initialization}} (void)int(1, 2); // expected-error{{function-style cast to a builtin type can only take one argument}} } <file_sep>/include/clang/Frontend/ManagerRegistry.h //===-- ManagerRegistry.h - Pluggable analyzer module registry --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ManagerRegistry and Register* classes. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_FRONTEND_MANAGER_REGISTRY_H #define LLVM_CLANG_FRONTEND_MANAGER_REGISTRY_H #include "clang/Analysis/PathSensitive/GRState.h" namespace clang { /// ManagerRegistry - This class records manager creators registered at /// runtime. The information is communicated to AnalysisManager through static /// members. Better design is expected. class ManagerRegistry { public: static StoreManagerCreator StoreMgrCreator; static ConstraintManagerCreator ConstraintMgrCreator; }; /// RegisterConstraintManager - This class is used to setup the constraint /// manager of the static analyzer. The constructor takes a creator function /// pointer for creating the constraint manager. /// /// It is used like this: /// /// class MyConstraintManager {}; /// ConstraintManager* CreateMyConstraintManager(GRStateManager& statemgr) { /// return new MyConstraintManager(statemgr); /// } /// RegisterConstraintManager X(CreateMyConstraintManager); class RegisterConstraintManager { public: RegisterConstraintManager(ConstraintManagerCreator CMC) { assert(ManagerRegistry::ConstraintMgrCreator == 0 && "ConstraintMgrCreator already set!"); ManagerRegistry::ConstraintMgrCreator = CMC; } }; } #endif <file_sep>/test/SemaTemplate/instantiate-typedef.cpp // RUN: clang-cc -fsyntax-only -verify %s template<typename T> struct add_pointer { typedef T* type; // expected-error{{'type' declared as a pointer to a reference}} }; add_pointer<int>::type test1(int * ptr) { return ptr; } add_pointer<float>::type test2(int * ptr) { return ptr; // expected-error{{incompatible type returning 'int *', expected 'add_pointer<float>::type' (aka 'float *')}} } add_pointer<int&>::type // expected-note{{in instantiation of template class 'struct add_pointer<int &>' requested here}} expected-error {{unknown type name 'type'}} test3(); <file_sep>/lib/Analysis/SVals.cpp //= RValues.cpp - Abstract RValues for Path-Sens. Value Tracking -*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines SVal, Loc, and NonLoc, classes that represent // abstract r-values for use with path-sensitive value tracking. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Basic/IdentifierTable.h" #include "llvm/Support/Streams.h" using namespace clang; using llvm::dyn_cast; using llvm::cast; using llvm::APSInt; //===----------------------------------------------------------------------===// // Symbol iteration within an SVal. //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Utility methods. //===----------------------------------------------------------------------===// /// getAsLocSymbol - If this SVal is a location (subclasses Loc) and /// wraps a symbol, return that SymbolRef. Otherwise return a SymbolRef /// where 'isValid()' returns false. SymbolRef SVal::getAsLocSymbol() const { if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(this)) { const MemRegion *R = X->getRegion(); while (R) { // Blast through region views. if (const TypedViewRegion *View = dyn_cast<TypedViewRegion>(R)) { R = View->getSuperRegion(); continue; } if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(R)) return SymR->getSymbol(); break; } } return 0; } /// getAsSymbol - If this Sval wraps a symbol return that SymbolRef. /// Otherwise return a SymbolRef where 'isValid()' returns false. SymbolRef SVal::getAsSymbol() const { if (const nonloc::SymbolVal *X = dyn_cast<nonloc::SymbolVal>(this)) return X->getSymbol(); if (const nonloc::SymExprVal *X = dyn_cast<nonloc::SymExprVal>(this)) if (SymbolRef Y = dyn_cast<SymbolData>(X->getSymbolicExpression())) return Y; return getAsLocSymbol(); } /// getAsSymbolicExpression - If this Sval wraps a symbolic expression then /// return that expression. Otherwise return NULL. const SymExpr *SVal::getAsSymbolicExpression() const { if (const nonloc::SymExprVal *X = dyn_cast<nonloc::SymExprVal>(this)) return X->getSymbolicExpression(); return getAsSymbol(); } bool SVal::symbol_iterator::operator==(const symbol_iterator &X) const { return itr == X.itr; } bool SVal::symbol_iterator::operator!=(const symbol_iterator &X) const { return itr != X.itr; } SVal::symbol_iterator::symbol_iterator(const SymExpr *SE) { itr.push_back(SE); while (!isa<SymbolData>(itr.back())) expand(); } SVal::symbol_iterator& SVal::symbol_iterator::operator++() { assert(!itr.empty() && "attempting to iterate on an 'end' iterator"); assert(isa<SymbolData>(itr.back())); itr.pop_back(); if (!itr.empty()) while (!isa<SymbolData>(itr.back())) expand(); return *this; } SymbolRef SVal::symbol_iterator::operator*() { assert(!itr.empty() && "attempting to dereference an 'end' iterator"); return cast<SymbolData>(itr.back()); } void SVal::symbol_iterator::expand() { const SymExpr *SE = itr.back(); itr.pop_back(); if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) { itr.push_back(SIE->getLHS()); return; } else if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) { itr.push_back(SSE->getLHS()); itr.push_back(SSE->getRHS()); return; } assert(false && "unhandled expansion case"); } //===----------------------------------------------------------------------===// // Other Iterators. //===----------------------------------------------------------------------===// nonloc::CompoundVal::iterator nonloc::CompoundVal::begin() const { return getValue()->begin(); } nonloc::CompoundVal::iterator nonloc::CompoundVal::end() const { return getValue()->end(); } //===----------------------------------------------------------------------===// // Useful predicates. //===----------------------------------------------------------------------===// bool SVal::isZeroConstant() const { if (isa<loc::ConcreteInt>(*this)) return cast<loc::ConcreteInt>(*this).getValue() == 0; else if (isa<nonloc::ConcreteInt>(*this)) return cast<nonloc::ConcreteInt>(*this).getValue() == 0; else return false; } //===----------------------------------------------------------------------===// // Transfer function dispatch for Non-Locs. //===----------------------------------------------------------------------===// SVal nonloc::ConcreteInt::EvalBinOp(BasicValueFactory& BasicVals, BinaryOperator::Opcode Op, const nonloc::ConcreteInt& R) const { const llvm::APSInt* X = BasicVals.EvaluateAPSInt(Op, getValue(), R.getValue()); if (X) return nonloc::ConcreteInt(*X); else return UndefinedVal(); } // Bitwise-Complement. nonloc::ConcreteInt nonloc::ConcreteInt::EvalComplement(BasicValueFactory& BasicVals) const { return BasicVals.getValue(~getValue()); } // Unary Minus. nonloc::ConcreteInt nonloc::ConcreteInt::EvalMinus(BasicValueFactory& BasicVals, UnaryOperator* U) const { assert (U->getType() == U->getSubExpr()->getType()); assert (U->getType()->isIntegerType()); return BasicVals.getValue(-getValue()); } //===----------------------------------------------------------------------===// // Transfer function dispatch for Locs. //===----------------------------------------------------------------------===// SVal loc::ConcreteInt::EvalBinOp(BasicValueFactory& BasicVals, BinaryOperator::Opcode Op, const loc::ConcreteInt& R) const { assert (Op == BinaryOperator::Add || Op == BinaryOperator::Sub || (Op >= BinaryOperator::LT && Op <= BinaryOperator::NE)); const llvm::APSInt* X = BasicVals.EvaluateAPSInt(Op, getValue(), R.getValue()); if (X) return loc::ConcreteInt(*X); else return UndefinedVal(); } //===----------------------------------------------------------------------===// // Utility methods for constructing SVals. //===----------------------------------------------------------------------===// SVal ValueManager::makeZeroVal(QualType T) { if (Loc::IsLocType(T)) return Loc::MakeNull(BasicVals); if (T->isIntegerType()) return NonLoc::MakeVal(BasicVals, 0, T); // FIXME: Handle floats. // FIXME: Handle structs. return UnknownVal(); } //===----------------------------------------------------------------------===// // Utility methods for constructing Non-Locs. //===----------------------------------------------------------------------===// NonLoc ValueManager::makeNonLoc(SymbolRef sym) { return nonloc::SymbolVal(sym); } NonLoc ValueManager::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, const APSInt& v, QualType T) { // The Environment ensures we always get a persistent APSInt in // BasicValueFactory, so we don't need to get the APSInt from // BasicValueFactory again. assert(!Loc::IsLocType(T)); return nonloc::SymExprVal(SymMgr.getSymIntExpr(lhs, op, v, T)); } NonLoc ValueManager::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType T) { assert(SymMgr.getType(lhs) == SymMgr.getType(rhs)); assert(!Loc::IsLocType(T)); return nonloc::SymExprVal(SymMgr.getSymSymExpr(lhs, op, rhs, T)); } NonLoc NonLoc::MakeIntVal(BasicValueFactory& BasicVals, uint64_t X, bool isUnsigned) { return nonloc::ConcreteInt(BasicVals.getIntValue(X, isUnsigned)); } NonLoc NonLoc::MakeVal(BasicValueFactory& BasicVals, uint64_t X, unsigned BitWidth, bool isUnsigned) { return nonloc::ConcreteInt(BasicVals.getValue(X, BitWidth, isUnsigned)); } NonLoc NonLoc::MakeVal(BasicValueFactory& BasicVals, uint64_t X, QualType T) { return nonloc::ConcreteInt(BasicVals.getValue(X, T)); } NonLoc NonLoc::MakeVal(BasicValueFactory& BasicVals, IntegerLiteral* I) { return nonloc::ConcreteInt(BasicVals.getValue(APSInt(I->getValue(), I->getType()->isUnsignedIntegerType()))); } NonLoc NonLoc::MakeVal(BasicValueFactory& BasicVals, const llvm::APInt& I, bool isUnsigned) { return nonloc::ConcreteInt(BasicVals.getValue(I, isUnsigned)); } NonLoc NonLoc::MakeVal(BasicValueFactory& BasicVals, const llvm::APSInt& I) { return nonloc::ConcreteInt(BasicVals.getValue(I)); } NonLoc NonLoc::MakeIntTruthVal(BasicValueFactory& BasicVals, bool b) { return nonloc::ConcreteInt(BasicVals.getTruthValue(b)); } NonLoc ValueManager::makeTruthVal(bool b, QualType T) { return nonloc::ConcreteInt(BasicVals.getTruthValue(b, T)); } NonLoc NonLoc::MakeCompoundVal(QualType T, llvm::ImmutableList<SVal> Vals, BasicValueFactory& BasicVals) { return nonloc::CompoundVal(BasicVals.getCompoundValData(T, Vals)); } SVal ValueManager::getRValueSymbolVal(const MemRegion* R) { SymbolRef sym = SymMgr.getRegionRValueSymbol(R); if (const TypedRegion* TR = dyn_cast<TypedRegion>(R)) { QualType T = TR->getRValueType(SymMgr.getContext()); // If T is of function pointer type, create a CodeTextRegion wrapping a // symbol. if (T->isFunctionPointerType()) { return Loc::MakeVal(MemMgr.getCodeTextRegion(sym, T)); } if (Loc::IsLocType(T)) return Loc::MakeVal(MemMgr.getSymbolicRegion(sym)); // Only handle integers for now. if (T->isIntegerType() && T->isScalarType()) return makeNonLoc(sym); } return UnknownVal(); } SVal ValueManager::getConjuredSymbolVal(const Expr* E, unsigned Count) { QualType T = E->getType(); SymbolRef sym = SymMgr.getConjuredSymbol(E, Count); // If T is of function pointer type, create a CodeTextRegion wrapping a // symbol. if (T->isFunctionPointerType()) { return Loc::MakeVal(MemMgr.getCodeTextRegion(sym, T)); } if (Loc::IsLocType(T)) return Loc::MakeVal(MemMgr.getSymbolicRegion(sym)); if (T->isIntegerType() && T->isScalarType()) return makeNonLoc(sym); return UnknownVal(); } SVal ValueManager::getConjuredSymbolVal(const Expr* E, QualType T, unsigned Count) { SymbolRef sym = SymMgr.getConjuredSymbol(E, T, Count); // If T is of function pointer type, create a CodeTextRegion wrapping a // symbol. if (T->isFunctionPointerType()) { return Loc::MakeVal(MemMgr.getCodeTextRegion(sym, T)); } if (Loc::IsLocType(T)) return Loc::MakeVal(MemMgr.getSymbolicRegion(sym)); if (T->isIntegerType() && T->isScalarType()) return makeNonLoc(sym); return UnknownVal(); } SVal ValueManager::getFunctionPointer(const FunctionDecl* FD) { CodeTextRegion* R = MemMgr.getCodeTextRegion(FD, Context.getPointerType(FD->getType())); return Loc::MakeVal(R); } nonloc::LocAsInteger nonloc::LocAsInteger::Make(BasicValueFactory& Vals, Loc V, unsigned Bits) { return LocAsInteger(Vals.getPersistentSValWithData(V, Bits)); } //===----------------------------------------------------------------------===// // Utility methods for constructing Locs. //===----------------------------------------------------------------------===// Loc Loc::MakeVal(const MemRegion* R) { return loc::MemRegionVal(R); } Loc Loc::MakeVal(AddrLabelExpr* E) { return loc::GotoLabel(E->getLabel()); } Loc Loc::MakeNull(BasicValueFactory &BasicVals) { return loc::ConcreteInt(BasicVals.getZeroWithPtrWidth()); } //===----------------------------------------------------------------------===// // Pretty-Printing. //===----------------------------------------------------------------------===// void SVal::printStdErr() const { print(llvm::errs()); } void SVal::print(std::ostream& Out) const { llvm::raw_os_ostream out(Out); print(out); } void SVal::print(llvm::raw_ostream& Out) const { switch (getBaseKind()) { case UnknownKind: Out << "Invalid"; break; case NonLocKind: cast<NonLoc>(this)->print(Out); break; case LocKind: cast<Loc>(this)->print(Out); break; case UndefinedKind: Out << "Undefined"; break; default: assert (false && "Invalid SVal."); } } void NonLoc::print(llvm::raw_ostream& Out) const { switch (getSubKind()) { case nonloc::ConcreteIntKind: Out << cast<nonloc::ConcreteInt>(this)->getValue().getZExtValue(); if (cast<nonloc::ConcreteInt>(this)->getValue().isUnsigned()) Out << 'U'; break; case nonloc::SymbolValKind: Out << '$' << cast<nonloc::SymbolVal>(this)->getSymbol(); break; case nonloc::SymExprValKind: { const nonloc::SymExprVal& C = *cast<nonloc::SymExprVal>(this); const SymExpr *SE = C.getSymbolicExpression(); Out << SE; break; } case nonloc::LocAsIntegerKind: { const nonloc::LocAsInteger& C = *cast<nonloc::LocAsInteger>(this); C.getLoc().print(Out); Out << " [as " << C.getNumBits() << " bit integer]"; break; } case nonloc::CompoundValKind: { const nonloc::CompoundVal& C = *cast<nonloc::CompoundVal>(this); Out << " {"; bool first = true; for (nonloc::CompoundVal::iterator I=C.begin(), E=C.end(); I!=E; ++I) { if (first) { Out << ' '; first = false; } else Out << ", "; (*I).print(Out); } Out << " }"; break; } default: assert (false && "Pretty-printed not implemented for this NonLoc."); break; } } void Loc::print(llvm::raw_ostream& Out) const { switch (getSubKind()) { case loc::ConcreteIntKind: Out << cast<loc::ConcreteInt>(this)->getValue().getZExtValue() << " (Loc)"; break; case loc::GotoLabelKind: Out << "&&" << cast<loc::GotoLabel>(this)->getLabel()->getID()->getName(); break; case loc::MemRegionKind: Out << '&' << cast<loc::MemRegionVal>(this)->getRegion()->getString(); break; case loc::FuncValKind: Out << "function " << cast<loc::FuncVal>(this)->getDecl()->getIdentifier()->getName(); break; default: assert (false && "Pretty-printing not implemented for this Loc."); break; } } <file_sep>/tools/driver/driver.cpp //===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the entry point to the clang driver; it is a thin wrapper // for functionality in the Driver clang library. // //===----------------------------------------------------------------------===// #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Option.h" #include "clang/Driver/Options.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Config/config.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Host.h" #include "llvm/System/Path.h" #include "llvm/System/Signals.h" using namespace clang; using namespace clang::driver; class DriverDiagnosticPrinter : public DiagnosticClient { std::string ProgName; llvm::raw_ostream &OS; public: DriverDiagnosticPrinter(const std::string _ProgName, llvm::raw_ostream &_OS) : ProgName(_ProgName), OS(_OS) {} virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info); }; void DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info) { OS << ProgName << ": "; switch (Level) { case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type"); case Diagnostic::Note: OS << "note: "; break; case Diagnostic::Warning: OS << "warning: "; break; case Diagnostic::Error: OS << "error: "; break; case Diagnostic::Fatal: OS << "fatal error: "; break; } llvm::SmallString<100> OutStr; Info.FormatDiagnostic(OutStr); OS.write(OutStr.begin(), OutStr.size()); OS << '\n'; } llvm::sys::Path GetExecutablePath(const char *Argv0) { // This just needs to be some symbol in the binary; C++ doesn't // allow taking the address of ::main however. void *P = (void*) (intptr_t) GetExecutablePath; return llvm::sys::Path::GetMainExecutable(Argv0, P); } int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); llvm::sys::Path Path = GetExecutablePath(argv[0]); llvm::OwningPtr<DiagnosticClient> DiagClient(new DriverDiagnosticPrinter(Path.getBasename(), llvm::errs())); Diagnostic Diags(DiagClient.get()); llvm::OwningPtr<Driver> TheDriver(new Driver(Path.getBasename().c_str(), Path.getDirname().c_str(), llvm::sys::getHostTriple().c_str(), "a.out", Diags)); llvm::OwningPtr<Compilation> C; // Handle CCC_ADD_ARGS, a comma separated list of extra arguments. std::set<std::string> SavedStrings; if (const char *Cur = ::getenv("CCC_ADD_ARGS")) { std::vector<const char*> StringPointers; // FIXME: Driver shouldn't take extra initial argument. StringPointers.push_back(argv[0]); for (;;) { const char *Next = strchr(Cur, ','); if (Next) { const char *P = SavedStrings.insert(std::string(Cur, Next)).first->c_str(); StringPointers.push_back(P); Cur = Next + 1; } else { if (*Cur != '\0') { const char *P = SavedStrings.insert(std::string(Cur)).first->c_str(); StringPointers.push_back(P); } break; } } StringPointers.insert(StringPointers.end(), argv + 1, argv + argc); C.reset(TheDriver->BuildCompilation(StringPointers.size(), &StringPointers[0])); } else C.reset(TheDriver->BuildCompilation(argc, argv)); int Res = 0; if (C.get()) Res = C->Execute(); llvm::llvm_shutdown(); return Res; } <file_sep>/tools/clang-cc/SerializationTest.cpp //===--- SerializationTest.cpp - Experimental Object Serialization --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements prototype code for serialization of objects in clang. // It is not intended yet for public use, but simply is a placeholder to // experiment with new serialization features. Serialization will eventually // be integrated as a proper component of the clang libraries. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CFG.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "clang-cc.h" #include "ASTConsumers.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/Support/Streams.h" #include "llvm/System/Path.h" #include <fstream> #include <cstring> using namespace clang; //===----------------------------------------------------------------------===// // Driver code. //===----------------------------------------------------------------------===// namespace { class SerializationTest : public ASTConsumer { Diagnostic &Diags; FileManager &FMgr; public: SerializationTest(Diagnostic &d, FileManager& fmgr) : Diags(d), FMgr(fmgr) {} ~SerializationTest() {} virtual void HandleTranslationUnit(ASTContext &C); private: bool Serialize(llvm::sys::Path& Filename, llvm::sys::Path& FNameDeclPrint, ASTContext &Ctx); bool Deserialize(llvm::sys::Path& Filename, llvm::sys::Path& FNameDeclPrint); }; } // end anonymous namespace ASTConsumer* clang::CreateSerializationTest(Diagnostic &Diags, FileManager& FMgr) { return new SerializationTest(Diags, FMgr); } bool SerializationTest::Serialize(llvm::sys::Path& Filename, llvm::sys::Path& FNameDeclPrint, ASTContext &Ctx) { { // Pretty-print the decls to a temp file. std::string Err; llvm::raw_fd_ostream DeclPP(FNameDeclPrint.c_str(), true, Err); assert (Err.empty() && "Could not open file for printing out decls."); llvm::OwningPtr<ASTConsumer> FilePrinter(CreateASTPrinter(&DeclPP)); TranslationUnitDecl *TUD = Ctx.getTranslationUnitDecl(); for (DeclContext::decl_iterator I = TUD->decls_begin(Ctx), E = TUD->decls_end(Ctx); I != E; ++I) FilePrinter->HandleTopLevelDecl(DeclGroupRef(*I)); } // Serialize the translation unit. // Reserve 256K for bitstream buffer. std::vector<unsigned char> Buffer; Buffer.reserve(256*1024); Ctx.EmitASTBitcodeBuffer(Buffer); // Write the bits to disk. if (FILE* fp = fopen(Filename.c_str(),"wb")) { fwrite((char*)&Buffer.front(), sizeof(char), Buffer.size(), fp); fclose(fp); return true; } return false; } bool SerializationTest::Deserialize(llvm::sys::Path& Filename, llvm::sys::Path& FNameDeclPrint) { // Deserialize the translation unit. ASTContext *NewCtx; { // Create the memory buffer that contains the contents of the file. llvm::OwningPtr<llvm::MemoryBuffer> MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str())); if (!MBuffer) return false; NewCtx = ASTContext::ReadASTBitcodeBuffer(*MBuffer, FMgr); } if (!NewCtx) return false; { // Pretty-print the deserialized decls to a temp file. std::string Err; llvm::raw_fd_ostream DeclPP(FNameDeclPrint.c_str(), true, Err); assert (Err.empty() && "Could not open file for printing out decls."); llvm::OwningPtr<ASTConsumer> FilePrinter(CreateASTPrinter(&DeclPP)); TranslationUnitDecl *TUD = NewCtx->getTranslationUnitDecl(); for (DeclContext::decl_iterator I = TUD->decls_begin(*NewCtx), E = TUD->decls_end(*NewCtx); I != E; ++I) FilePrinter->HandleTopLevelDecl(DeclGroupRef(*I)); } delete NewCtx; return true; } namespace { class TmpDirJanitor { llvm::sys::Path& Dir; public: explicit TmpDirJanitor(llvm::sys::Path& dir) : Dir(dir) {} ~TmpDirJanitor() { llvm::cerr << "Removing: " << Dir.c_str() << '\n'; Dir.eraseFromDisk(true); } }; } void SerializationTest::HandleTranslationUnit(ASTContext &Ctx) { std::string ErrMsg; llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); if (Dir.isEmpty()) { llvm::cerr << "Error: " << ErrMsg << "\n"; return; } TmpDirJanitor RemoveTmpOnExit(Dir); llvm::sys::Path FNameDeclBefore = Dir; FNameDeclBefore.appendComponent("test.decl_before.txt"); if (FNameDeclBefore.makeUnique(true, &ErrMsg)) { llvm::cerr << "Error: " << ErrMsg << "\n"; return; } llvm::sys::Path FNameDeclAfter = Dir; FNameDeclAfter.appendComponent("test.decl_after.txt"); if (FNameDeclAfter.makeUnique(true, &ErrMsg)) { llvm::cerr << "Error: " << ErrMsg << "\n"; return; } llvm::sys::Path ASTFilename = Dir; ASTFilename.appendComponent("test.ast"); if (ASTFilename.makeUnique(true, &ErrMsg)) { llvm::cerr << "Error: " << ErrMsg << "\n"; return; } // Serialize and then deserialize the ASTs. bool status = Serialize(ASTFilename, FNameDeclBefore, Ctx); assert (status && "Serialization failed."); status = Deserialize(ASTFilename, FNameDeclAfter); assert (status && "Deserialization failed."); // Read both pretty-printed files and compare them. using llvm::MemoryBuffer; llvm::OwningPtr<MemoryBuffer> MBufferSer(MemoryBuffer::getFile(FNameDeclBefore.c_str())); if(!MBufferSer) { llvm::cerr << "ERROR: Cannot read pretty-printed file (pre-pickle).\n"; return; } llvm::OwningPtr<MemoryBuffer> MBufferDSer(MemoryBuffer::getFile(FNameDeclAfter.c_str())); if(!MBufferDSer) { llvm::cerr << "ERROR: Cannot read pretty-printed file (post-pickle).\n"; return; } const char *p1 = MBufferSer->getBufferStart(); const char *e1 = MBufferSer->getBufferEnd(); const char *p2 = MBufferDSer->getBufferStart(); const char *e2 = MBufferDSer->getBufferEnd(); if (MBufferSer->getBufferSize() == MBufferDSer->getBufferSize()) for ( ; p1 != e1 ; ++p1, ++p2 ) if (*p1 != *p2) break; if (p1 != e1 || p2 != e2 ) llvm::cerr << "ERROR: Pretty-printed files are not the same.\n"; else llvm::cerr << "SUCCESS: Pretty-printed files are the same.\n"; } <file_sep>/lib/Sema/IdentifierResolver.cpp //===- IdentifierResolver.cpp - Lexical Scope Name lookup -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the IdentifierResolver class, which is used for lexical // scoped lookup, based on declaration names. // //===----------------------------------------------------------------------===// #include "IdentifierResolver.h" #include "clang/Basic/LangOptions.h" #include <list> #include <vector> using namespace clang; //===----------------------------------------------------------------------===// // IdDeclInfoMap class //===----------------------------------------------------------------------===// /// IdDeclInfoMap - Associates IdDeclInfos with declaration names. /// Allocates 'pools' (vectors of IdDeclInfos) to avoid allocating each /// individual IdDeclInfo to heap. class IdentifierResolver::IdDeclInfoMap { static const unsigned int VECTOR_SIZE = 512; // Holds vectors of IdDeclInfos that serve as 'pools'. // New vectors are added when the current one is full. std::list< std::vector<IdDeclInfo> > IDIVecs; unsigned int CurIndex; public: IdDeclInfoMap() : CurIndex(VECTOR_SIZE) {} /// Returns the IdDeclInfo associated to the DeclarationName. /// It creates a new IdDeclInfo if one was not created before for this id. IdDeclInfo &operator[](DeclarationName Name); }; //===----------------------------------------------------------------------===// // IdDeclInfo Implementation //===----------------------------------------------------------------------===// /// AddShadowed - Add a decl by putting it directly above the 'Shadow' decl. /// Later lookups will find the 'Shadow' decl first. The 'Shadow' decl must /// be already added to the scope chain and must be in the same context as /// the decl that we want to add. void IdentifierResolver::IdDeclInfo::AddShadowed(NamedDecl *D, NamedDecl *Shadow) { for (DeclsTy::iterator I = Decls.end(); I != Decls.begin(); --I) { if (Shadow == *(I-1)) { Decls.insert(I-1, D); return; } } assert(0 && "Shadow wasn't in scope chain!"); } /// RemoveDecl - Remove the decl from the scope chain. /// The decl must already be part of the decl chain. void IdentifierResolver::IdDeclInfo::RemoveDecl(NamedDecl *D) { for (DeclsTy::iterator I = Decls.end(); I != Decls.begin(); --I) { if (D == *(I-1)) { Decls.erase(I-1); return; } } assert(0 && "Didn't find this decl on its identifier's chain!"); } bool IdentifierResolver::IdDeclInfo::ReplaceDecl(NamedDecl *Old, NamedDecl *New) { for (DeclsTy::iterator I = Decls.end(); I != Decls.begin(); --I) { if (Old == *(I-1)) { *(I - 1) = New; return true; } } return false; } //===----------------------------------------------------------------------===// // IdentifierResolver Implementation //===----------------------------------------------------------------------===// IdentifierResolver::IdentifierResolver(const LangOptions &langOpt) : LangOpt(langOpt), IdDeclInfos(new IdDeclInfoMap) { } IdentifierResolver::~IdentifierResolver() { delete IdDeclInfos; } /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. bool IdentifierResolver::isDeclInScope(Decl *D, DeclContext *Ctx, ASTContext &Context, Scope *S) const { Ctx = Ctx->getLookupContext(); if (Ctx->isFunctionOrMethod()) { // Ignore the scopes associated within transparent declaration contexts. while (S->getEntity() && ((DeclContext *)S->getEntity())->isTransparentContext()) S = S->getParent(); if (S->isDeclScope(Action::DeclPtrTy::make(D))) return true; if (LangOpt.CPlusPlus) { // C++ 3.3.2p3: // The name declared in a catch exception-declaration is local to the // handler and shall not be redeclared in the outermost block of the // handler. // C++ 3.3.2p4: // Names declared in the for-init-statement, and in the condition of if, // while, for, and switch statements are local to the if, while, for, or // switch statement (including the controlled statement), and shall not be // redeclared in a subsequent condition of that statement nor in the // outermost block (or, for the if statement, any of the outermost blocks) // of the controlled statement. // assert(S->getParent() && "No TUScope?"); if (S->getParent()->getFlags() & Scope::ControlScope) return S->getParent()->isDeclScope(Action::DeclPtrTy::make(D)); } return false; } return D->getDeclContext()->getLookupContext() == Ctx->getPrimaryContext(); } /// AddDecl - Link the decl to its shadowed decl chain. void IdentifierResolver::AddDecl(NamedDecl *D) { DeclarationName Name = D->getDeclName(); void *Ptr = Name.getFETokenInfo<void>(); if (!Ptr) { Name.setFETokenInfo(D); return; } IdDeclInfo *IDI; if (isDeclPtr(Ptr)) { Name.setFETokenInfo(NULL); IDI = &(*IdDeclInfos)[Name]; NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr); IDI->AddDecl(PrevD); } else IDI = toIdDeclInfo(Ptr); IDI->AddDecl(D); } /// AddShadowedDecl - Link the decl to its shadowed decl chain putting it /// after the decl that the iterator points to, thus the 'Shadow' decl will be /// encountered before the 'D' decl. void IdentifierResolver::AddShadowedDecl(NamedDecl *D, NamedDecl *Shadow) { assert(D->getDeclName() == Shadow->getDeclName() && "Different ids!"); DeclarationName Name = D->getDeclName(); void *Ptr = Name.getFETokenInfo<void>(); assert(Ptr && "No decl from Ptr ?"); IdDeclInfo *IDI; if (isDeclPtr(Ptr)) { Name.setFETokenInfo(NULL); IDI = &(*IdDeclInfos)[Name]; NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr); assert(PrevD == Shadow && "Invalid shadow decl ?"); IDI->AddDecl(D); IDI->AddDecl(PrevD); return; } IDI = toIdDeclInfo(Ptr); IDI->AddShadowed(D, Shadow); } /// RemoveDecl - Unlink the decl from its shadowed decl chain. /// The decl must already be part of the decl chain. void IdentifierResolver::RemoveDecl(NamedDecl *D) { assert(D && "null param passed"); DeclarationName Name = D->getDeclName(); void *Ptr = Name.getFETokenInfo<void>(); assert(Ptr && "Didn't find this decl on its identifier's chain!"); if (isDeclPtr(Ptr)) { assert(D == Ptr && "Didn't find this decl on its identifier's chain!"); Name.setFETokenInfo(NULL); return; } return toIdDeclInfo(Ptr)->RemoveDecl(D); } bool IdentifierResolver::ReplaceDecl(NamedDecl *Old, NamedDecl *New) { assert(Old->getDeclName() == New->getDeclName() && "Cannot replace a decl with another decl of a different name"); DeclarationName Name = Old->getDeclName(); void *Ptr = Name.getFETokenInfo<void>(); if (!Ptr) return false; if (isDeclPtr(Ptr)) { if (Ptr == Old) { Name.setFETokenInfo(New); return true; } return false; } return toIdDeclInfo(Ptr)->ReplaceDecl(Old, New); } /// begin - Returns an iterator for decls with name 'Name'. IdentifierResolver::iterator IdentifierResolver::begin(DeclarationName Name) { void *Ptr = Name.getFETokenInfo<void>(); if (!Ptr) return end(); if (isDeclPtr(Ptr)) return iterator(static_cast<NamedDecl*>(Ptr)); IdDeclInfo *IDI = toIdDeclInfo(Ptr); IdDeclInfo::DeclsTy::iterator I = IDI->decls_end(); if (I != IDI->decls_begin()) return iterator(I-1); // No decls found. return end(); } //===----------------------------------------------------------------------===// // IdDeclInfoMap Implementation //===----------------------------------------------------------------------===// /// Returns the IdDeclInfo associated to the DeclarationName. /// It creates a new IdDeclInfo if one was not created before for this id. IdentifierResolver::IdDeclInfo & IdentifierResolver::IdDeclInfoMap::operator[](DeclarationName Name) { void *Ptr = Name.getFETokenInfo<void>(); if (Ptr) return *toIdDeclInfo(Ptr); if (CurIndex == VECTOR_SIZE) { // Add a IdDeclInfo vector 'pool' IDIVecs.push_back(std::vector<IdDeclInfo>()); // Fill the vector IDIVecs.back().resize(VECTOR_SIZE); CurIndex = 0; } IdDeclInfo *IDI = &IDIVecs.back()[CurIndex]; Name.setFETokenInfo(reinterpret_cast<void*>( reinterpret_cast<uintptr_t>(IDI) | 0x1) ); ++CurIndex; return *IDI; } <file_sep>/lib/Sema/SemaChecking.cpp //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements extra semantic analysis beyond what is enforced // by the C type system. // //===----------------------------------------------------------------------===// #include "Sema.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/Preprocessor.h" using namespace clang; /// getLocationOfStringLiteralByte - Return a source location that points to the /// specified byte of the specified string literal. /// /// Strings are amazingly complex. They can be formed from multiple tokens and /// can have escape sequences in them in addition to the usual trigraph and /// escaped newline business. This routine handles this complexity. /// SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const { assert(!SL->isWide() && "This doesn't work for wide strings yet"); // Loop over all of the tokens in this string until we find the one that // contains the byte we're looking for. unsigned TokNo = 0; while (1) { assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!"); SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo); // Get the spelling of the string so that we can get the data that makes up // the string literal, not the identifier for the macro it is potentially // expanded through. SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc); // Re-lex the token to get its length and original spelling. std::pair<FileID, unsigned> LocInfo = SourceMgr.getDecomposedLoc(StrTokSpellingLoc); std::pair<const char *,const char *> Buffer = SourceMgr.getBufferData(LocInfo.first); const char *StrData = Buffer.first+LocInfo.second; // Create a langops struct and enable trigraphs. This is sufficient for // relexing tokens. LangOptions LangOpts; LangOpts.Trigraphs = true; // Create a lexer starting at the beginning of this token. Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData, Buffer.second); Token TheTok; TheLexer.LexFromRawLexer(TheTok); // Use the StringLiteralParser to compute the length of the string in bytes. StringLiteralParser SLP(&TheTok, 1, PP); unsigned TokNumBytes = SLP.GetStringLength(); // If the byte is in this token, return the location of the byte. if (ByteNo < TokNumBytes || (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) { unsigned Offset = StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP); // Now that we know the offset of the token in the spelling, use the // preprocessor to get the offset in the original source. return PP.AdvanceToTokenCharacter(StrTokLoc, Offset); } // Move to the next string token. ++TokNo; ByteNo -= TokNumBytes; } } /// CheckFunctionCall - Check a direct function call for various correctness /// and safety properties not strictly enforced by the C type system. Action::OwningExprResult Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { OwningExprResult TheCallResult(Owned(TheCall)); // Get the IdentifierInfo* for the called function. IdentifierInfo *FnInfo = FDecl->getIdentifier(); // None of the checks below are needed for functions that don't have // simple names (e.g., C++ conversion functions). if (!FnInfo) return move(TheCallResult); switch (FDecl->getBuiltinID(Context)) { case Builtin::BI__builtin___CFStringMakeConstantString: assert(TheCall->getNumArgs() == 1 && "Wrong # arguments to builtin CFStringMakeConstantString"); if (CheckObjCString(TheCall->getArg(0))) return ExprError(); return move(TheCallResult); case Builtin::BI__builtin_stdarg_start: case Builtin::BI__builtin_va_start: if (SemaBuiltinVAStart(TheCall)) return ExprError(); return move(TheCallResult); case Builtin::BI__builtin_isgreater: case Builtin::BI__builtin_isgreaterequal: case Builtin::BI__builtin_isless: case Builtin::BI__builtin_islessequal: case Builtin::BI__builtin_islessgreater: case Builtin::BI__builtin_isunordered: if (SemaBuiltinUnorderedCompare(TheCall)) return ExprError(); return move(TheCallResult); case Builtin::BI__builtin_return_address: case Builtin::BI__builtin_frame_address: if (SemaBuiltinStackAddress(TheCall)) return ExprError(); return move(TheCallResult); case Builtin::BI__builtin_shufflevector: return SemaBuiltinShuffleVector(TheCall); // TheCall will be freed by the smart pointer here, but that's fine, since // SemaBuiltinShuffleVector guts it, but then doesn't release it. case Builtin::BI__builtin_prefetch: if (SemaBuiltinPrefetch(TheCall)) return ExprError(); return move(TheCallResult); case Builtin::BI__builtin_object_size: if (SemaBuiltinObjectSize(TheCall)) return ExprError(); } // FIXME: This mechanism should be abstracted to be less fragile and // more efficient. For example, just map function ids to custom // handlers. // Printf checking. if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) { if (Format->getType() == "printf") { bool HasVAListArg = Format->getFirstArg() == 0; if (!HasVAListArg) { if (const FunctionProtoType *Proto = FDecl->getType()->getAsFunctionProtoType()) HasVAListArg = !Proto->isVariadic(); } CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, HasVAListArg ? 0 : Format->getFirstArg() - 1); } } return move(TheCallResult); } /// CheckObjCString - Checks that the argument to the builtin /// CFString constructor is correct /// FIXME: GCC currently emits the following warning: /// "warning: input conversion stopped due to an input byte that does not /// belong to the input codeset UTF-8" /// Note: It might also make sense to do the UTF-16 conversion here (would /// simplify the backend). bool Sema::CheckObjCString(Expr *Arg) { Arg = Arg->IgnoreParenCasts(); StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); if (!Literal || Literal->isWide()) { Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) << Arg->getSourceRange(); return true; } const char *Data = Literal->getStrData(); unsigned Length = Literal->getByteLength(); for (unsigned i = 0; i < Length; ++i) { if (!Data[i]) { Diag(getLocationOfStringLiteralByte(Literal, i), diag::warn_cfstring_literal_contains_nul_character) << Arg->getSourceRange(); break; } } return false; } /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. /// Emit an error and return true on failure, return false on success. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { Expr *Fn = TheCall->getCallee(); if (TheCall->getNumArgs() > 2) { Diag(TheCall->getArg(2)->getLocStart(), diag::err_typecheck_call_too_many_args) << 0 /*function call*/ << Fn->getSourceRange() << SourceRange(TheCall->getArg(2)->getLocStart(), (*(TheCall->arg_end()-1))->getLocEnd()); return true; } if (TheCall->getNumArgs() < 2) { return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) << 0 /*function call*/; } // Determine whether the current function is variadic or not. bool isVariadic; if (CurBlock) isVariadic = CurBlock->isVariadic; else if (getCurFunctionDecl()) { if (FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType())) isVariadic = FTP->isVariadic(); else isVariadic = false; } else { isVariadic = getCurMethodDecl()->isVariadic(); } if (!isVariadic) { Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); return true; } // Verify that the second argument to the builtin is the last argument of the // current function or method. bool SecondArgIsLastNamedArgument = false; const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { // FIXME: This isn't correct for methods (results in bogus warning). // Get the last formal in the current function. const ParmVarDecl *LastArg; if (CurBlock) LastArg = *(CurBlock->TheDecl->param_end()-1); else if (FunctionDecl *FD = getCurFunctionDecl()) LastArg = *(FD->param_end()-1); else LastArg = *(getCurMethodDecl()->param_end()-1); SecondArgIsLastNamedArgument = PV == LastArg; } } if (!SecondArgIsLastNamedArgument) Diag(TheCall->getArg(1)->getLocStart(), diag::warn_second_parameter_of_va_start_not_last_named_argument); return false; } /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and /// friends. This is declared to take (...), so we have to check everything. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { if (TheCall->getNumArgs() < 2) return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) << 0 /*function call*/; if (TheCall->getNumArgs() > 2) return Diag(TheCall->getArg(2)->getLocStart(), diag::err_typecheck_call_too_many_args) << 0 /*function call*/ << SourceRange(TheCall->getArg(2)->getLocStart(), (*(TheCall->arg_end()-1))->getLocEnd()); Expr *OrigArg0 = TheCall->getArg(0); Expr *OrigArg1 = TheCall->getArg(1); // Do standard promotions between the two arguments, returning their common // type. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); // Make sure any conversions are pushed back into the call; this is // type safe since unordered compare builtins are declared as "_Bool // foo(...)". TheCall->setArg(0, OrigArg0); TheCall->setArg(1, OrigArg1); // If the common type isn't a real floating type, then the arguments were // invalid for this operation. if (!Res->isRealFloatingType()) return Diag(OrigArg0->getLocStart(), diag::err_typecheck_call_invalid_ordered_compare) << OrigArg0->getType() << OrigArg1->getType() << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()); return false; } bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) { // The signature for these builtins is exact; the only thing we need // to check is that the argument is a constant. SourceLocation Loc; if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange(); return false; } /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. // This is declared to take (...), so we have to check everything. Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { if (TheCall->getNumArgs() < 3) return ExprError(Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) << 0 /*function call*/ << TheCall->getSourceRange()); QualType FAType = TheCall->getArg(0)->getType(); QualType SAType = TheCall->getArg(1)->getType(); if (!FAType->isVectorType() || !SAType->isVectorType()) { Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) << SourceRange(TheCall->getArg(0)->getLocStart(), TheCall->getArg(1)->getLocEnd()); return ExprError(); } if (Context.getCanonicalType(FAType).getUnqualifiedType() != Context.getCanonicalType(SAType).getUnqualifiedType()) { Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) << SourceRange(TheCall->getArg(0)->getLocStart(), TheCall->getArg(1)->getLocEnd()); return ExprError(); } unsigned numElements = FAType->getAsVectorType()->getNumElements(); if (TheCall->getNumArgs() != numElements+2) { if (TheCall->getNumArgs() < numElements+2) return ExprError(Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) << 0 /*function call*/ << TheCall->getSourceRange()); return ExprError(Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) << 0 /*function call*/ << TheCall->getSourceRange()); } for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { llvm::APSInt Result(32); if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) return ExprError(Diag(TheCall->getLocStart(), diag::err_shufflevector_nonconstant_argument) << TheCall->getArg(i)->getSourceRange()); if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) return ExprError(Diag(TheCall->getLocStart(), diag::err_shufflevector_argument_too_large) << TheCall->getArg(i)->getSourceRange()); } llvm::SmallVector<Expr*, 32> exprs; for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { exprs.push_back(TheCall->getArg(i)); TheCall->setArg(i, 0); } return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2, FAType, TheCall->getCallee()->getLocStart(), TheCall->getRParenLoc())); } /// SemaBuiltinPrefetch - Handle __builtin_prefetch. // This is declared to take (const void*, ...) and can take two // optional constant int args. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { unsigned NumArgs = TheCall->getNumArgs(); if (NumArgs > 3) return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args) << 0 /*function call*/ << TheCall->getSourceRange(); // Argument 0 is checked for us and the remaining arguments must be // constant integers. for (unsigned i = 1; i != NumArgs; ++i) { Expr *Arg = TheCall->getArg(i); QualType RWType = Arg->getType(); const BuiltinType *BT = RWType->getAsBuiltinType(); llvm::APSInt Result; if (!BT || BT->getKind() != BuiltinType::Int || !Arg->isIntegerConstantExpr(Result, Context)) return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument) << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); // FIXME: gcc issues a warning and rewrites these to 0. These // seems especially odd for the third argument since the default // is 3. if (i == 1) { if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1) return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); } else { if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); } } return false; } /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, /// int type). This simply type checks that type is one of the defined /// constants (0-3). bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { Expr *Arg = TheCall->getArg(1); QualType ArgType = Arg->getType(); const BuiltinType *BT = ArgType->getAsBuiltinType(); llvm::APSInt Result(32); if (!BT || BT->getKind() != BuiltinType::Int || !Arg->isIntegerConstantExpr(Result, Context)) { return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument) << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); } if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); } return false; } // Handle i > 1 ? "x" : "y", recursivelly bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg) { switch (E->getStmtClass()) { case Stmt::ConditionalOperatorClass: { const ConditionalOperator *C = cast<ConditionalOperator>(E); return SemaCheckStringLiteral(C->getLHS(), TheCall, HasVAListArg, format_idx, firstDataArg) && SemaCheckStringLiteral(C->getRHS(), TheCall, HasVAListArg, format_idx, firstDataArg); } case Stmt::ImplicitCastExprClass: { const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E); return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, format_idx, firstDataArg); } case Stmt::ParenExprClass: { const ParenExpr *Expr = cast<ParenExpr>(E); return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg, format_idx, firstDataArg); } case Stmt::DeclRefExprClass: { const DeclRefExpr *DR = cast<DeclRefExpr>(E); // As an exception, do not flag errors for variables binding to // const string literals. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { bool isConstant = false; QualType T = DR->getType(); if (const ArrayType *AT = Context.getAsArrayType(T)) { isConstant = AT->getElementType().isConstant(Context); } else if (const PointerType *PT = T->getAsPointerType()) { isConstant = T.isConstant(Context) && PT->getPointeeType().isConstant(Context); } if (isConstant) { const VarDecl *Def = 0; if (const Expr *Init = VD->getDefinition(Def)) return SemaCheckStringLiteral(Init, TheCall, HasVAListArg, format_idx, firstDataArg); } } return false; } case Stmt::ObjCStringLiteralClass: case Stmt::StringLiteralClass: { const StringLiteral *StrE = NULL; if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) StrE = ObjCFExpr->getString(); else StrE = cast<StringLiteral>(E); if (StrE) { CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx, firstDataArg); return true; } return false; } default: return false; } } /// CheckPrintfArguments - Check calls to printf (and similar functions) for /// correct use of format strings. /// /// HasVAListArg - A predicate indicating whether the printf-like /// function is passed an explicit va_arg argument (e.g., vprintf) /// /// format_idx - The index into Args for the format string. /// /// Improper format strings to functions in the printf family can be /// the source of bizarre bugs and very serious security holes. A /// good source of information is available in the following paper /// (which includes additional references): /// /// FormatGuard: Automatic Protection From printf Format String /// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001. /// /// Functionality implemented: /// /// We can statically check the following properties for string /// literal format strings for non v.*printf functions (where the /// arguments are passed directly): // /// (1) Are the number of format conversions equal to the number of /// data arguments? /// /// (2) Does each format conversion correctly match the type of the /// corresponding data argument? (TODO) /// /// Moreover, for all printf functions we can: /// /// (3) Check for a missing format string (when not caught by type checking). /// /// (4) Check for no-operation flags; e.g. using "#" with format /// conversion 'c' (TODO) /// /// (5) Check the use of '%n', a major source of security holes. /// /// (6) Check for malformed format conversions that don't specify anything. /// /// (7) Check for empty format strings. e.g: printf(""); /// /// (8) Check that the format string is a wide literal. /// /// (9) Also check the arguments of functions with the __format__ attribute. /// (TODO). /// /// All of these checks can be done by parsing the format string. /// /// For now, we ONLY do (1), (3), (5), (6), (7), and (8). void Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg) { const Expr *Fn = TheCall->getCallee(); // CHECK: printf-like function is called with no format string. if (format_idx >= TheCall->getNumArgs()) { Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string) << Fn->getSourceRange(); return; } const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); // CHECK: format string is not a string literal. // // Dynamically generated format strings are difficult to // automatically vet at compile time. Requiring that format strings // are string literals: (1) permits the checking of format strings by // the compiler and thereby (2) can practically remove the source of // many format string exploits. // Format string can be either ObjC string (e.g. @"%d") or // C string (e.g. "%d") // ObjC string uses the same format specifiers as C string, so we can use // the same format string checking logic for both ObjC and C strings. bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, firstDataArg); if (!isFExpr) { // For vprintf* functions (i.e., HasVAListArg==true), we add a // special check to see if the format string is a function parameter // of the function calling the printf function. If the function // has an attribute indicating it is a printf-like function, then we // should suppress warnings concerning non-literals being used in a call // to a vprintf function. For example: // // void // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) { // va_list ap; // va_start(ap, fmt); // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". // ... // // // FIXME: We don't have full attribute support yet, so just check to see // if the argument is a DeclRefExpr that references a parameter. We'll // add proper support for checking the attribute later. if (HasVAListArg) if (const DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr)) if (isa<ParmVarDecl>(DR->getDecl())) return; Diag(TheCall->getArg(format_idx)->getLocStart(), diag::warn_printf_not_string_constant) << OrigFormatExpr->getSourceRange(); return; } } void Sema::CheckPrintfString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, const CallExpr *TheCall, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg) { const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr); // CHECK: is the format string a wide literal? if (FExpr->isWide()) { Diag(FExpr->getLocStart(), diag::warn_printf_format_string_is_wide_literal) << OrigFormatExpr->getSourceRange(); return; } // Str - The format string. NOTE: this is NOT null-terminated! const char * const Str = FExpr->getStrData(); // CHECK: empty format string? const unsigned StrLen = FExpr->getByteLength(); if (StrLen == 0) { Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string) << OrigFormatExpr->getSourceRange(); return; } // We process the format string using a binary state machine. The // current state is stored in CurrentState. enum { state_OrdChr, state_Conversion } CurrentState = state_OrdChr; // numConversions - The number of conversions seen so far. This is // incremented as we traverse the format string. unsigned numConversions = 0; // numDataArgs - The number of data arguments after the format // string. This can only be determined for non vprintf-like // functions. For those functions, this value is 1 (the sole // va_arg argument). unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg; // Inspect the format string. unsigned StrIdx = 0; // LastConversionIdx - Index within the format string where we last saw // a '%' character that starts a new format conversion. unsigned LastConversionIdx = 0; for (; StrIdx < StrLen; ++StrIdx) { // Is the number of detected conversion conversions greater than // the number of matching data arguments? If so, stop. if (!HasVAListArg && numConversions > numDataArgs) break; // Handle "\0" if (Str[StrIdx] == '\0') { // The string returned by getStrData() is not null-terminated, // so the presence of a null character is likely an error. Diag(getLocationOfStringLiteralByte(FExpr, StrIdx), diag::warn_printf_format_string_contains_null_char) << OrigFormatExpr->getSourceRange(); return; } // Ordinary characters (not processing a format conversion). if (CurrentState == state_OrdChr) { if (Str[StrIdx] == '%') { CurrentState = state_Conversion; LastConversionIdx = StrIdx; } continue; } // Seen '%'. Now processing a format conversion. switch (Str[StrIdx]) { // Handle dynamic precision or width specifier. case '*': { ++numConversions; if (!HasVAListArg && numConversions > numDataArgs) { SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx); if (Str[StrIdx-1] == '.') Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg) << OrigFormatExpr->getSourceRange(); else Diag(Loc, diag::warn_printf_asterisk_width_missing_arg) << OrigFormatExpr->getSourceRange(); // Don't do any more checking. We'll just emit spurious errors. return; } // Perform type checking on width/precision specifier. const Expr *E = TheCall->getArg(format_idx+numConversions); if (const BuiltinType *BT = E->getType()->getAsBuiltinType()) if (BT->getKind() == BuiltinType::Int) break; SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx); if (Str[StrIdx-1] == '.') Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type) << E->getType() << E->getSourceRange(); else Diag(Loc, diag::warn_printf_asterisk_width_wrong_type) << E->getType() << E->getSourceRange(); break; } // Characters which can terminate a format conversion // (e.g. "%d"). Characters that specify length modifiers or // other flags are handled by the default case below. // // FIXME: additional checks will go into the following cases. case 'i': case 'd': case 'o': case 'u': case 'x': case 'X': case 'D': case 'O': case 'U': case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case 'a': case 'A': case 'c': case 'C': case 'S': case 's': case 'p': ++numConversions; CurrentState = state_OrdChr; break; // CHECK: Are we using "%n"? Issue a warning. case 'n': { ++numConversions; CurrentState = state_OrdChr; SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, LastConversionIdx); Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange(); break; } // Handle "%@" case '@': // %@ is allowed in ObjC format strings only. if(ObjCFExpr != NULL) CurrentState = state_OrdChr; else { // Issue a warning: invalid format conversion. SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, LastConversionIdx); Diag(Loc, diag::warn_printf_invalid_conversion) << std::string(Str+LastConversionIdx, Str+std::min(LastConversionIdx+2, StrLen)) << OrigFormatExpr->getSourceRange(); } ++numConversions; break; // Handle "%%" case '%': // Sanity check: Was the first "%" character the previous one? // If not, we will assume that we have a malformed format // conversion, and that the current "%" character is the start // of a new conversion. if (StrIdx - LastConversionIdx == 1) CurrentState = state_OrdChr; else { // Issue a warning: invalid format conversion. SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, LastConversionIdx); Diag(Loc, diag::warn_printf_invalid_conversion) << std::string(Str+LastConversionIdx, Str+StrIdx) << OrigFormatExpr->getSourceRange(); // This conversion is broken. Advance to the next format // conversion. LastConversionIdx = StrIdx; ++numConversions; } break; default: // This case catches all other characters: flags, widths, etc. // We should eventually process those as well. break; } } if (CurrentState == state_Conversion) { // Issue a warning: invalid format conversion. SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, LastConversionIdx); Diag(Loc, diag::warn_printf_invalid_conversion) << std::string(Str+LastConversionIdx, Str+std::min(LastConversionIdx+2, StrLen)) << OrigFormatExpr->getSourceRange(); return; } if (!HasVAListArg) { // CHECK: Does the number of format conversions exceed the number // of data arguments? if (numConversions > numDataArgs) { SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, LastConversionIdx); Diag(Loc, diag::warn_printf_insufficient_data_args) << OrigFormatExpr->getSourceRange(); } // CHECK: Does the number of data arguments exceed the number of // format conversions in the format string? else if (numConversions < numDataArgs) Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(), diag::warn_printf_too_many_data_args) << OrigFormatExpr->getSourceRange(); } } //===--- CHECK: Return Address of Stack Variable --------------------------===// static DeclRefExpr* EvalVal(Expr *E); static DeclRefExpr* EvalAddr(Expr* E); /// CheckReturnStackAddr - Check if a return statement returns the address /// of a stack variable. void Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc) { // Perform checking for returned stack addresses. if (lhsType->isPointerType() || lhsType->isBlockPointerType()) { if (DeclRefExpr *DR = EvalAddr(RetValExp)) Diag(DR->getLocStart(), diag::warn_ret_stack_addr) << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); // Skip over implicit cast expressions when checking for block expressions. if (ImplicitCastExpr *IcExpr = dyn_cast_or_null<ImplicitCastExpr>(RetValExp)) RetValExp = IcExpr->getSubExpr(); if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp)) Diag(C->getLocStart(), diag::err_ret_local_block) << C->getSourceRange(); } // Perform checking for stack values returned by reference. else if (lhsType->isReferenceType()) { // Check for a reference to the stack if (DeclRefExpr *DR = EvalVal(RetValExp)) Diag(DR->getLocStart(), diag::warn_ret_stack_ref) << DR->getDecl()->getDeclName() << RetValExp->getSourceRange(); } } /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that /// check if the expression in a return statement evaluates to an address /// to a location on the stack. The recursion is used to traverse the /// AST of the return expression, with recursion backtracking when we /// encounter a subexpression that (1) clearly does not lead to the address /// of a stack variable or (2) is something we cannot determine leads to /// the address of a stack variable based on such local checking. /// /// EvalAddr processes expressions that are pointers that are used as /// references (and not L-values). EvalVal handles all other values. /// At the base case of the recursion is a check for a DeclRefExpr* in /// the refers to a stack variable. /// /// This implementation handles: /// /// * pointer-to-pointer casts /// * implicit conversions from array references to pointers /// * taking the address of fields /// * arbitrary interplay between "&" and "*" operators /// * pointer arithmetic from an address of a stack variable /// * taking the address of an array element where the array is on the stack static DeclRefExpr* EvalAddr(Expr *E) { // We should only be called for evaluating pointer expressions. assert((E->getType()->isPointerType() || E->getType()->isBlockPointerType() || E->getType()->isObjCQualifiedIdType()) && "EvalAddr only works on pointers"); // Our "symbolic interpreter" is just a dispatch off the currently // viewed AST node. We then recursively traverse the AST by calling // EvalAddr and EvalVal appropriately. switch (E->getStmtClass()) { case Stmt::ParenExprClass: // Ignore parentheses. return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); case Stmt::UnaryOperatorClass: { // The only unary operator that make sense to handle here // is AddrOf. All others don't make sense as pointers. UnaryOperator *U = cast<UnaryOperator>(E); if (U->getOpcode() == UnaryOperator::AddrOf) return EvalVal(U->getSubExpr()); else return NULL; } case Stmt::BinaryOperatorClass: { // Handle pointer arithmetic. All other binary operators are not valid // in this context. BinaryOperator *B = cast<BinaryOperator>(E); BinaryOperator::Opcode op = B->getOpcode(); if (op != BinaryOperator::Add && op != BinaryOperator::Sub) return NULL; Expr *Base = B->getLHS(); // Determine which argument is the real pointer base. It could be // the RHS argument instead of the LHS. if (!Base->getType()->isPointerType()) Base = B->getRHS(); assert (Base->getType()->isPointerType()); return EvalAddr(Base); } // For conditional operators we need to see if either the LHS or RHS are // valid DeclRefExpr*s. If one of them is valid, we return it. case Stmt::ConditionalOperatorClass: { ConditionalOperator *C = cast<ConditionalOperator>(E); // Handle the GNU extension for missing LHS. if (Expr *lhsExpr = C->getLHS()) if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) return LHS; return EvalAddr(C->getRHS()); } // For casts, we need to handle conversions from arrays to // pointer values, and pointer-to-pointer conversions. case Stmt::ImplicitCastExprClass: case Stmt::CStyleCastExprClass: case Stmt::CXXFunctionalCastExprClass: { Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); QualType T = SubExpr->getType(); if (SubExpr->getType()->isPointerType() || SubExpr->getType()->isBlockPointerType() || SubExpr->getType()->isObjCQualifiedIdType()) return EvalAddr(SubExpr); else if (T->isArrayType()) return EvalVal(SubExpr); else return 0; } // C++ casts. For dynamic casts, static casts, and const casts, we // are always converting from a pointer-to-pointer, so we just blow // through the cast. In the case the dynamic cast doesn't fail (and // return NULL), we take the conservative route and report cases // where we return the address of a stack variable. For Reinterpre // FIXME: The comment about is wrong; we're not always converting // from pointer to pointer. I'm guessing that this code should also // handle references to objects. case Stmt::CXXStaticCastExprClass: case Stmt::CXXDynamicCastExprClass: case Stmt::CXXConstCastExprClass: case Stmt::CXXReinterpretCastExprClass: { Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) return EvalAddr(S); else return NULL; } // Everything else: we simply don't reason about them. default: return NULL; } } /// EvalVal - This function is complements EvalAddr in the mutual recursion. /// See the comments for EvalAddr for more details. static DeclRefExpr* EvalVal(Expr *E) { // We should only be called for evaluating non-pointer expressions, or // expressions with a pointer type that are not used as references but instead // are l-values (e.g., DeclRefExpr with a pointer type). // Our "symbolic interpreter" is just a dispatch off the currently // viewed AST node. We then recursively traverse the AST by calling // EvalAddr and EvalVal appropriately. switch (E->getStmtClass()) { case Stmt::DeclRefExprClass: case Stmt::QualifiedDeclRefExprClass: { // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking // at code that refers to a variable's name. We check if it has local // storage within the function, and if so, return the expression. DeclRefExpr *DR = cast<DeclRefExpr>(E); if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR; return NULL; } case Stmt::ParenExprClass: // Ignore parentheses. return EvalVal(cast<ParenExpr>(E)->getSubExpr()); case Stmt::UnaryOperatorClass: { // The only unary operator that make sense to handle here // is Deref. All others don't resolve to a "name." This includes // handling all sorts of rvalues passed to a unary operator. UnaryOperator *U = cast<UnaryOperator>(E); if (U->getOpcode() == UnaryOperator::Deref) return EvalAddr(U->getSubExpr()); return NULL; } case Stmt::ArraySubscriptExprClass: { // Array subscripts are potential references to data on the stack. We // retrieve the DeclRefExpr* for the array variable if it indeed // has local storage. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); } case Stmt::ConditionalOperatorClass: { // For conditional operators we need to see if either the LHS or RHS are // non-NULL DeclRefExpr's. If one is non-NULL, we return it. ConditionalOperator *C = cast<ConditionalOperator>(E); // Handle the GNU extension for missing LHS. if (Expr *lhsExpr = C->getLHS()) if (DeclRefExpr *LHS = EvalVal(lhsExpr)) return LHS; return EvalVal(C->getRHS()); } // Accesses to members are potential references to data on the stack. case Stmt::MemberExprClass: { MemberExpr *M = cast<MemberExpr>(E); // Check for indirect access. We only want direct field accesses. if (!M->isArrow()) return EvalVal(M->getBase()); else return NULL; } // Everything else: we simply don't reason about them. default: return NULL; } } //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// /// Check for comparisons of floating point operands using != and ==. /// Issue a warning if these are no self-comparisons, as they are not likely /// to do what the programmer intended. void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { bool EmitWarning = true; Expr* LeftExprSansParen = lex->IgnoreParens(); Expr* RightExprSansParen = rex->IgnoreParens(); // Special case: check for x == x (which is OK). // Do not emit warnings for such cases. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) if (DRL->getDecl() == DRR->getDecl()) EmitWarning = false; // Special case: check for comparisons against literals that can be exactly // represented by APFloat. In such cases, do not emit a warning. This // is a heuristic: often comparison against such literals are used to // detect if a value in a variable has not changed. This clearly can // lead to false negatives. if (EmitWarning) { if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { if (FLL->isExact()) EmitWarning = false; } else if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ if (FLR->isExact()) EmitWarning = false; } } // Check for comparisons with builtin types. if (EmitWarning) if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) if (CL->isBuiltinCall(Context)) EmitWarning = false; if (EmitWarning) if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) if (CR->isBuiltinCall(Context)) EmitWarning = false; // Emit the diagnostic. if (EmitWarning) Diag(loc, diag::warn_floatingpoint_eq) << lex->getSourceRange() << rex->getSourceRange(); } <file_sep>/lib/Driver/ArgList.cpp //===--- ArgList.cpp - Argument List Management -------------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/ArgList.h" #include "clang/Driver/Arg.h" #include "clang/Driver/Option.h" using namespace clang::driver; ArgList::ArgList(arglist_type &_Args) : Args(_Args) { } ArgList::~ArgList() { } void ArgList::append(Arg *A) { Args.push_back(A); } Arg *ArgList::getLastArg(options::ID Id, bool Claim) const { // FIXME: Make search efficient? for (const_reverse_iterator it = rbegin(), ie = rend(); it != ie; ++it) { if ((*it)->getOption().matches(Id)) { if (Claim) (*it)->claim(); return *it; } } return 0; } Arg *ArgList::getLastArg(options::ID Id0, options::ID Id1, bool Claim) const { Arg *Res, *A0 = getLastArg(Id0, false), *A1 = getLastArg(Id1, false); if (A0 && A1) Res = A0->getIndex() > A1->getIndex() ? A0 : A1; else Res = A0 ? A0 : A1; if (Claim && Res) Res->claim(); return Res; } bool ArgList::hasFlag(options::ID Pos, options::ID Neg, bool Default) const { if (Arg *A = getLastArg(Pos, Neg)) return A->getOption().matches(Pos); return Default; } void ArgList::AddLastArg(ArgStringList &Output, options::ID Id) const { if (Arg *A = getLastArg(Id)) { A->claim(); A->render(*this, Output); } } void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(Id0)) { A->claim(); A->render(*this, Output); } } } void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(Id0) || A->getOption().matches(Id1)) { A->claim(); A->render(*this, Output); } } } void ArgList::AddAllArgs(ArgStringList &Output, options::ID Id0, options::ID Id1, options::ID Id2) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(Id0) || A->getOption().matches(Id1) || A->getOption().matches(Id2)) { A->claim(); A->render(*this, Output); } } } void ArgList::AddAllArgValues(ArgStringList &Output, options::ID Id0) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(Id0)) { A->claim(); for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) Output.push_back(A->getValue(*this, i)); } } } void ArgList::AddAllArgValues(ArgStringList &Output, options::ID Id0, options::ID Id1) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(Id0) || A->getOption().matches(Id1)) { A->claim(); for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) Output.push_back(A->getValue(*this, i)); } } } void ArgList::AddAllArgsTranslated(ArgStringList &Output, options::ID Id0, const char *Translation) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(Id0)) { A->claim(); Output.push_back(Translation); Output.push_back(A->getValue(*this, 0)); } } } void ArgList::ClaimAllArgs(options::ID Id0) const { // FIXME: Make fast. for (const_iterator it = begin(), ie = end(); it != ie; ++it) { const Arg *A = *it; if (A->getOption().matches(Id0)) A->claim(); } } // InputArgList::InputArgList(const char **ArgBegin, const char **ArgEnd) : ArgList(ActualArgs), NumInputArgStrings(ArgEnd - ArgBegin) { ArgStrings.append(ArgBegin, ArgEnd); } InputArgList::~InputArgList() { // An InputArgList always owns its arguments. for (iterator it = begin(), ie = end(); it != ie; ++it) delete *it; } unsigned InputArgList::MakeIndex(const char *String0) const { unsigned Index = ArgStrings.size(); // Tuck away so we have a reliable const char *. SynthesizedStrings.push_back(String0); ArgStrings.push_back(SynthesizedStrings.back().c_str()); return Index; } unsigned InputArgList::MakeIndex(const char *String0, const char *String1) const { unsigned Index0 = MakeIndex(String0); unsigned Index1 = MakeIndex(String1); assert(Index0 + 1 == Index1 && "Unexpected non-consecutive indices!"); (void) Index1; return Index0; } const char *InputArgList::MakeArgString(const char *Str) const { return getArgString(MakeIndex(Str)); } // DerivedArgList::DerivedArgList(InputArgList &_BaseArgs, bool _OnlyProxy) : ArgList(_OnlyProxy ? _BaseArgs.getArgs() : ActualArgs), BaseArgs(_BaseArgs), OnlyProxy(_OnlyProxy) { } DerivedArgList::~DerivedArgList() { // We only own the arguments we explicitly synthesized. for (iterator it = SynthesizedArgs.begin(), ie = SynthesizedArgs.end(); it != ie; ++it) delete *it; } const char *DerivedArgList::MakeArgString(const char *Str) const { return BaseArgs.MakeArgString(Str); } Arg *DerivedArgList::MakeFlagArg(const Arg *BaseArg, const Option *Opt) const { return new FlagArg(Opt, BaseArgs.MakeIndex(Opt->getName()), BaseArg); } Arg *DerivedArgList::MakePositionalArg(const Arg *BaseArg, const Option *Opt, const char *Value) const { return new PositionalArg(Opt, BaseArgs.MakeIndex(Value), BaseArg); } Arg *DerivedArgList::MakeSeparateArg(const Arg *BaseArg, const Option *Opt, const char *Value) const { return new SeparateArg(Opt, BaseArgs.MakeIndex(Opt->getName(), Value), 1, BaseArg); } Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option *Opt, const char *Value) const { std::string Joined(Opt->getName()); Joined += Value; return new JoinedArg(Opt, BaseArgs.MakeIndex(Joined.c_str()), BaseArg); } <file_sep>/lib/Driver/HostInfo.cpp //===--- HostInfo.cpp - Host specific information -----------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/HostInfo.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Option.h" #include "clang/Driver/Options.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Compiler.h" #include "ToolChains.h" #include <cassert> using namespace clang::driver; HostInfo::HostInfo(const Driver &D, const char *_Arch, const char *_Platform, const char *_OS) : TheDriver(D), Arch(_Arch), Platform(_Platform), OS(_OS) { } HostInfo::~HostInfo() { } namespace { // Darwin Host Info /// DarwinHostInfo - Darwin host information implementation. class DarwinHostInfo : public HostInfo { /// Darwin version of host. unsigned DarwinVersion[3]; /// GCC version to use on this host. unsigned GCCVersion[3]; /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain *> ToolChains; public: DarwinHostInfo(const Driver &D, const char *Arch, const char *Platform, const char *OS); ~DarwinHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { types::ID Ty = types::lookupTypeForExtension(Ext); // Darwin always preprocesses assembly files (unless -x is used // explicitly). if (Ty == types::TY_PP_Asm) return types::TY_Asm; return Ty; } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; DarwinHostInfo::DarwinHostInfo(const Driver &D, const char *_Arch, const char *_Platform, const char *_OS) : HostInfo(D, _Arch, _Platform, _OS) { assert((getArchName() == "i386" || getArchName() == "x86_64" || getArchName() == "powerpc" || getArchName() == "powerpc64") && "Unknown Darwin arch."); assert(memcmp(&getOSName()[0], "darwin", 6) == 0 && "Unknown Darwin platform."); const char *Release = &getOSName()[6]; bool HadExtra; if (!Driver::GetReleaseVersion(Release, DarwinVersion[0], DarwinVersion[1], DarwinVersion[2], HadExtra)) { D.Diag(clang::diag::err_drv_invalid_darwin_version) << Release; } // We can only call 4.2.1 for now. GCCVersion[0] = 4; GCCVersion[1] = 2; GCCVersion[2] = 1; } DarwinHostInfo::~DarwinHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool DarwinHostInfo::useDriverDriver() const { return true; } ToolChain *DarwinHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { if (!ArchName) { ArchName = getArchName().c_str(); // If no arch name is specified, infer it from the host and // -m32/-m64. if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { if (getArchName() == "i386" || getArchName() == "x86_64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "i386" : "x86_64"; } else if (getArchName() == "powerpc" || getArchName() == "powerpc64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "powerpc" : "powerpc64"; } } } else { // Normalize arch name; we shouldn't be doing this here. if (strcmp(ArchName, "ppc") == 0) ArchName = "powerpc"; else if (strcmp(ArchName, "ppc64") == 0) ArchName = "powerpc64"; } ToolChain *&TC = ToolChains[ArchName]; if (!TC) { if (strcmp(ArchName, "i386") == 0 || strcmp(ArchName, "x86_64") == 0) TC = new toolchains::Darwin_X86(*this, ArchName, getPlatformName().c_str(), getOSName().c_str(), DarwinVersion, GCCVersion); else TC = new toolchains::Darwin_GCC(*this, ArchName, getPlatformName().c_str(), getOSName().c_str()); } return TC; } // Unknown Host Info /// UnknownHostInfo - Generic host information to use for unknown /// hosts. class UnknownHostInfo : public HostInfo { /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain*> ToolChains; public: UnknownHostInfo(const Driver &D, const char *Arch, const char *Platform, const char *OS); ~UnknownHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; UnknownHostInfo::UnknownHostInfo(const Driver &D, const char *Arch, const char *Platform, const char *OS) : HostInfo(D, Arch, Platform, OS) { } UnknownHostInfo::~UnknownHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool UnknownHostInfo::useDriverDriver() const { return false; } ToolChain *UnknownHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { assert(!ArchName && "Unexpected arch name on platform without driver driver support."); // Automatically handle some instances of -m32/-m64 we know about. ArchName = getArchName().c_str(); if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { if (getArchName() == "i386" || getArchName() == "x86_64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "i386" : "x86_64"; } else if (getArchName() == "powerpc" || getArchName() == "powerpc64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "powerpc" : "powerpc64"; } } ToolChain *&TC = ToolChains[ArchName]; if (!TC) TC = new toolchains::Generic_GCC(*this, ArchName, getPlatformName().c_str(), getOSName().c_str()); return TC; } // FreeBSD Host Info /// FreeBSDHostInfo - FreeBSD host information implementation. class FreeBSDHostInfo : public HostInfo { /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain*> ToolChains; public: FreeBSDHostInfo(const Driver &D, const char *Arch, const char *Platform, const char *OS); ~FreeBSDHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; FreeBSDHostInfo::FreeBSDHostInfo(const Driver &D, const char *Arch, const char *Platform, const char *OS) : HostInfo(D, Arch, Platform, OS) { } FreeBSDHostInfo::~FreeBSDHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool FreeBSDHostInfo::useDriverDriver() const { return false; } ToolChain *FreeBSDHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { bool Lib32 = false; assert(!ArchName && "Unexpected arch name on platform without driver driver support."); // On x86_64 we need to be able to compile 32-bits binaries as well. // Compiling 64-bit binaries on i386 is not supported. We don't have a // lib64. ArchName = getArchName().c_str(); if (Args.hasArg(options::OPT_m32) && getArchName() == "x86_64") { ArchName = "i386"; Lib32 = true; } ToolChain *&TC = ToolChains[ArchName]; if (!TC) TC = new toolchains::FreeBSD(*this, ArchName, getPlatformName().c_str(), getOSName().c_str(), Lib32); return TC; } } const HostInfo *clang::driver::createDarwinHostInfo(const Driver &D, const char *Arch, const char *Platform, const char *OS) { return new DarwinHostInfo(D, Arch, Platform, OS); } const HostInfo *clang::driver::createFreeBSDHostInfo(const Driver &D, const char *Arch, const char *Platform, const char *OS) { return new FreeBSDHostInfo(D, Arch, Platform, OS); } const HostInfo *clang::driver::createUnknownHostInfo(const Driver &D, const char *Arch, const char *Platform, const char *OS) { return new UnknownHostInfo(D, Arch, Platform, OS); } <file_sep>/lib/Analysis/GRExprEngine.cpp //=-- GRExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-= // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a meta-engine for path-sensitive dataflow analysis that // is built on GREngine, but provides the boilerplate to execute transfer // functions and build the ExplodedGraph at the expression level. // //===----------------------------------------------------------------------===// #include "clang/AST/ParentMap.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" #include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h" #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/PrettyStackTrace.h" #include "llvm/Support/Streams.h" #include "llvm/ADT/ImmutableList.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #ifndef NDEBUG #include "llvm/Support/GraphWriter.h" #include <sstream> #endif using namespace clang; using llvm::dyn_cast; using llvm::cast; using llvm::APSInt; //===----------------------------------------------------------------------===// // Engine construction and deletion. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN MappedBatchAuditor : public GRSimpleAPICheck { typedef llvm::ImmutableList<GRSimpleAPICheck*> Checks; typedef llvm::DenseMap<void*,Checks> MapTy; MapTy M; Checks::Factory F; Checks AllStmts; public: MappedBatchAuditor(llvm::BumpPtrAllocator& Alloc) : F(Alloc), AllStmts(F.GetEmptyList()) {} virtual ~MappedBatchAuditor() { llvm::DenseSet<GRSimpleAPICheck*> AlreadyVisited; for (MapTy::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI) for (Checks::iterator I=MI->second.begin(), E=MI->second.end(); I!=E;++I){ GRSimpleAPICheck* check = *I; if (AlreadyVisited.count(check)) continue; AlreadyVisited.insert(check); delete check; } } void AddCheck(GRSimpleAPICheck *A, Stmt::StmtClass C) { assert (A && "Check cannot be null."); void* key = reinterpret_cast<void*>((uintptr_t) C); MapTy::iterator I = M.find(key); M[key] = F.Concat(A, I == M.end() ? F.GetEmptyList() : I->second); } void AddCheck(GRSimpleAPICheck *A) { assert (A && "Check cannot be null."); AllStmts = F.Concat(A, AllStmts); } virtual bool Audit(NodeTy* N, GRStateManager& VMgr) { // First handle the auditors that accept all statements. bool isSink = false; for (Checks::iterator I = AllStmts.begin(), E = AllStmts.end(); I!=E; ++I) isSink |= (*I)->Audit(N, VMgr); // Next handle the auditors that accept only specific statements. Stmt* S = cast<PostStmt>(N->getLocation()).getStmt(); void* key = reinterpret_cast<void*>((uintptr_t) S->getStmtClass()); MapTy::iterator MI = M.find(key); if (MI != M.end()) { for (Checks::iterator I=MI->second.begin(), E=MI->second.end(); I!=E; ++I) isSink |= (*I)->Audit(N, VMgr); } return isSink; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Engine construction and deletion. //===----------------------------------------------------------------------===// static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) { IdentifierInfo* II = &Ctx.Idents.get(name); return Ctx.Selectors.getSelector(0, &II); } GRExprEngine::GRExprEngine(CFG& cfg, Decl& CD, ASTContext& Ctx, LiveVariables& L, BugReporterData& BRD, bool purgeDead, bool eagerlyAssume, StoreManagerCreator SMC, ConstraintManagerCreator CMC) : CoreEngine(cfg, CD, Ctx, *this), G(CoreEngine.getGraph()), Liveness(L), Builder(NULL), StateMgr(G.getContext(), SMC, CMC, G.getAllocator(), cfg, CD, L), SymMgr(StateMgr.getSymbolManager()), ValMgr(StateMgr.getValueManager()), CurrentStmt(NULL), NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL), RaiseSel(GetNullarySelector("raise", G.getContext())), PurgeDead(purgeDead), BR(BRD, *this), EagerlyAssume(eagerlyAssume) {} GRExprEngine::~GRExprEngine() { BR.FlushReports(); delete [] NSExceptionInstanceRaiseSelectors; } //===----------------------------------------------------------------------===// // Utility methods. //===----------------------------------------------------------------------===// void GRExprEngine::setTransferFunctions(GRTransferFuncs* tf) { StateMgr.TF = tf; tf->RegisterChecks(getBugReporter()); tf->RegisterPrinters(getStateManager().Printers); } void GRExprEngine::AddCheck(GRSimpleAPICheck* A, Stmt::StmtClass C) { if (!BatchAuditor) BatchAuditor.reset(new MappedBatchAuditor(getGraph().getAllocator())); ((MappedBatchAuditor*) BatchAuditor.get())->AddCheck(A, C); } void GRExprEngine::AddCheck(GRSimpleAPICheck *A) { if (!BatchAuditor) BatchAuditor.reset(new MappedBatchAuditor(getGraph().getAllocator())); ((MappedBatchAuditor*) BatchAuditor.get())->AddCheck(A); } const GRState* GRExprEngine::getInitialState() { const GRState *state = StateMgr.getInitialState(); // Precondition: the first argument of 'main' is an integer guaranteed // to be > 0. // FIXME: It would be nice if we had a more general mechanism to add // such preconditions. Some day. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(&StateMgr.getCodeDecl())) if (strcmp(FD->getIdentifier()->getName(), "main") == 0 && FD->getNumParams() > 0) { const ParmVarDecl *PD = FD->getParamDecl(0); QualType T = PD->getType(); if (T->isIntegerType()) if (const MemRegion *R = StateMgr.getRegion(PD)) { SVal V = GetSVal(state, loc::MemRegionVal(R)); SVal Constraint = EvalBinOp(BinaryOperator::GT, V, ValMgr.makeZeroVal(T), getContext().IntTy); bool isFeasible = false; const GRState *newState = Assume(state, Constraint, true, isFeasible); if (newState) state = newState; } } return state; } //===----------------------------------------------------------------------===// // Top-level transfer function logic (Dispatcher). //===----------------------------------------------------------------------===// void GRExprEngine::ProcessStmt(Stmt* S, StmtNodeBuilder& builder) { PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), S->getLocStart(), "Error evaluating statement"); Builder = &builder; EntryNode = builder.getLastNode(); // FIXME: Consolidate. CurrentStmt = S; StateMgr.CurrentStmt = S; // Set up our simple checks. if (BatchAuditor) Builder->setAuditor(BatchAuditor.get()); // Create the cleaned state. SymbolReaper SymReaper(Liveness, SymMgr); CleanedState = PurgeDead ? StateMgr.RemoveDeadBindings(EntryNode->getState(), CurrentStmt, SymReaper) : EntryNode->getState(); // Process any special transfer function for dead symbols. NodeSet Tmp; if (!SymReaper.hasDeadSymbols()) Tmp.Add(EntryNode); else { SaveAndRestore<bool> OldSink(Builder->BuildSinks); SaveOr OldHasGen(Builder->HasGeneratedNode); SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols); Builder->PurgingDeadSymbols = true; getTF().EvalDeadSymbols(Tmp, *this, *Builder, EntryNode, S, CleanedState, SymReaper); if (!Builder->BuildSinks && !Builder->HasGeneratedNode) Tmp.Add(EntryNode); } bool HasAutoGenerated = false; for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { NodeSet Dst; // Set the cleaned state. Builder->SetCleanedState(*I == EntryNode ? CleanedState : GetState(*I)); // Visit the statement. Visit(S, *I, Dst); // Do we need to auto-generate a node? We only need to do this to generate // a node with a "cleaned" state; GRCoreEngine will actually handle // auto-transitions for other cases. if (Dst.size() == 1 && *Dst.begin() == EntryNode && !Builder->HasGeneratedNode && !HasAutoGenerated) { HasAutoGenerated = true; builder.generateNode(S, GetState(EntryNode), *I); } } // NULL out these variables to cleanup. CleanedState = NULL; EntryNode = NULL; // FIXME: Consolidate. StateMgr.CurrentStmt = 0; CurrentStmt = 0; Builder = NULL; } void GRExprEngine::Visit(Stmt* S, NodeTy* Pred, NodeSet& Dst) { PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), S->getLocStart(), "Error evaluating statement"); // FIXME: add metadata to the CFG so that we can disable // this check when we KNOW that there is no block-level subexpression. // The motivation is that this check requires a hashtable lookup. if (S != CurrentStmt && getCFG().isBlkExpr(S)) { Dst.Add(Pred); return; } switch (S->getStmtClass()) { default: // Cases we intentionally have "default" handle: // AddrLabelExpr, IntegerLiteral, CharacterLiteral Dst.Add(Pred); // No-op. Simply propagate the current state unchanged. break; case Stmt::ArraySubscriptExprClass: VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst, false); break; case Stmt::AsmStmtClass: VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst); break; case Stmt::BinaryOperatorClass: { BinaryOperator* B = cast<BinaryOperator>(S); if (B->isLogicalOp()) { VisitLogicalExpr(B, Pred, Dst); break; } else if (B->getOpcode() == BinaryOperator::Comma) { const GRState* state = GetState(Pred); MakeNode(Dst, B, Pred, BindExpr(state, B, GetSVal(state, B->getRHS()))); break; } if (EagerlyAssume && (B->isRelationalOp() || B->isEqualityOp())) { NodeSet Tmp; VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp); EvalEagerlyAssume(Dst, Tmp, cast<Expr>(S)); } else VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); break; } case Stmt::CallExprClass: case Stmt::CXXOperatorCallExprClass: { CallExpr* C = cast<CallExpr>(S); VisitCall(C, Pred, C->arg_begin(), C->arg_end(), Dst); break; } // FIXME: ChooseExpr is really a constant. We need to fix // the CFG do not model them as explicit control-flow. case Stmt::ChooseExprClass: { // __builtin_choose_expr ChooseExpr* C = cast<ChooseExpr>(S); VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); break; } case Stmt::CompoundAssignOperatorClass: VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst); break; case Stmt::CompoundLiteralExprClass: VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst, false); break; case Stmt::ConditionalOperatorClass: { // '?' operator ConditionalOperator* C = cast<ConditionalOperator>(S); VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst); break; } case Stmt::DeclRefExprClass: case Stmt::QualifiedDeclRefExprClass: VisitDeclRefExpr(cast<DeclRefExpr>(S), Pred, Dst, false); break; case Stmt::DeclStmtClass: VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst); break; case Stmt::ImplicitCastExprClass: case Stmt::CStyleCastExprClass: { CastExpr* C = cast<CastExpr>(S); VisitCast(C, C->getSubExpr(), Pred, Dst); break; } case Stmt::InitListExprClass: VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst); break; case Stmt::MemberExprClass: VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst, false); break; case Stmt::ObjCIvarRefExprClass: VisitObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst, false); break; case Stmt::ObjCForCollectionStmtClass: VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst); break; case Stmt::ObjCMessageExprClass: { VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), Pred, Dst); break; } case Stmt::ObjCAtThrowStmtClass: { // FIXME: This is not complete. We basically treat @throw as // an abort. SaveAndRestore<bool> OldSink(Builder->BuildSinks); Builder->BuildSinks = true; MakeNode(Dst, S, Pred, GetState(Pred)); break; } case Stmt::ParenExprClass: Visit(cast<ParenExpr>(S)->getSubExpr()->IgnoreParens(), Pred, Dst); break; case Stmt::ReturnStmtClass: VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst); break; case Stmt::SizeOfAlignOfExprClass: VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), Pred, Dst); break; case Stmt::StmtExprClass: { StmtExpr* SE = cast<StmtExpr>(S); if (SE->getSubStmt()->body_empty()) { // Empty statement expression. assert(SE->getType() == getContext().VoidTy && "Empty statement expression must have void type."); Dst.Add(Pred); break; } if (Expr* LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) { const GRState* state = GetState(Pred); MakeNode(Dst, SE, Pred, BindExpr(state, SE, GetSVal(state, LastExpr))); } else Dst.Add(Pred); break; } case Stmt::StringLiteralClass: VisitLValue(cast<StringLiteral>(S), Pred, Dst); break; case Stmt::UnaryOperatorClass: { UnaryOperator *U = cast<UnaryOperator>(S); if (EagerlyAssume && (U->getOpcode() == UnaryOperator::LNot)) { NodeSet Tmp; VisitUnaryOperator(U, Pred, Tmp, false); EvalEagerlyAssume(Dst, Tmp, U); } else VisitUnaryOperator(U, Pred, Dst, false); break; } } } void GRExprEngine::VisitLValue(Expr* Ex, NodeTy* Pred, NodeSet& Dst) { Ex = Ex->IgnoreParens(); if (Ex != CurrentStmt && getCFG().isBlkExpr(Ex)) { Dst.Add(Pred); return; } switch (Ex->getStmtClass()) { case Stmt::ArraySubscriptExprClass: VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(Ex), Pred, Dst, true); return; case Stmt::DeclRefExprClass: case Stmt::QualifiedDeclRefExprClass: VisitDeclRefExpr(cast<DeclRefExpr>(Ex), Pred, Dst, true); return; case Stmt::ObjCIvarRefExprClass: VisitObjCIvarRefExpr(cast<ObjCIvarRefExpr>(Ex), Pred, Dst, true); return; case Stmt::UnaryOperatorClass: VisitUnaryOperator(cast<UnaryOperator>(Ex), Pred, Dst, true); return; case Stmt::MemberExprClass: VisitMemberExpr(cast<MemberExpr>(Ex), Pred, Dst, true); return; case Stmt::CompoundLiteralExprClass: VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(Ex), Pred, Dst, true); return; case Stmt::ObjCPropertyRefExprClass: // FIXME: Property assignments are lvalues, but not really "locations". // e.g.: self.x = something; // Here the "self.x" really can translate to a method call (setter) when // the assignment is made. Moreover, the entire assignment expression // evaluate to whatever "something" is, not calling the "getter" for // the property (which would make sense since it can have side effects). // We'll probably treat this as a location, but not one that we can // take the address of. Perhaps we need a new SVal class for cases // like thsis? // Note that we have a similar problem for bitfields, since they don't // have "locations" in the sense that we can take their address. Dst.Add(Pred); return; case Stmt::StringLiteralClass: { const GRState* state = GetState(Pred); SVal V = StateMgr.GetLValue(state, cast<StringLiteral>(Ex)); MakeNode(Dst, Ex, Pred, BindExpr(state, Ex, V)); return; } default: // Arbitrary subexpressions can return aggregate temporaries that // can be used in a lvalue context. We need to enhance our support // of such temporaries in both the environment and the store, so right // now we just do a regular visit. assert ((Ex->getType()->isAggregateType()) && "Other kinds of expressions with non-aggregate/union types do" " not have lvalues."); Visit(Ex, Pred, Dst); } } //===----------------------------------------------------------------------===// // Block entrance. (Update counters). //===----------------------------------------------------------------------===// bool GRExprEngine::ProcessBlockEntrance(CFGBlock* B, const GRState*, GRBlockCounter BC) { return BC.getNumVisited(B->getBlockID()) < 3; } //===----------------------------------------------------------------------===// // Generic node creation. //===----------------------------------------------------------------------===// GRExprEngine::NodeTy* GRExprEngine::MakeNode(NodeSet& Dst, Stmt* S, NodeTy* Pred, const GRState* St, ProgramPoint::Kind K, const void *tag) { assert (Builder && "GRStmtNodeBuilder not present."); SaveAndRestore<const void*> OldTag(Builder->Tag); Builder->Tag = tag; return Builder->MakeNode(Dst, S, Pred, St, K); } //===----------------------------------------------------------------------===// // Branch processing. //===----------------------------------------------------------------------===// const GRState* GRExprEngine::MarkBranch(const GRState* state, Stmt* Terminator, bool branchTaken) { switch (Terminator->getStmtClass()) { default: return state; case Stmt::BinaryOperatorClass: { // '&&' and '||' BinaryOperator* B = cast<BinaryOperator>(Terminator); BinaryOperator::Opcode Op = B->getOpcode(); assert (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr); // For &&, if we take the true branch, then the value of the whole // expression is that of the RHS expression. // // For ||, if we take the false branch, then the value of the whole // expression is that of the RHS expression. Expr* Ex = (Op == BinaryOperator::LAnd && branchTaken) || (Op == BinaryOperator::LOr && !branchTaken) ? B->getRHS() : B->getLHS(); return BindBlkExpr(state, B, UndefinedVal(Ex)); } case Stmt::ConditionalOperatorClass: { // ?: ConditionalOperator* C = cast<ConditionalOperator>(Terminator); // For ?, if branchTaken == true then the value is either the LHS or // the condition itself. (GNU extension). Expr* Ex; if (branchTaken) Ex = C->getLHS() ? C->getLHS() : C->getCond(); else Ex = C->getRHS(); return BindBlkExpr(state, C, UndefinedVal(Ex)); } case Stmt::ChooseExprClass: { // ?: ChooseExpr* C = cast<ChooseExpr>(Terminator); Expr* Ex = branchTaken ? C->getLHS() : C->getRHS(); return BindBlkExpr(state, C, UndefinedVal(Ex)); } } } /// RecoverCastedSymbol - A helper function for ProcessBranch that is used /// to try to recover some path-sensitivity for casts of symbolic /// integers that promote their values (which are currently not tracked well). /// This function returns the SVal bound to Condition->IgnoreCasts if all the // cast(s) did was sign-extend the original value. static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state, Stmt* Condition, ASTContext& Ctx) { Expr *Ex = dyn_cast<Expr>(Condition); if (!Ex) return UnknownVal(); uint64_t bits = 0; bool bitsInit = false; while (CastExpr *CE = dyn_cast<CastExpr>(Ex)) { QualType T = CE->getType(); if (!T->isIntegerType()) return UnknownVal(); uint64_t newBits = Ctx.getTypeSize(T); if (!bitsInit || newBits < bits) { bitsInit = true; bits = newBits; } Ex = CE->getSubExpr(); } // We reached a non-cast. Is it a symbolic value? QualType T = Ex->getType(); if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits) return UnknownVal(); return StateMgr.GetSVal(state, Ex); } void GRExprEngine::ProcessBranch(Stmt* Condition, Stmt* Term, BranchNodeBuilder& builder) { // Remove old bindings for subexpressions. const GRState* PrevState = StateMgr.RemoveSubExprBindings(builder.getState()); // Check for NULL conditions; e.g. "for(;;)" if (!Condition) { builder.markInfeasible(false); return; } PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), Condition->getLocStart(), "Error evaluating branch"); SVal V = GetSVal(PrevState, Condition); switch (V.getBaseKind()) { default: break; case SVal::UnknownKind: { if (Expr *Ex = dyn_cast<Expr>(Condition)) { if (Ex->getType()->isIntegerType()) { // Try to recover some path-sensitivity. Right now casts of symbolic // integers that promote their values are currently not tracked well. // If 'Condition' is such an expression, try and recover the // underlying value and use that instead. SVal recovered = RecoverCastedSymbol(getStateManager(), builder.getState(), Condition, getContext()); if (!recovered.isUnknown()) { V = recovered; break; } } } builder.generateNode(MarkBranch(PrevState, Term, true), true); builder.generateNode(MarkBranch(PrevState, Term, false), false); return; } case SVal::UndefinedKind: { NodeTy* N = builder.generateNode(PrevState, true); if (N) { N->markAsSink(); UndefBranches.insert(N); } builder.markInfeasible(false); return; } } // Process the true branch. bool isFeasible = false; const GRState* state = Assume(PrevState, V, true, isFeasible); if (isFeasible) builder.generateNode(MarkBranch(state, Term, true), true); else builder.markInfeasible(true); // Process the false branch. isFeasible = false; state = Assume(PrevState, V, false, isFeasible); if (isFeasible) builder.generateNode(MarkBranch(state, Term, false), false); else builder.markInfeasible(false); } /// ProcessIndirectGoto - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a computed goto jump. void GRExprEngine::ProcessIndirectGoto(IndirectGotoNodeBuilder& builder) { const GRState* state = builder.getState(); SVal V = GetSVal(state, builder.getTarget()); // Three possibilities: // // (1) We know the computed label. // (2) The label is NULL (or some other constant), or Undefined. // (3) We have no clue about the label. Dispatch to all targets. // typedef IndirectGotoNodeBuilder::iterator iterator; if (isa<loc::GotoLabel>(V)) { LabelStmt* L = cast<loc::GotoLabel>(V).getLabel(); for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) { if (I.getLabel() == L) { builder.generateNode(I, state); return; } } assert (false && "No block with label."); return; } if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) { // Dispatch to the first target and mark it as a sink. NodeTy* N = builder.generateNode(builder.begin(), state, true); UndefBranches.insert(N); return; } // This is really a catch-all. We don't support symbolics yet. assert (V.isUnknown()); for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) builder.generateNode(I, state); } void GRExprEngine::VisitGuardedExpr(Expr* Ex, Expr* L, Expr* R, NodeTy* Pred, NodeSet& Dst) { assert (Ex == CurrentStmt && getCFG().isBlkExpr(Ex)); const GRState* state = GetState(Pred); SVal X = GetBlkExprSVal(state, Ex); assert (X.isUndef()); Expr* SE = (Expr*) cast<UndefinedVal>(X).getData(); assert (SE); X = GetBlkExprSVal(state, SE); // Make sure that we invalidate the previous binding. MakeNode(Dst, Ex, Pred, StateMgr.BindExpr(state, Ex, X, true, true)); } /// ProcessSwitch - Called by GRCoreEngine. Used to generate successor /// nodes by processing the 'effects' of a switch statement. void GRExprEngine::ProcessSwitch(SwitchNodeBuilder& builder) { typedef SwitchNodeBuilder::iterator iterator; const GRState* state = builder.getState(); Expr* CondE = builder.getCondition(); SVal CondV = GetSVal(state, CondE); if (CondV.isUndef()) { NodeTy* N = builder.generateDefaultCaseNode(state, true); UndefBranches.insert(N); return; } const GRState* DefaultSt = state; bool DefaultFeasible = false; for (iterator I = builder.begin(), EI = builder.end(); I != EI; ++I) { CaseStmt* Case = cast<CaseStmt>(I.getCase()); // Evaluate the LHS of the case value. Expr::EvalResult V1; bool b = Case->getLHS()->Evaluate(V1, getContext()); // Sanity checks. These go away in Release builds. assert(b && V1.Val.isInt() && !V1.HasSideEffects && "Case condition must evaluate to an integer constant."); b = b; // silence unused variable warning assert(V1.Val.getInt().getBitWidth() == getContext().getTypeSize(CondE->getType())); // Get the RHS of the case, if it exists. Expr::EvalResult V2; if (Expr* E = Case->getRHS()) { b = E->Evaluate(V2, getContext()); assert(b && V2.Val.isInt() && !V2.HasSideEffects && "Case condition must evaluate to an integer constant."); b = b; // silence unused variable warning } else V2 = V1; // FIXME: Eventually we should replace the logic below with a range // comparison, rather than concretize the values within the range. // This should be easy once we have "ranges" for NonLVals. do { nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt())); SVal Res = EvalBinOp(BinaryOperator::EQ, CondV, CaseVal, getContext().IntTy); // Now "assume" that the case matches. bool isFeasible = false; const GRState* StNew = Assume(state, Res, true, isFeasible); if (isFeasible) { builder.generateCaseStmtNode(I, StNew); // If CondV evaluates to a constant, then we know that this // is the *only* case that we can take, so stop evaluating the // others. if (isa<nonloc::ConcreteInt>(CondV)) return; } // Now "assume" that the case doesn't match. Add this state // to the default state (if it is feasible). isFeasible = false; StNew = Assume(DefaultSt, Res, false, isFeasible); if (isFeasible) { DefaultFeasible = true; DefaultSt = StNew; } // Concretize the next value in the range. if (V1.Val.getInt() == V2.Val.getInt()) break; ++V1.Val.getInt(); assert (V1.Val.getInt() <= V2.Val.getInt()); } while (true); } // If we reach here, than we know that the default branch is // possible. if (DefaultFeasible) builder.generateDefaultCaseNode(DefaultSt); } //===----------------------------------------------------------------------===// // Transfer functions: logical operations ('&&', '||'). //===----------------------------------------------------------------------===// void GRExprEngine::VisitLogicalExpr(BinaryOperator* B, NodeTy* Pred, NodeSet& Dst) { assert (B->getOpcode() == BinaryOperator::LAnd || B->getOpcode() == BinaryOperator::LOr); assert (B == CurrentStmt && getCFG().isBlkExpr(B)); const GRState* state = GetState(Pred); SVal X = GetBlkExprSVal(state, B); assert (X.isUndef()); Expr* Ex = (Expr*) cast<UndefinedVal>(X).getData(); assert (Ex); if (Ex == B->getRHS()) { X = GetBlkExprSVal(state, Ex); // Handle undefined values. if (X.isUndef()) { MakeNode(Dst, B, Pred, BindBlkExpr(state, B, X)); return; } // We took the RHS. Because the value of the '&&' or '||' expression must // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0 // or 1. Alternatively, we could take a lazy approach, and calculate this // value later when necessary. We don't have the machinery in place for // this right now, and since most logical expressions are used for branches, // the payoff is not likely to be large. Instead, we do eager evaluation. bool isFeasible = false; const GRState* NewState = Assume(state, X, true, isFeasible); if (isFeasible) MakeNode(Dst, B, Pred, BindBlkExpr(NewState, B, MakeConstantVal(1U, B))); isFeasible = false; NewState = Assume(state, X, false, isFeasible); if (isFeasible) MakeNode(Dst, B, Pred, BindBlkExpr(NewState, B, MakeConstantVal(0U, B))); } else { // We took the LHS expression. Depending on whether we are '&&' or // '||' we know what the value of the expression is via properties of // the short-circuiting. X = MakeConstantVal( B->getOpcode() == BinaryOperator::LAnd ? 0U : 1U, B); MakeNode(Dst, B, Pred, BindBlkExpr(state, B, X)); } } //===----------------------------------------------------------------------===// // Transfer functions: Loads and stores. //===----------------------------------------------------------------------===// void GRExprEngine::VisitDeclRefExpr(DeclRefExpr* Ex, NodeTy* Pred, NodeSet& Dst, bool asLValue) { const GRState* state = GetState(Pred); const NamedDecl* D = Ex->getDecl(); if (const VarDecl* VD = dyn_cast<VarDecl>(D)) { SVal V = StateMgr.GetLValue(state, VD); if (asLValue) MakeNode(Dst, Ex, Pred, BindExpr(state, Ex, V)); else EvalLoad(Dst, Ex, Pred, state, V); return; } else if (const EnumConstantDecl* ED = dyn_cast<EnumConstantDecl>(D)) { assert(!asLValue && "EnumConstantDecl does not have lvalue."); BasicValueFactory& BasicVals = StateMgr.getBasicVals(); SVal V = nonloc::ConcreteInt(BasicVals.getValue(ED->getInitVal())); MakeNode(Dst, Ex, Pred, BindExpr(state, Ex, V)); return; } else if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) { assert(asLValue); SVal V = loc::FuncVal(FD); MakeNode(Dst, Ex, Pred, BindExpr(state, Ex, V)); return; } assert (false && "ValueDecl support for this ValueDecl not implemented."); } /// VisitArraySubscriptExpr - Transfer function for array accesses void GRExprEngine::VisitArraySubscriptExpr(ArraySubscriptExpr* A, NodeTy* Pred, NodeSet& Dst, bool asLValue) { Expr* Base = A->getBase()->IgnoreParens(); Expr* Idx = A->getIdx()->IgnoreParens(); NodeSet Tmp; if (Base->getType()->isVectorType()) { // For vector types get its lvalue. // FIXME: This may not be correct. Is the rvalue of a vector its location? // In fact, I think this is just a hack. We need to get the right // semantics. VisitLValue(Base, Pred, Tmp); } else Visit(Base, Pred, Tmp); // Get Base's rvalue, which should be an LocVal. for (NodeSet::iterator I1=Tmp.begin(), E1=Tmp.end(); I1!=E1; ++I1) { NodeSet Tmp2; Visit(Idx, *I1, Tmp2); // Evaluate the index. for (NodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end(); I2!=E2; ++I2) { const GRState* state = GetState(*I2); SVal V = StateMgr.GetLValue(state, GetSVal(state, Base), GetSVal(state, Idx)); if (asLValue) MakeNode(Dst, A, *I2, BindExpr(state, A, V)); else EvalLoad(Dst, A, *I2, state, V); } } } /// VisitMemberExpr - Transfer function for member expressions. void GRExprEngine::VisitMemberExpr(MemberExpr* M, NodeTy* Pred, NodeSet& Dst, bool asLValue) { Expr* Base = M->getBase()->IgnoreParens(); NodeSet Tmp; if (M->isArrow()) Visit(Base, Pred, Tmp); // p->f = ... or ... = p->f else VisitLValue(Base, Pred, Tmp); // x.f = ... or ... = x.f FieldDecl *Field = dyn_cast<FieldDecl>(M->getMemberDecl()); if (!Field) // FIXME: skipping member expressions for non-fields return; for (NodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) { const GRState* state = GetState(*I); // FIXME: Should we insert some assumption logic in here to determine // if "Base" is a valid piece of memory? Before we put this assumption // later when using FieldOffset lvals (which we no longer have). SVal L = StateMgr.GetLValue(state, GetSVal(state, Base), Field); if (asLValue) MakeNode(Dst, M, *I, BindExpr(state, M, L)); else EvalLoad(Dst, M, *I, state, L); } } /// EvalBind - Handle the semantics of binding a value to a specific location. /// This method is used by EvalStore and (soon) VisitDeclStmt, and others. void GRExprEngine::EvalBind(NodeSet& Dst, Expr* Ex, NodeTy* Pred, const GRState* state, SVal location, SVal Val) { const GRState* newState = 0; if (location.isUnknown()) { // We know that the new state will be the same as the old state since // the location of the binding is "unknown". Consequently, there // is no reason to just create a new node. newState = state; } else { // We are binding to a value other than 'unknown'. Perform the binding // using the StoreManager. newState = StateMgr.BindLoc(state, cast<Loc>(location), Val); } // The next thing to do is check if the GRTransferFuncs object wants to // update the state based on the new binding. If the GRTransferFunc object // doesn't do anything, just auto-propagate the current state. GRStmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, Pred, newState, Ex, newState != state); getTF().EvalBind(BuilderRef, location, Val); } /// EvalStore - Handle the semantics of a store via an assignment. /// @param Dst The node set to store generated state nodes /// @param Ex The expression representing the location of the store /// @param state The current simulation state /// @param location The location to store the value /// @param Val The value to be stored void GRExprEngine::EvalStore(NodeSet& Dst, Expr* Ex, NodeTy* Pred, const GRState* state, SVal location, SVal Val, const void *tag) { assert (Builder && "GRStmtNodeBuilder must be defined."); // Evaluate the location (checks for bad dereferences). Pred = EvalLocation(Ex, Pred, state, location, tag); if (!Pred) return; assert (!location.isUndef()); state = GetState(Pred); // Proceed with the store. SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind); SaveAndRestore<const void*> OldTag(Builder->Tag); Builder->PointKind = ProgramPoint::PostStoreKind; Builder->Tag = tag; EvalBind(Dst, Ex, Pred, state, location, Val); } void GRExprEngine::EvalLoad(NodeSet& Dst, Expr* Ex, NodeTy* Pred, const GRState* state, SVal location, const void *tag) { // Evaluate the location (checks for bad dereferences). Pred = EvalLocation(Ex, Pred, state, location, tag); if (!Pred) return; state = GetState(Pred); // Proceed with the load. ProgramPoint::Kind K = ProgramPoint::PostLoadKind; // FIXME: Currently symbolic analysis "generates" new symbols // for the contents of values. We need a better approach. if (location.isUnknown()) { // This is important. We must nuke the old binding. MakeNode(Dst, Ex, Pred, BindExpr(state, Ex, UnknownVal()), K, tag); } else { SVal V = GetSVal(state, cast<Loc>(location), Ex->getType()); MakeNode(Dst, Ex, Pred, BindExpr(state, Ex, V), K, tag); } } void GRExprEngine::EvalStore(NodeSet& Dst, Expr* Ex, Expr* StoreE, NodeTy* Pred, const GRState* state, SVal location, SVal Val, const void *tag) { NodeSet TmpDst; EvalStore(TmpDst, StoreE, Pred, state, location, Val, tag); for (NodeSet::iterator I=TmpDst.begin(), E=TmpDst.end(); I!=E; ++I) MakeNode(Dst, Ex, *I, (*I)->getState(), ProgramPoint::PostStmtKind, tag); } GRExprEngine::NodeTy* GRExprEngine::EvalLocation(Stmt* Ex, NodeTy* Pred, const GRState* state, SVal location, const void *tag) { SaveAndRestore<const void*> OldTag(Builder->Tag); Builder->Tag = tag; // Check for loads/stores from/to undefined values. if (location.isUndef()) { NodeTy* N = Builder->generateNode(Ex, state, Pred, ProgramPoint::PostUndefLocationCheckFailedKind); if (N) { N->markAsSink(); UndefDeref.insert(N); } return 0; } // Check for loads/stores from/to unknown locations. Treat as No-Ops. if (location.isUnknown()) return Pred; // During a load, one of two possible situations arise: // (1) A crash, because the location (pointer) was NULL. // (2) The location (pointer) is not NULL, and the dereference works. // // We add these assumptions. Loc LV = cast<Loc>(location); // "Assume" that the pointer is not NULL. bool isFeasibleNotNull = false; const GRState* StNotNull = Assume(state, LV, true, isFeasibleNotNull); // "Assume" that the pointer is NULL. bool isFeasibleNull = false; GRStateRef StNull = GRStateRef(Assume(state, LV, false, isFeasibleNull), getStateManager()); if (isFeasibleNull) { // Use the Generic Data Map to mark in the state what lval was null. const SVal* PersistentLV = getBasicVals().getPersistentSVal(LV); StNull = StNull.set<GRState::NullDerefTag>(PersistentLV); // We don't use "MakeNode" here because the node will be a sink // and we have no intention of processing it later. NodeTy* NullNode = Builder->generateNode(Ex, StNull, Pred, ProgramPoint::PostNullCheckFailedKind); if (NullNode) { NullNode->markAsSink(); if (isFeasibleNotNull) ImplicitNullDeref.insert(NullNode); else ExplicitNullDeref.insert(NullNode); } } if (!isFeasibleNotNull) return 0; // Check for out-of-bound array access. if (isa<loc::MemRegionVal>(LV)) { const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion(); if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) { // Get the index of the accessed element. SVal Idx = ER->getIndex(); // Get the extent of the array. SVal NumElements = getStoreManager().getSizeInElements(StNotNull, ER->getSuperRegion()); bool isFeasibleInBound = false; const GRState* StInBound = AssumeInBound(StNotNull, Idx, NumElements, true, isFeasibleInBound); bool isFeasibleOutBound = false; const GRState* StOutBound = AssumeInBound(StNotNull, Idx, NumElements, false, isFeasibleOutBound); if (isFeasibleOutBound) { // Report warning. Make sink node manually. NodeTy* OOBNode = Builder->generateNode(Ex, StOutBound, Pred, ProgramPoint::PostOutOfBoundsCheckFailedKind); if (OOBNode) { OOBNode->markAsSink(); if (isFeasibleInBound) ImplicitOOBMemAccesses.insert(OOBNode); else ExplicitOOBMemAccesses.insert(OOBNode); } } if (!isFeasibleInBound) return 0; StNotNull = StInBound; } } // Generate a new node indicating the checks succeed. return Builder->generateNode(Ex, StNotNull, Pred, ProgramPoint::PostLocationChecksSucceedKind); } //===----------------------------------------------------------------------===// // Transfer function: OSAtomics. // // FIXME: Eventually refactor into a more "plugin" infrastructure. //===----------------------------------------------------------------------===// // Mac OS X: // http://developer.apple.com/documentation/Darwin/Reference/Manpages/man3 // atomic.3.html // static bool EvalOSAtomicCompareAndSwap(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, CallExpr* CE, SVal L, ExplodedNode<GRState>* Pred) { // Not enough arguments to match OSAtomicCompareAndSwap? if (CE->getNumArgs() != 3) return false; ASTContext &C = Engine.getContext(); Expr *oldValueExpr = CE->getArg(0); QualType oldValueType = C.getCanonicalType(oldValueExpr->getType()); Expr *newValueExpr = CE->getArg(1); QualType newValueType = C.getCanonicalType(newValueExpr->getType()); // Do the types of 'oldValue' and 'newValue' match? if (oldValueType != newValueType) return false; Expr *theValueExpr = CE->getArg(2); const PointerType *theValueType = theValueExpr->getType()->getAsPointerType(); // theValueType not a pointer? if (!theValueType) return false; QualType theValueTypePointee = C.getCanonicalType(theValueType->getPointeeType()).getUnqualifiedType(); // The pointee must match newValueType and oldValueType. if (theValueTypePointee != newValueType) return false; static unsigned magic_load = 0; static unsigned magic_store = 0; const void *OSAtomicLoadTag = &magic_load; const void *OSAtomicStoreTag = &magic_store; // Load 'theValue'. GRStateManager &StateMgr = Engine.getStateManager(); const GRState *state = Pred->getState(); ExplodedNodeSet<GRState> Tmp; SVal location = StateMgr.GetSVal(state, theValueExpr); Engine.EvalLoad(Tmp, theValueExpr, Pred, state, location, OSAtomicLoadTag); for (ExplodedNodeSet<GRState>::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) { ExplodedNode<GRState> *N = *I; const GRState *stateLoad = N->getState(); SVal theValueVal = StateMgr.GetSVal(stateLoad, theValueExpr); SVal oldValueVal = StateMgr.GetSVal(stateLoad, oldValueExpr); // Perform the comparison. SVal Cmp = Engine.EvalBinOp(BinaryOperator::EQ, theValueVal, oldValueVal, Engine.getContext().IntTy); bool isFeasible = false; const GRState *stateEqual = StateMgr.Assume(stateLoad, Cmp, true, isFeasible); // Were they equal? if (isFeasible) { // Perform the store. ExplodedNodeSet<GRState> TmpStore; Engine.EvalStore(TmpStore, theValueExpr, N, stateEqual, location, StateMgr.GetSVal(stateEqual, newValueExpr), OSAtomicStoreTag); // Now bind the result of the comparison. for (ExplodedNodeSet<GRState>::iterator I2 = TmpStore.begin(), E2 = TmpStore.end(); I2 != E2; ++I2) { ExplodedNode<GRState> *predNew = *I2; const GRState *stateNew = predNew->getState(); SVal Res = Engine.getValueManager().makeTruthVal(true, CE->getType()); Engine.MakeNode(Dst, CE, predNew, Engine.BindExpr(stateNew, CE, Res)); } } // Were they not equal? isFeasible = false; const GRState *stateNotEqual = StateMgr.Assume(stateLoad, Cmp, false, isFeasible); if (isFeasible) { SVal Res = Engine.getValueManager().makeTruthVal(false, CE->getType()); Engine.MakeNode(Dst, CE, N, Engine.BindExpr(stateNotEqual, CE, Res)); } } return true; } static bool EvalOSAtomic(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Engine, GRStmtNodeBuilder<GRState>& Builder, CallExpr* CE, SVal L, ExplodedNode<GRState>* Pred) { if (!isa<loc::FuncVal>(L)) return false; const FunctionDecl *FD = cast<loc::FuncVal>(L).getDecl(); const char *FName = FD->getNameAsCString(); // Check for compare and swap. if (strncmp(FName, "OSAtomicCompareAndSwap", 22) == 0 || strncmp(FName, "objc_atomicCompareAndSwap", 25) == 0) return EvalOSAtomicCompareAndSwap(Dst, Engine, Builder, CE, L, Pred); // FIXME: Other atomics. return false; } //===----------------------------------------------------------------------===// // Transfer function: Function calls. //===----------------------------------------------------------------------===// void GRExprEngine::EvalCall(NodeSet& Dst, CallExpr* CE, SVal L, NodeTy* Pred) { assert (Builder && "GRStmtNodeBuilder must be defined."); // FIXME: Allow us to chain together transfer functions. if (EvalOSAtomic(Dst, *this, *Builder, CE, L, Pred)) return; getTF().EvalCall(Dst, *this, *Builder, CE, L, Pred); } void GRExprEngine::VisitCall(CallExpr* CE, NodeTy* Pred, CallExpr::arg_iterator AI, CallExpr::arg_iterator AE, NodeSet& Dst) { // Determine the type of function we're calling (if available). const FunctionProtoType *Proto = NULL; QualType FnType = CE->getCallee()->IgnoreParens()->getType(); if (const PointerType *FnTypePtr = FnType->getAsPointerType()) Proto = FnTypePtr->getPointeeType()->getAsFunctionProtoType(); VisitCallRec(CE, Pred, AI, AE, Dst, Proto, /*ParamIdx=*/0); } void GRExprEngine::VisitCallRec(CallExpr* CE, NodeTy* Pred, CallExpr::arg_iterator AI, CallExpr::arg_iterator AE, NodeSet& Dst, const FunctionProtoType *Proto, unsigned ParamIdx) { // Process the arguments. if (AI != AE) { // If the call argument is being bound to a reference parameter, // visit it as an lvalue, not an rvalue. bool VisitAsLvalue = false; if (Proto && ParamIdx < Proto->getNumArgs()) VisitAsLvalue = Proto->getArgType(ParamIdx)->isReferenceType(); NodeSet DstTmp; if (VisitAsLvalue) VisitLValue(*AI, Pred, DstTmp); else Visit(*AI, Pred, DstTmp); ++AI; for (NodeSet::iterator DI=DstTmp.begin(), DE=DstTmp.end(); DI != DE; ++DI) VisitCallRec(CE, *DI, AI, AE, Dst, Proto, ParamIdx + 1); return; } // If we reach here we have processed all of the arguments. Evaluate // the callee expression. NodeSet DstTmp; Expr* Callee = CE->getCallee()->IgnoreParens(); Visit(Callee, Pred, DstTmp); // Finally, evaluate the function call. for (NodeSet::iterator DI = DstTmp.begin(), DE = DstTmp.end(); DI!=DE; ++DI) { const GRState* state = GetState(*DI); SVal L = GetSVal(state, Callee); // FIXME: Add support for symbolic function calls (calls involving // function pointer values that are symbolic). // Check for undefined control-flow or calls to NULL. if (L.isUndef() || isa<loc::ConcreteInt>(L)) { NodeTy* N = Builder->generateNode(CE, state, *DI); if (N) { N->markAsSink(); BadCalls.insert(N); } continue; } // Check for the "noreturn" attribute. SaveAndRestore<bool> OldSink(Builder->BuildSinks); if (isa<loc::FuncVal>(L)) { FunctionDecl* FD = cast<loc::FuncVal>(L).getDecl(); if (FD->getAttr<NoReturnAttr>() || FD->getAttr<AnalyzerNoReturnAttr>()) Builder->BuildSinks = true; else { // HACK: Some functions are not marked noreturn, and don't return. // Here are a few hardwired ones. If this takes too long, we can // potentially cache these results. const char* s = FD->getIdentifier()->getName(); unsigned n = strlen(s); switch (n) { default: break; case 4: if (!memcmp(s, "exit", 4)) Builder->BuildSinks = true; break; case 5: if (!memcmp(s, "panic", 5)) Builder->BuildSinks = true; else if (!memcmp(s, "error", 5)) { if (CE->getNumArgs() > 0) { SVal X = GetSVal(state, *CE->arg_begin()); // FIXME: use Assume to inspect the possible symbolic value of // X. Also check the specific signature of error(). nonloc::ConcreteInt* CI = dyn_cast<nonloc::ConcreteInt>(&X); if (CI && CI->getValue() != 0) Builder->BuildSinks = true; } } break; case 6: if (!memcmp(s, "Assert", 6)) { Builder->BuildSinks = true; break; } // FIXME: This is just a wrapper around throwing an exception. // Eventually inter-procedural analysis should handle this easily. if (!memcmp(s, "ziperr", 6)) Builder->BuildSinks = true; break; case 7: if (!memcmp(s, "assfail", 7)) Builder->BuildSinks = true; break; case 8: if (!memcmp(s ,"db_error", 8) || !memcmp(s, "__assert", 8)) Builder->BuildSinks = true; break; case 12: if (!memcmp(s, "__assert_rtn", 12)) Builder->BuildSinks = true; break; case 13: if (!memcmp(s, "__assert_fail", 13)) Builder->BuildSinks = true; break; case 14: if (!memcmp(s, "dtrace_assfail", 14) || !memcmp(s, "yy_fatal_error", 14)) Builder->BuildSinks = true; break; case 26: if (!memcmp(s, "_XCAssertionFailureHandler", 26) || !memcmp(s, "_DTAssertionFailureHandler", 26) || !memcmp(s, "_TSAssertionFailureHandler", 26)) Builder->BuildSinks = true; break; } } } // Evaluate the call. if (isa<loc::FuncVal>(L)) { if (unsigned id = cast<loc::FuncVal>(L).getDecl()->getBuiltinID(getContext())) switch (id) { case Builtin::BI__builtin_expect: { // For __builtin_expect, just return the value of the subexpression. assert (CE->arg_begin() != CE->arg_end()); SVal X = GetSVal(state, *(CE->arg_begin())); MakeNode(Dst, CE, *DI, BindExpr(state, CE, X)); continue; } case Builtin::BI__builtin_alloca: { // FIXME: Refactor into StoreManager itself? MemRegionManager& RM = getStateManager().getRegionManager(); const MemRegion* R = RM.getAllocaRegion(CE, Builder->getCurrentBlockCount()); // Set the extent of the region in bytes. This enables us to use the // SVal of the argument directly. If we save the extent in bits, we // cannot represent values like symbol*8. SVal Extent = GetSVal(state, *(CE->arg_begin())); state = getStoreManager().setExtent(state, R, Extent); MakeNode(Dst, CE, *DI, BindExpr(state, CE, loc::MemRegionVal(R))); continue; } default: break; } } // Check any arguments passed-by-value against being undefined. bool badArg = false; for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { if (GetSVal(GetState(*DI), *I).isUndef()) { NodeTy* N = Builder->generateNode(CE, GetState(*DI), *DI); if (N) { N->markAsSink(); UndefArgs[N] = *I; } badArg = true; break; } } if (badArg) continue; // Dispatch to the plug-in transfer function. unsigned size = Dst.size(); SaveOr OldHasGen(Builder->HasGeneratedNode); EvalCall(Dst, CE, L, *DI); // Handle the case where no nodes where generated. Auto-generate that // contains the updated state if we aren't generating sinks. if (!Builder->BuildSinks && Dst.size() == size && !Builder->HasGeneratedNode) MakeNode(Dst, CE, *DI, state); } } //===----------------------------------------------------------------------===// // Transfer function: Objective-C ivar references. //===----------------------------------------------------------------------===// static std::pair<const void*,const void*> EagerlyAssumeTag = std::pair<const void*,const void*>(&EagerlyAssumeTag,0); void GRExprEngine::EvalEagerlyAssume(NodeSet &Dst, NodeSet &Src, Expr *Ex) { for (NodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) { NodeTy *Pred = *I; // Test if the previous node was as the same expression. This can happen // when the expression fails to evaluate to anything meaningful and // (as an optimization) we don't generate a node. ProgramPoint P = Pred->getLocation(); if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) { Dst.Add(Pred); continue; } const GRState* state = Pred->getState(); SVal V = GetSVal(state, Ex); if (isa<nonloc::SymExprVal>(V)) { // First assume that the condition is true. bool isFeasible = false; const GRState *stateTrue = Assume(state, V, true, isFeasible); if (isFeasible) { stateTrue = BindExpr(stateTrue, Ex, MakeConstantVal(1U, Ex)); Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag), stateTrue, Pred)); } // Next, assume that the condition is false. isFeasible = false; const GRState *stateFalse = Assume(state, V, false, isFeasible); if (isFeasible) { stateFalse = BindExpr(stateFalse, Ex, MakeConstantVal(0U, Ex)); Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag), stateFalse, Pred)); } } else Dst.Add(Pred); } } //===----------------------------------------------------------------------===// // Transfer function: Objective-C ivar references. //===----------------------------------------------------------------------===// void GRExprEngine::VisitObjCIvarRefExpr(ObjCIvarRefExpr* Ex, NodeTy* Pred, NodeSet& Dst, bool asLValue) { Expr* Base = cast<Expr>(Ex->getBase()); NodeSet Tmp; Visit(Base, Pred, Tmp); for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); SVal BaseVal = GetSVal(state, Base); SVal location = StateMgr.GetLValue(state, Ex->getDecl(), BaseVal); if (asLValue) MakeNode(Dst, Ex, *I, BindExpr(state, Ex, location)); else EvalLoad(Dst, Ex, *I, state, location); } } //===----------------------------------------------------------------------===// // Transfer function: Objective-C fast enumeration 'for' statements. //===----------------------------------------------------------------------===// void GRExprEngine::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S, NodeTy* Pred, NodeSet& Dst) { // ObjCForCollectionStmts are processed in two places. This method // handles the case where an ObjCForCollectionStmt* occurs as one of the // statements within a basic block. This transfer function does two things: // // (1) binds the next container value to 'element'. This creates a new // node in the ExplodedGraph. // // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating // whether or not the container has any more elements. This value // will be tested in ProcessBranch. We need to explicitly bind // this value because a container can contain nil elements. // // FIXME: Eventually this logic should actually do dispatches to // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration). // This will require simulating a temporary NSFastEnumerationState, either // through an SVal or through the use of MemRegions. This value can // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop // terminates we reclaim the temporary (it goes out of scope) and we // we can test if the SVal is 0 or if the MemRegion is null (depending // on what approach we take). // // For now: simulate (1) by assigning either a symbol or nil if the // container is empty. Thus this transfer function will by default // result in state splitting. Stmt* elem = S->getElement(); SVal ElementV; if (DeclStmt* DS = dyn_cast<DeclStmt>(elem)) { VarDecl* ElemD = cast<VarDecl>(DS->getSingleDecl()); assert (ElemD->getInit() == 0); ElementV = getStateManager().GetLValue(GetState(Pred), ElemD); VisitObjCForCollectionStmtAux(S, Pred, Dst, ElementV); return; } NodeSet Tmp; VisitLValue(cast<Expr>(elem), Pred, Tmp); for (NodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); VisitObjCForCollectionStmtAux(S, *I, Dst, GetSVal(state, elem)); } } void GRExprEngine::VisitObjCForCollectionStmtAux(ObjCForCollectionStmt* S, NodeTy* Pred, NodeSet& Dst, SVal ElementV) { // Get the current state. Use 'EvalLocation' to determine if it is a null // pointer, etc. Stmt* elem = S->getElement(); Pred = EvalLocation(elem, Pred, GetState(Pred), ElementV); if (!Pred) return; GRStateRef state = GRStateRef(GetState(Pred), getStateManager()); // Handle the case where the container still has elements. QualType IntTy = getContext().IntTy; SVal TrueV = NonLoc::MakeVal(getBasicVals(), 1, IntTy); GRStateRef hasElems = state.BindExpr(S, TrueV); // Handle the case where the container has no elements. SVal FalseV = NonLoc::MakeVal(getBasicVals(), 0, IntTy); GRStateRef noElems = state.BindExpr(S, FalseV); if (loc::MemRegionVal* MV = dyn_cast<loc::MemRegionVal>(&ElementV)) if (const TypedRegion* R = dyn_cast<TypedRegion>(MV->getRegion())) { // FIXME: The proper thing to do is to really iterate over the // container. We will do this with dispatch logic to the store. // For now, just 'conjure' up a symbolic value. QualType T = R->getRValueType(getContext()); assert (Loc::IsLocType(T)); unsigned Count = Builder->getCurrentBlockCount(); SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count); SVal V = Loc::MakeVal(getStoreManager().getRegionManager().getSymbolicRegion(Sym)); hasElems = hasElems.BindLoc(ElementV, V); // Bind the location to 'nil' on the false branch. SVal nilV = loc::ConcreteInt(getBasicVals().getValue(0, T)); noElems = noElems.BindLoc(ElementV, nilV); } // Create the new nodes. MakeNode(Dst, S, Pred, hasElems); MakeNode(Dst, S, Pred, noElems); } //===----------------------------------------------------------------------===// // Transfer function: Objective-C message expressions. //===----------------------------------------------------------------------===// void GRExprEngine::VisitObjCMessageExpr(ObjCMessageExpr* ME, NodeTy* Pred, NodeSet& Dst){ VisitObjCMessageExprArgHelper(ME, ME->arg_begin(), ME->arg_end(), Pred, Dst); } void GRExprEngine::VisitObjCMessageExprArgHelper(ObjCMessageExpr* ME, ObjCMessageExpr::arg_iterator AI, ObjCMessageExpr::arg_iterator AE, NodeTy* Pred, NodeSet& Dst) { if (AI == AE) { // Process the receiver. if (Expr* Receiver = ME->getReceiver()) { NodeSet Tmp; Visit(Receiver, Pred, Tmp); for (NodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI != NE; ++NI) VisitObjCMessageExprDispatchHelper(ME, *NI, Dst); return; } VisitObjCMessageExprDispatchHelper(ME, Pred, Dst); return; } NodeSet Tmp; Visit(*AI, Pred, Tmp); ++AI; for (NodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI != NE; ++NI) VisitObjCMessageExprArgHelper(ME, AI, AE, *NI, Dst); } void GRExprEngine::VisitObjCMessageExprDispatchHelper(ObjCMessageExpr* ME, NodeTy* Pred, NodeSet& Dst) { // FIXME: More logic for the processing the method call. const GRState* state = GetState(Pred); bool RaisesException = false; if (Expr* Receiver = ME->getReceiver()) { SVal L = GetSVal(state, Receiver); // Check for undefined control-flow. if (L.isUndef()) { NodeTy* N = Builder->generateNode(ME, state, Pred); if (N) { N->markAsSink(); UndefReceivers.insert(N); } return; } // "Assume" that the receiver is not NULL. bool isFeasibleNotNull = false; const GRState *StNotNull = Assume(state, L, true, isFeasibleNotNull); // "Assume" that the receiver is NULL. bool isFeasibleNull = false; const GRState *StNull = Assume(state, L, false, isFeasibleNull); if (isFeasibleNull) { QualType RetTy = ME->getType(); // Check if the receiver was nil and the return value a struct. if(RetTy->isRecordType()) { if (BR.getParentMap().isConsumedExpr(ME)) { // The [0 ...] expressions will return garbage. Flag either an // explicit or implicit error. Because of the structure of this // function we currently do not bifurfacte the state graph at // this point. // FIXME: We should bifurcate and fill the returned struct with // garbage. if (NodeTy* N = Builder->generateNode(ME, StNull, Pred)) { N->markAsSink(); if (isFeasibleNotNull) NilReceiverStructRetImplicit.insert(N); else NilReceiverStructRetExplicit.insert(N); } } } else { ASTContext& Ctx = getContext(); if (RetTy != Ctx.VoidTy) { if (BR.getParentMap().isConsumedExpr(ME)) { // sizeof(void *) const uint64_t voidPtrSize = Ctx.getTypeSize(Ctx.VoidPtrTy); // sizeof(return type) const uint64_t returnTypeSize = Ctx.getTypeSize(ME->getType()); if(voidPtrSize < returnTypeSize) { if (NodeTy* N = Builder->generateNode(ME, StNull, Pred)) { N->markAsSink(); if(isFeasibleNotNull) NilReceiverLargerThanVoidPtrRetImplicit.insert(N); else NilReceiverLargerThanVoidPtrRetExplicit.insert(N); } } else if (!isFeasibleNotNull) { // Handle the safe cases where the return value is 0 if the // receiver is nil. // // FIXME: For now take the conservative approach that we only // return null values if we *know* that the receiver is nil. // This is because we can have surprises like: // // ... = [[NSScreens screens] objectAtIndex:0]; // // What can happen is that [... screens] could return nil, but // it most likely isn't nil. We should assume the semantics // of this case unless we have *a lot* more knowledge. // SVal V = ValMgr.makeZeroVal(ME->getType()); MakeNode(Dst, ME, Pred, BindExpr(StNull, ME, V)); return; } } } } // We have handled the cases where the receiver is nil. The remainder // of this method should assume that the receiver is not nil. if (!StNotNull) return; state = StNotNull; } // Check if the "raise" message was sent. if (ME->getSelector() == RaiseSel) RaisesException = true; } else { IdentifierInfo* ClsName = ME->getClassName(); Selector S = ME->getSelector(); // Check for special instance methods. if (!NSExceptionII) { ASTContext& Ctx = getContext(); NSExceptionII = &Ctx.Idents.get("NSException"); } if (ClsName == NSExceptionII) { enum { NUM_RAISE_SELECTORS = 2 }; // Lazily create a cache of the selectors. if (!NSExceptionInstanceRaiseSelectors) { ASTContext& Ctx = getContext(); NSExceptionInstanceRaiseSelectors = new Selector[NUM_RAISE_SELECTORS]; llvm::SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II; unsigned idx = 0; // raise:format: II.push_back(&Ctx.Idents.get("raise")); II.push_back(&Ctx.Idents.get("format")); NSExceptionInstanceRaiseSelectors[idx++] = Ctx.Selectors.getSelector(II.size(), &II[0]); // raise:format::arguments: II.push_back(&Ctx.Idents.get("arguments")); NSExceptionInstanceRaiseSelectors[idx++] = Ctx.Selectors.getSelector(II.size(), &II[0]); } for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i) if (S == NSExceptionInstanceRaiseSelectors[i]) { RaisesException = true; break; } } } // Check for any arguments that are uninitialized/undefined. for (ObjCMessageExpr::arg_iterator I = ME->arg_begin(), E = ME->arg_end(); I != E; ++I) { if (GetSVal(state, *I).isUndef()) { // Generate an error node for passing an uninitialized/undefined value // as an argument to a message expression. This node is a sink. NodeTy* N = Builder->generateNode(ME, state, Pred); if (N) { N->markAsSink(); MsgExprUndefArgs[N] = *I; } return; } } // Check if we raise an exception. For now treat these as sinks. Eventually // we will want to handle exceptions properly. SaveAndRestore<bool> OldSink(Builder->BuildSinks); if (RaisesException) Builder->BuildSinks = true; // Dispatch to plug-in transfer function. unsigned size = Dst.size(); SaveOr OldHasGen(Builder->HasGeneratedNode); EvalObjCMessageExpr(Dst, ME, Pred); // Handle the case where no nodes where generated. Auto-generate that // contains the updated state if we aren't generating sinks. if (!Builder->BuildSinks && Dst.size() == size && !Builder->HasGeneratedNode) MakeNode(Dst, ME, Pred, state); } //===----------------------------------------------------------------------===// // Transfer functions: Miscellaneous statements. //===----------------------------------------------------------------------===// void GRExprEngine::VisitCastPointerToInteger(SVal V, const GRState* state, QualType PtrTy, Expr* CastE, NodeTy* Pred, NodeSet& Dst) { if (!V.isUnknownOrUndef()) { // FIXME: Determine if the number of bits of the target type is // equal or exceeds the number of bits to store the pointer value. // If not, flag an error. MakeNode(Dst, CastE, Pred, BindExpr(state, CastE, EvalCast(cast<Loc>(V), CastE->getType()))); } else MakeNode(Dst, CastE, Pred, BindExpr(state, CastE, V)); } void GRExprEngine::VisitCast(Expr* CastE, Expr* Ex, NodeTy* Pred, NodeSet& Dst){ NodeSet S1; QualType T = CastE->getType(); QualType ExTy = Ex->getType(); if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE)) T = ExCast->getTypeAsWritten(); if (ExTy->isArrayType() || ExTy->isFunctionType() || T->isReferenceType()) VisitLValue(Ex, Pred, S1); else Visit(Ex, Pred, S1); // Check for casting to "void". if (T->isVoidType()) { for (NodeSet::iterator I1 = S1.begin(), E1 = S1.end(); I1 != E1; ++I1) Dst.Add(*I1); return; } // FIXME: The rest of this should probably just go into EvalCall, and // let the transfer function object be responsible for constructing // nodes. for (NodeSet::iterator I1 = S1.begin(), E1 = S1.end(); I1 != E1; ++I1) { NodeTy* N = *I1; const GRState* state = GetState(N); SVal V = GetSVal(state, Ex); ASTContext& C = getContext(); // Unknown? if (V.isUnknown()) { Dst.Add(N); continue; } // Undefined? if (V.isUndef()) goto PassThrough; // For const casts, just propagate the value. if (C.getCanonicalType(T).getUnqualifiedType() == C.getCanonicalType(ExTy).getUnqualifiedType()) goto PassThrough; // Check for casts from pointers to integers. if (T->isIntegerType() && Loc::IsLocType(ExTy)) { VisitCastPointerToInteger(V, state, ExTy, CastE, N, Dst); continue; } // Check for casts from integers to pointers. if (Loc::IsLocType(T) && ExTy->isIntegerType()) { if (nonloc::LocAsInteger *LV = dyn_cast<nonloc::LocAsInteger>(&V)) { // Just unpackage the lval and return it. V = LV->getLoc(); MakeNode(Dst, CastE, N, BindExpr(state, CastE, V)); continue; } goto DispatchCast; } // Just pass through function and block pointers. if (ExTy->isBlockPointerType() || ExTy->isFunctionPointerType()) { assert(Loc::IsLocType(T)); goto PassThrough; } // Check for casts from array type to another type. if (ExTy->isArrayType()) { // We will always decay to a pointer. V = StateMgr.ArrayToPointer(cast<Loc>(V)); // Are we casting from an array to a pointer? If so just pass on // the decayed value. if (T->isPointerType()) goto PassThrough; // Are we casting from an array to an integer? If so, cast the decayed // pointer value to an integer. assert(T->isIntegerType()); QualType ElemTy = cast<ArrayType>(ExTy)->getElementType(); QualType PointerTy = getContext().getPointerType(ElemTy); VisitCastPointerToInteger(V, state, PointerTy, CastE, N, Dst); continue; } // Check for casts from a region to a specific type. if (loc::MemRegionVal *RV = dyn_cast<loc::MemRegionVal>(&V)) { // FIXME: For TypedViewRegions, we should handle the case where the // underlying symbolic pointer is a function pointer or // block pointer. // FIXME: We should handle the case where we strip off view layers to get // to a desugared type. assert(Loc::IsLocType(T)); // We get a symbolic function pointer for a dereference of a function // pointer, but it is of function type. Example: // struct FPRec { // void (*my_func)(int * x); // }; // // int bar(int x); // // int f1_a(struct FPRec* foo) { // int x; // (*foo->my_func)(&x); // return bar(x)+1; // no-warning // } assert(Loc::IsLocType(ExTy) || ExTy->isFunctionType()); const MemRegion* R = RV->getRegion(); StoreManager& StoreMgr = getStoreManager(); // Delegate to store manager to get the result of casting a region // to a different type. const StoreManager::CastResult& Res = StoreMgr.CastRegion(state, R, T); // Inspect the result. If the MemRegion* returned is NULL, this // expression evaluates to UnknownVal. R = Res.getRegion(); if (R) { V = loc::MemRegionVal(R); } else { V = UnknownVal(); } // Generate the new node in the ExplodedGraph. MakeNode(Dst, CastE, N, BindExpr(Res.getState(), CastE, V)); continue; } // All other cases. DispatchCast: { MakeNode(Dst, CastE, N, BindExpr(state, CastE, EvalCast(V, CastE->getType()))); continue; } PassThrough: { MakeNode(Dst, CastE, N, BindExpr(state, CastE, V)); } } } void GRExprEngine::VisitCompoundLiteralExpr(CompoundLiteralExpr* CL, NodeTy* Pred, NodeSet& Dst, bool asLValue) { InitListExpr* ILE = cast<InitListExpr>(CL->getInitializer()->IgnoreParens()); NodeSet Tmp; Visit(ILE, Pred, Tmp); for (NodeSet::iterator I = Tmp.begin(), EI = Tmp.end(); I!=EI; ++I) { const GRState* state = GetState(*I); SVal ILV = GetSVal(state, ILE); state = StateMgr.BindCompoundLiteral(state, CL, ILV); if (asLValue) MakeNode(Dst, CL, *I, BindExpr(state, CL, StateMgr.GetLValue(state, CL))); else MakeNode(Dst, CL, *I, BindExpr(state, CL, ILV)); } } void GRExprEngine::VisitDeclStmt(DeclStmt* DS, NodeTy* Pred, NodeSet& Dst) { // The CFG has one DeclStmt per Decl. Decl* D = *DS->decl_begin(); if (!D || !isa<VarDecl>(D)) return; const VarDecl* VD = dyn_cast<VarDecl>(D); Expr* InitEx = const_cast<Expr*>(VD->getInit()); // FIXME: static variables may have an initializer, but the second // time a function is called those values may not be current. NodeSet Tmp; if (InitEx) Visit(InitEx, Pred, Tmp); if (Tmp.empty()) Tmp.Add(Pred); for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); unsigned Count = Builder->getCurrentBlockCount(); // Check if 'VD' is a VLA and if so check if has a non-zero size. QualType T = getContext().getCanonicalType(VD->getType()); if (VariableArrayType* VLA = dyn_cast<VariableArrayType>(T)) { // FIXME: Handle multi-dimensional VLAs. Expr* SE = VLA->getSizeExpr(); SVal Size = GetSVal(state, SE); if (Size.isUndef()) { if (NodeTy* N = Builder->generateNode(DS, state, Pred)) { N->markAsSink(); ExplicitBadSizedVLA.insert(N); } continue; } bool isFeasibleZero = false; const GRState* ZeroSt = Assume(state, Size, false, isFeasibleZero); bool isFeasibleNotZero = false; state = Assume(state, Size, true, isFeasibleNotZero); if (isFeasibleZero) { if (NodeTy* N = Builder->generateNode(DS, ZeroSt, Pred)) { N->markAsSink(); if (isFeasibleNotZero) ImplicitBadSizedVLA.insert(N); else ExplicitBadSizedVLA.insert(N); } } if (!isFeasibleNotZero) continue; } // Decls without InitExpr are not initialized explicitly. if (InitEx) { SVal InitVal = GetSVal(state, InitEx); QualType T = VD->getType(); // Recover some path-sensitivity if a scalar value evaluated to // UnknownVal. if (InitVal.isUnknown() || !getConstraintManager().canReasonAbout(InitVal)) { InitVal = ValMgr.getConjuredSymbolVal(InitEx, Count); } state = StateMgr.BindDecl(state, VD, InitVal); // The next thing to do is check if the GRTransferFuncs object wants to // update the state based on the new binding. If the GRTransferFunc // object doesn't do anything, just auto-propagate the current state. GRStmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, state, DS,true); getTF().EvalBind(BuilderRef, loc::MemRegionVal(StateMgr.getRegion(VD)), InitVal); } else { state = StateMgr.BindDeclWithNoInit(state, VD); MakeNode(Dst, DS, *I, state); } } } namespace { // This class is used by VisitInitListExpr as an item in a worklist // for processing the values contained in an InitListExpr. class VISIBILITY_HIDDEN InitListWLItem { public: llvm::ImmutableList<SVal> Vals; GRExprEngine::NodeTy* N; InitListExpr::reverse_iterator Itr; InitListWLItem(GRExprEngine::NodeTy* n, llvm::ImmutableList<SVal> vals, InitListExpr::reverse_iterator itr) : Vals(vals), N(n), Itr(itr) {} }; } void GRExprEngine::VisitInitListExpr(InitListExpr* E, NodeTy* Pred, NodeSet& Dst) { const GRState* state = GetState(Pred); QualType T = getContext().getCanonicalType(E->getType()); unsigned NumInitElements = E->getNumInits(); if (T->isArrayType() || T->isStructureType()) { llvm::ImmutableList<SVal> StartVals = getBasicVals().getEmptySValList(); // Handle base case where the initializer has no elements. // e.g: static int* myArray[] = {}; if (NumInitElements == 0) { SVal V = NonLoc::MakeCompoundVal(T, StartVals, getBasicVals()); MakeNode(Dst, E, Pred, BindExpr(state, E, V)); return; } // Create a worklist to process the initializers. llvm::SmallVector<InitListWLItem, 10> WorkList; WorkList.reserve(NumInitElements); WorkList.push_back(InitListWLItem(Pred, StartVals, E->rbegin())); InitListExpr::reverse_iterator ItrEnd = E->rend(); // Process the worklist until it is empty. while (!WorkList.empty()) { InitListWLItem X = WorkList.back(); WorkList.pop_back(); NodeSet Tmp; Visit(*X.Itr, X.N, Tmp); InitListExpr::reverse_iterator NewItr = X.Itr + 1; for (NodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) { // Get the last initializer value. state = GetState(*NI); SVal InitV = GetSVal(state, cast<Expr>(*X.Itr)); // Construct the new list of values by prepending the new value to // the already constructed list. llvm::ImmutableList<SVal> NewVals = getBasicVals().consVals(InitV, X.Vals); if (NewItr == ItrEnd) { // Now we have a list holding all init values. Make CompoundValData. SVal V = NonLoc::MakeCompoundVal(T, NewVals, getBasicVals()); // Make final state and node. MakeNode(Dst, E, *NI, BindExpr(state, E, V)); } else { // Still some initializer values to go. Push them onto the worklist. WorkList.push_back(InitListWLItem(*NI, NewVals, NewItr)); } } } return; } if (T->isUnionType() || T->isVectorType()) { // FIXME: to be implemented. // Note: That vectors can return true for T->isIntegerType() MakeNode(Dst, E, Pred, state); return; } if (Loc::IsLocType(T) || T->isIntegerType()) { assert (E->getNumInits() == 1); NodeSet Tmp; Expr* Init = E->getInit(0); Visit(Init, Pred, Tmp); for (NodeSet::iterator I = Tmp.begin(), EI = Tmp.end(); I != EI; ++I) { state = GetState(*I); MakeNode(Dst, E, *I, BindExpr(state, E, GetSVal(state, Init))); } return; } printf("InitListExpr type = %s\n", T.getAsString().c_str()); assert(0 && "unprocessed InitListExpr type"); } /// VisitSizeOfAlignOfExpr - Transfer function for sizeof(type). void GRExprEngine::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr* Ex, NodeTy* Pred, NodeSet& Dst) { QualType T = Ex->getTypeOfArgument(); uint64_t amt; if (Ex->isSizeOf()) { if (T == getContext().VoidTy) { // sizeof(void) == 1 byte. amt = 1; } else if (!T.getTypePtr()->isConstantSizeType()) { // FIXME: Add support for VLAs. return; } else if (T->isObjCInterfaceType()) { // Some code tries to take the sizeof an ObjCInterfaceType, relying that // the compiler has laid out its representation. Just report Unknown // for these. return; } else { // All other cases. amt = getContext().getTypeSize(T) / 8; } } else // Get alignment of the type. amt = getContext().getTypeAlign(T) / 8; MakeNode(Dst, Ex, Pred, BindExpr(GetState(Pred), Ex, NonLoc::MakeVal(getBasicVals(), amt, Ex->getType()))); } void GRExprEngine::VisitUnaryOperator(UnaryOperator* U, NodeTy* Pred, NodeSet& Dst, bool asLValue) { switch (U->getOpcode()) { default: break; case UnaryOperator::Deref: { Expr* Ex = U->getSubExpr()->IgnoreParens(); NodeSet Tmp; Visit(Ex, Pred, Tmp); for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); SVal location = GetSVal(state, Ex); if (asLValue) MakeNode(Dst, U, *I, BindExpr(state, U, location)); else EvalLoad(Dst, U, *I, state, location); } return; } case UnaryOperator::Real: { Expr* Ex = U->getSubExpr()->IgnoreParens(); NodeSet Tmp; Visit(Ex, Pred, Tmp); for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { // FIXME: We don't have complex SValues yet. if (Ex->getType()->isAnyComplexType()) { // Just report "Unknown." Dst.Add(*I); continue; } // For all other types, UnaryOperator::Real is an identity operation. assert (U->getType() == Ex->getType()); const GRState* state = GetState(*I); MakeNode(Dst, U, *I, BindExpr(state, U, GetSVal(state, Ex))); } return; } case UnaryOperator::Imag: { Expr* Ex = U->getSubExpr()->IgnoreParens(); NodeSet Tmp; Visit(Ex, Pred, Tmp); for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { // FIXME: We don't have complex SValues yet. if (Ex->getType()->isAnyComplexType()) { // Just report "Unknown." Dst.Add(*I); continue; } // For all other types, UnaryOperator::Float returns 0. assert (Ex->getType()->isIntegerType()); const GRState* state = GetState(*I); SVal X = NonLoc::MakeVal(getBasicVals(), 0, Ex->getType()); MakeNode(Dst, U, *I, BindExpr(state, U, X)); } return; } // FIXME: Just report "Unknown" for OffsetOf. case UnaryOperator::OffsetOf: Dst.Add(Pred); return; case UnaryOperator::Plus: assert (!asLValue); // FALL-THROUGH. case UnaryOperator::Extension: { // Unary "+" is a no-op, similar to a parentheses. We still have places // where it may be a block-level expression, so we need to // generate an extra node that just propagates the value of the // subexpression. Expr* Ex = U->getSubExpr()->IgnoreParens(); NodeSet Tmp; Visit(Ex, Pred, Tmp); for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); MakeNode(Dst, U, *I, BindExpr(state, U, GetSVal(state, Ex))); } return; } case UnaryOperator::AddrOf: { assert(!asLValue); Expr* Ex = U->getSubExpr()->IgnoreParens(); NodeSet Tmp; VisitLValue(Ex, Pred, Tmp); for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); SVal V = GetSVal(state, Ex); state = BindExpr(state, U, V); MakeNode(Dst, U, *I, state); } return; } case UnaryOperator::LNot: case UnaryOperator::Minus: case UnaryOperator::Not: { assert (!asLValue); Expr* Ex = U->getSubExpr()->IgnoreParens(); NodeSet Tmp; Visit(Ex, Pred, Tmp); for (NodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); // Get the value of the subexpression. SVal V = GetSVal(state, Ex); if (V.isUnknownOrUndef()) { MakeNode(Dst, U, *I, BindExpr(state, U, V)); continue; } // QualType DstT = getContext().getCanonicalType(U->getType()); // QualType SrcT = getContext().getCanonicalType(Ex->getType()); // // if (DstT != SrcT) // Perform promotions. // V = EvalCast(V, DstT); // // if (V.isUnknownOrUndef()) { // MakeNode(Dst, U, *I, BindExpr(St, U, V)); // continue; // } switch (U->getOpcode()) { default: assert(false && "Invalid Opcode."); break; case UnaryOperator::Not: // FIXME: Do we need to handle promotions? state = BindExpr(state, U, EvalComplement(cast<NonLoc>(V))); break; case UnaryOperator::Minus: // FIXME: Do we need to handle promotions? state = BindExpr(state, U, EvalMinus(U, cast<NonLoc>(V))); break; case UnaryOperator::LNot: // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." // // Note: technically we do "E == 0", but this is the same in the // transfer functions as "0 == E". if (isa<Loc>(V)) { Loc X = Loc::MakeNull(getBasicVals()); SVal Result = EvalBinOp(BinaryOperator::EQ, cast<Loc>(V), X, U->getType()); state = BindExpr(state, U, Result); } else { nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); #if 0 SVal Result = EvalBinOp(BinaryOperator::EQ, cast<NonLoc>(V), X); state = SetSVal(state, U, Result); #else EvalBinOp(Dst, U, BinaryOperator::EQ, cast<NonLoc>(V), X, *I, U->getType()); continue; #endif } break; } MakeNode(Dst, U, *I, state); } return; } } // Handle ++ and -- (both pre- and post-increment). assert (U->isIncrementDecrementOp()); NodeSet Tmp; Expr* Ex = U->getSubExpr()->IgnoreParens(); VisitLValue(Ex, Pred, Tmp); for (NodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) { const GRState* state = GetState(*I); SVal V1 = GetSVal(state, Ex); // Perform a load. NodeSet Tmp2; EvalLoad(Tmp2, Ex, *I, state, V1); for (NodeSet::iterator I2 = Tmp2.begin(), E2 = Tmp2.end(); I2!=E2; ++I2) { state = GetState(*I2); SVal V2 = GetSVal(state, Ex); // Propagate unknown and undefined values. if (V2.isUnknownOrUndef()) { MakeNode(Dst, U, *I2, BindExpr(state, U, V2)); continue; } // Handle all other values. BinaryOperator::Opcode Op = U->isIncrementOp() ? BinaryOperator::Add : BinaryOperator::Sub; SVal Result = EvalBinOp(Op, V2, MakeConstantVal(1U, U), U->getType()); // Conjure a new symbol if necessary to recover precision. if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)) Result = ValMgr.getConjuredSymbolVal(Ex, Builder->getCurrentBlockCount()); state = BindExpr(state, U, U->isPostfix() ? V2 : Result); // Perform the store. EvalStore(Dst, U, *I2, state, V1, Result); } } } void GRExprEngine::VisitAsmStmt(AsmStmt* A, NodeTy* Pred, NodeSet& Dst) { VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst); } void GRExprEngine::VisitAsmStmtHelperOutputs(AsmStmt* A, AsmStmt::outputs_iterator I, AsmStmt::outputs_iterator E, NodeTy* Pred, NodeSet& Dst) { if (I == E) { VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst); return; } NodeSet Tmp; VisitLValue(*I, Pred, Tmp); ++I; for (NodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI != NE; ++NI) VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst); } void GRExprEngine::VisitAsmStmtHelperInputs(AsmStmt* A, AsmStmt::inputs_iterator I, AsmStmt::inputs_iterator E, NodeTy* Pred, NodeSet& Dst) { if (I == E) { // We have processed both the inputs and the outputs. All of the outputs // should evaluate to Locs. Nuke all of their values. // FIXME: Some day in the future it would be nice to allow a "plug-in" // which interprets the inline asm and stores proper results in the // outputs. const GRState* state = GetState(Pred); for (AsmStmt::outputs_iterator OI = A->begin_outputs(), OE = A->end_outputs(); OI != OE; ++OI) { SVal X = GetSVal(state, *OI); assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef. if (isa<Loc>(X)) state = BindLoc(state, cast<Loc>(X), UnknownVal()); } MakeNode(Dst, A, Pred, state); return; } NodeSet Tmp; Visit(*I, Pred, Tmp); ++I; for (NodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI != NE; ++NI) VisitAsmStmtHelperInputs(A, I, E, *NI, Dst); } void GRExprEngine::EvalReturn(NodeSet& Dst, ReturnStmt* S, NodeTy* Pred) { assert (Builder && "GRStmtNodeBuilder must be defined."); unsigned size = Dst.size(); SaveAndRestore<bool> OldSink(Builder->BuildSinks); SaveOr OldHasGen(Builder->HasGeneratedNode); getTF().EvalReturn(Dst, *this, *Builder, S, Pred); // Handle the case where no nodes where generated. if (!Builder->BuildSinks && Dst.size() == size && !Builder->HasGeneratedNode) MakeNode(Dst, S, Pred, GetState(Pred)); } void GRExprEngine::VisitReturnStmt(ReturnStmt* S, NodeTy* Pred, NodeSet& Dst) { Expr* R = S->getRetValue(); if (!R) { EvalReturn(Dst, S, Pred); return; } NodeSet Tmp; Visit(R, Pred, Tmp); for (NodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) { SVal X = GetSVal((*I)->getState(), R); // Check if we return the address of a stack variable. if (isa<loc::MemRegionVal>(X)) { // Determine if the value is on the stack. const MemRegion* R = cast<loc::MemRegionVal>(&X)->getRegion(); if (R && getStateManager().hasStackStorage(R)) { // Create a special node representing the error. if (NodeTy* N = Builder->generateNode(S, GetState(*I), *I)) { N->markAsSink(); RetsStackAddr.insert(N); } continue; } } // Check if we return an undefined value. else if (X.isUndef()) { if (NodeTy* N = Builder->generateNode(S, GetState(*I), *I)) { N->markAsSink(); RetsUndef.insert(N); } continue; } EvalReturn(Dst, S, *I); } } //===----------------------------------------------------------------------===// // Transfer functions: Binary operators. //===----------------------------------------------------------------------===// const GRState* GRExprEngine::CheckDivideZero(Expr* Ex, const GRState* state, NodeTy* Pred, SVal Denom) { // Divide by undefined? (potentially zero) if (Denom.isUndef()) { NodeTy* DivUndef = Builder->generateNode(Ex, state, Pred); if (DivUndef) { DivUndef->markAsSink(); ExplicitBadDivides.insert(DivUndef); } return 0; } // Check for divide/remainder-by-zero. // First, "assume" that the denominator is 0 or undefined. bool isFeasibleZero = false; const GRState* ZeroSt = Assume(state, Denom, false, isFeasibleZero); // Second, "assume" that the denominator cannot be 0. bool isFeasibleNotZero = false; state = Assume(state, Denom, true, isFeasibleNotZero); // Create the node for the divide-by-zero (if it occurred). if (isFeasibleZero) if (NodeTy* DivZeroNode = Builder->generateNode(Ex, ZeroSt, Pred)) { DivZeroNode->markAsSink(); if (isFeasibleNotZero) ImplicitBadDivides.insert(DivZeroNode); else ExplicitBadDivides.insert(DivZeroNode); } return isFeasibleNotZero ? state : 0; } void GRExprEngine::VisitBinaryOperator(BinaryOperator* B, GRExprEngine::NodeTy* Pred, GRExprEngine::NodeSet& Dst) { NodeSet Tmp1; Expr* LHS = B->getLHS()->IgnoreParens(); Expr* RHS = B->getRHS()->IgnoreParens(); // FIXME: Add proper support for ObjCKVCRefExpr. if (isa<ObjCKVCRefExpr>(LHS)) { Visit(RHS, Pred, Dst); return; } if (B->isAssignmentOp()) VisitLValue(LHS, Pred, Tmp1); else Visit(LHS, Pred, Tmp1); for (NodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1 != E1; ++I1) { SVal LeftV = GetSVal((*I1)->getState(), LHS); // Process the RHS. NodeSet Tmp2; Visit(RHS, *I1, Tmp2); // With both the LHS and RHS evaluated, process the operation itself. for (NodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end(); I2 != E2; ++I2) { const GRState* state = GetState(*I2); const GRState* OldSt = state; SVal RightV = GetSVal(state, RHS); BinaryOperator::Opcode Op = B->getOpcode(); switch (Op) { case BinaryOperator::Assign: { // EXPERIMENTAL: "Conjured" symbols. // FIXME: Handle structs. QualType T = RHS->getType(); if ((RightV.isUnknown() || !getConstraintManager().canReasonAbout(RightV)) && (Loc::IsLocType(T) || (T->isScalarType() && T->isIntegerType()))) { unsigned Count = Builder->getCurrentBlockCount(); RightV = ValMgr.getConjuredSymbolVal(B->getRHS(), Count); } // Simulate the effects of a "store": bind the value of the RHS // to the L-Value represented by the LHS. EvalStore(Dst, B, LHS, *I2, BindExpr(state, B, RightV), LeftV, RightV); continue; } case BinaryOperator::Div: case BinaryOperator::Rem: // Special checking for integer denominators. if (RHS->getType()->isIntegerType() && RHS->getType()->isScalarType()) { state = CheckDivideZero(B, state, *I2, RightV); if (!state) continue; } // FALL-THROUGH. default: { if (B->isAssignmentOp()) break; // Process non-assignements except commas or short-circuited // logical expressions (LAnd and LOr). SVal Result = EvalBinOp(Op, LeftV, RightV, B->getType()); if (Result.isUnknown()) { if (OldSt != state) { // Generate a new node if we have already created a new state. MakeNode(Dst, B, *I2, state); } else Dst.Add(*I2); continue; } if (Result.isUndef() && !LeftV.isUndef() && !RightV.isUndef()) { // The operands were *not* undefined, but the result is undefined. // This is a special node that should be flagged as an error. if (NodeTy* UndefNode = Builder->generateNode(B, state, *I2)) { UndefNode->markAsSink(); UndefResults.insert(UndefNode); } continue; } // Otherwise, create a new node. MakeNode(Dst, B, *I2, BindExpr(state, B, Result)); continue; } } assert (B->isCompoundAssignmentOp()); switch (Op) { default: assert(0 && "Invalid opcode for compound assignment."); case BinaryOperator::MulAssign: Op = BinaryOperator::Mul; break; case BinaryOperator::DivAssign: Op = BinaryOperator::Div; break; case BinaryOperator::RemAssign: Op = BinaryOperator::Rem; break; case BinaryOperator::AddAssign: Op = BinaryOperator::Add; break; case BinaryOperator::SubAssign: Op = BinaryOperator::Sub; break; case BinaryOperator::ShlAssign: Op = BinaryOperator::Shl; break; case BinaryOperator::ShrAssign: Op = BinaryOperator::Shr; break; case BinaryOperator::AndAssign: Op = BinaryOperator::And; break; case BinaryOperator::XorAssign: Op = BinaryOperator::Xor; break; case BinaryOperator::OrAssign: Op = BinaryOperator::Or; break; } // Perform a load (the LHS). This performs the checks for // null dereferences, and so on. NodeSet Tmp3; SVal location = GetSVal(state, LHS); EvalLoad(Tmp3, LHS, *I2, state, location); for (NodeSet::iterator I3=Tmp3.begin(), E3=Tmp3.end(); I3!=E3; ++I3) { state = GetState(*I3); SVal V = GetSVal(state, LHS); // Check for divide-by-zero. if ((Op == BinaryOperator::Div || Op == BinaryOperator::Rem) && RHS->getType()->isIntegerType() && RHS->getType()->isScalarType()) { // CheckDivideZero returns a new state where the denominator // is assumed to be non-zero. state = CheckDivideZero(B, state, *I3, RightV); if (!state) continue; } // Propagate undefined values (left-side). if (V.isUndef()) { EvalStore(Dst, B, LHS, *I3, BindExpr(state, B, V), location, V); continue; } // Propagate unknown values (left and right-side). if (RightV.isUnknown() || V.isUnknown()) { EvalStore(Dst, B, LHS, *I3, BindExpr(state, B, UnknownVal()), location, UnknownVal()); continue; } // At this point: // // The LHS is not Undef/Unknown. // The RHS is not Unknown. // Get the computation type. QualType CTy = cast<CompoundAssignOperator>(B)->getComputationResultType(); CTy = getContext().getCanonicalType(CTy); QualType CLHSTy = cast<CompoundAssignOperator>(B)->getComputationLHSType(); CLHSTy = getContext().getCanonicalType(CTy); QualType LTy = getContext().getCanonicalType(LHS->getType()); QualType RTy = getContext().getCanonicalType(RHS->getType()); // Promote LHS. V = EvalCast(V, CLHSTy); // Evaluate operands and promote to result type. if (RightV.isUndef()) { // Propagate undefined values (right-side). EvalStore(Dst, B, LHS, *I3, BindExpr(state, B, RightV), location, RightV); continue; } // Compute the result of the operation. SVal Result = EvalCast(EvalBinOp(Op, V, RightV, CTy), B->getType()); if (Result.isUndef()) { // The operands were not undefined, but the result is undefined. if (NodeTy* UndefNode = Builder->generateNode(B, state, *I3)) { UndefNode->markAsSink(); UndefResults.insert(UndefNode); } continue; } // EXPERIMENTAL: "Conjured" symbols. // FIXME: Handle structs. SVal LHSVal; if ((Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)) && (Loc::IsLocType(CTy) || (CTy->isScalarType() && CTy->isIntegerType()))) { unsigned Count = Builder->getCurrentBlockCount(); // The symbolic value is actually for the type of the left-hand side // expression, not the computation type, as this is the value the // LValue on the LHS will bind to. LHSVal = ValMgr.getConjuredSymbolVal(B->getRHS(), LTy, Count); // However, we need to convert the symbol to the computation type. Result = (LTy == CTy) ? LHSVal : EvalCast(LHSVal,CTy); } else { // The left-hand side may bind to a different value then the // computation type. LHSVal = (LTy == CTy) ? Result : EvalCast(Result,LTy); } EvalStore(Dst, B, LHS, *I3, BindExpr(state, B, Result), location, LHSVal); } } } } //===----------------------------------------------------------------------===// // Transfer-function Helpers. //===----------------------------------------------------------------------===// void GRExprEngine::EvalBinOp(ExplodedNodeSet<GRState>& Dst, Expr* Ex, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, ExplodedNode<GRState>* Pred, QualType T) { GRStateSet OStates; EvalBinOp(OStates, GetState(Pred), Ex, Op, L, R, T); for (GRStateSet::iterator I=OStates.begin(), E=OStates.end(); I!=E; ++I) MakeNode(Dst, Ex, Pred, *I); } void GRExprEngine::EvalBinOp(GRStateSet& OStates, const GRState* state, Expr* Ex, BinaryOperator::Opcode Op, NonLoc L, NonLoc R, QualType T) { GRStateSet::AutoPopulate AP(OStates, state); if (R.isValid()) getTF().EvalBinOpNN(OStates, *this, state, Ex, Op, L, R, T); } SVal GRExprEngine::EvalBinOp(BinaryOperator::Opcode Op, SVal L, SVal R, QualType T) { if (L.isUndef() || R.isUndef()) return UndefinedVal(); if (L.isUnknown() || R.isUnknown()) return UnknownVal(); if (isa<Loc>(L)) { if (isa<Loc>(R)) return getTF().EvalBinOp(*this, Op, cast<Loc>(L), cast<Loc>(R)); else return getTF().EvalBinOp(*this, Op, cast<Loc>(L), cast<NonLoc>(R)); } if (isa<Loc>(R)) { // Support pointer arithmetic where the increment/decrement operand // is on the left and the pointer on the right. assert (Op == BinaryOperator::Add || Op == BinaryOperator::Sub); // Commute the operands. return getTF().EvalBinOp(*this, Op, cast<Loc>(R), cast<NonLoc>(L)); } else return getTF().DetermEvalBinOpNN(*this, Op, cast<NonLoc>(L), cast<NonLoc>(R), T); } //===----------------------------------------------------------------------===// // Visualization. //===----------------------------------------------------------------------===// #ifndef NDEBUG static GRExprEngine* GraphPrintCheckerState; static SourceManager* GraphPrintSourceManager; namespace llvm { template<> struct VISIBILITY_HIDDEN DOTGraphTraits<GRExprEngine::NodeTy*> : public DefaultDOTGraphTraits { static std::string getNodeAttributes(const GRExprEngine::NodeTy* N, void*) { if (GraphPrintCheckerState->isImplicitNullDeref(N) || GraphPrintCheckerState->isExplicitNullDeref(N) || GraphPrintCheckerState->isUndefDeref(N) || GraphPrintCheckerState->isUndefStore(N) || GraphPrintCheckerState->isUndefControlFlow(N) || GraphPrintCheckerState->isExplicitBadDivide(N) || GraphPrintCheckerState->isImplicitBadDivide(N) || GraphPrintCheckerState->isUndefResult(N) || GraphPrintCheckerState->isBadCall(N) || GraphPrintCheckerState->isUndefArg(N)) return "color=\"red\",style=\"filled\""; if (GraphPrintCheckerState->isNoReturnCall(N)) return "color=\"blue\",style=\"filled\""; return ""; } static std::string getNodeLabel(const GRExprEngine::NodeTy* N, void*) { std::ostringstream Out; // Program Location. ProgramPoint Loc = N->getLocation(); switch (Loc.getKind()) { case ProgramPoint::BlockEntranceKind: Out << "Block Entrance: B" << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); break; case ProgramPoint::BlockExitKind: assert (false); break; default: { if (isa<PostStmt>(Loc)) { const PostStmt& L = cast<PostStmt>(Loc); Stmt* S = L.getStmt(); SourceLocation SLoc = S->getLocStart(); Out << S->getStmtClassName() << ' ' << (void*) S << ' '; llvm::raw_os_ostream OutS(Out); S->printPretty(OutS); OutS.flush(); if (SLoc.isFileID()) { Out << "\\lline=" << GraphPrintSourceManager->getInstantiationLineNumber(SLoc) << " col=" << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc) << "\\l"; } if (GraphPrintCheckerState->isImplicitNullDeref(N)) Out << "\\|Implicit-Null Dereference.\\l"; else if (GraphPrintCheckerState->isExplicitNullDeref(N)) Out << "\\|Explicit-Null Dereference.\\l"; else if (GraphPrintCheckerState->isUndefDeref(N)) Out << "\\|Dereference of undefialied value.\\l"; else if (GraphPrintCheckerState->isUndefStore(N)) Out << "\\|Store to Undefined Loc."; else if (GraphPrintCheckerState->isExplicitBadDivide(N)) Out << "\\|Explicit divide-by zero or undefined value."; else if (GraphPrintCheckerState->isImplicitBadDivide(N)) Out << "\\|Implicit divide-by zero or undefined value."; else if (GraphPrintCheckerState->isUndefResult(N)) Out << "\\|Result of operation is undefined."; else if (GraphPrintCheckerState->isNoReturnCall(N)) Out << "\\|Call to function marked \"noreturn\"."; else if (GraphPrintCheckerState->isBadCall(N)) Out << "\\|Call to NULL/Undefined."; else if (GraphPrintCheckerState->isUndefArg(N)) Out << "\\|Argument in call is undefined"; break; } const BlockEdge& E = cast<BlockEdge>(Loc); Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" << E.getDst()->getBlockID() << ')'; if (Stmt* T = E.getSrc()->getTerminator()) { SourceLocation SLoc = T->getLocStart(); Out << "\\|Terminator: "; llvm::raw_os_ostream OutS(Out); E.getSrc()->printTerminator(OutS); OutS.flush(); if (SLoc.isFileID()) { Out << "\\lline=" << GraphPrintSourceManager->getInstantiationLineNumber(SLoc) << " col=" << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc); } if (isa<SwitchStmt>(T)) { Stmt* Label = E.getDst()->getLabel(); if (Label) { if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) { Out << "\\lcase "; llvm::raw_os_ostream OutS(Out); C->getLHS()->printPretty(OutS); OutS.flush(); if (Stmt* RHS = C->getRHS()) { Out << " .. "; RHS->printPretty(OutS); OutS.flush(); } Out << ":"; } else { assert (isa<DefaultStmt>(Label)); Out << "\\ldefault:"; } } else Out << "\\l(implicit) default:"; } else if (isa<IndirectGotoStmt>(T)) { // FIXME } else { Out << "\\lCondition: "; if (*E.getSrc()->succ_begin() == E.getDst()) Out << "true"; else Out << "false"; } Out << "\\l"; } if (GraphPrintCheckerState->isUndefControlFlow(N)) { Out << "\\|Control-flow based on\\lUndefined value.\\l"; } } } Out << "\\|StateID: " << (void*) N->getState() << "\\|"; GRStateRef state(N->getState(), GraphPrintCheckerState->getStateManager()); state.printDOT(Out); Out << "\\l"; return Out.str(); } }; } // end llvm namespace #endif #ifndef NDEBUG template <typename ITERATOR> GRExprEngine::NodeTy* GetGraphNode(ITERATOR I) { return *I; } template <> GRExprEngine::NodeTy* GetGraphNode<llvm::DenseMap<GRExprEngine::NodeTy*, Expr*>::iterator> (llvm::DenseMap<GRExprEngine::NodeTy*, Expr*>::iterator I) { return I->first; } #endif void GRExprEngine::ViewGraph(bool trim) { #ifndef NDEBUG if (trim) { std::vector<NodeTy*> Src; // Flush any outstanding reports to make sure we cover all the nodes. // This does not cause them to get displayed. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) const_cast<BugType*>(*I)->FlushReports(BR); // Iterate through the reports and get their nodes. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) { for (BugType::const_iterator I2=(*I)->begin(), E2=(*I)->end(); I2!=E2; ++I2) { const BugReportEquivClass& EQ = *I2; const BugReport &R = **EQ.begin(); NodeTy *N = const_cast<NodeTy*>(R.getEndNode()); if (N) Src.push_back(N); } } ViewGraph(&Src[0], &Src[0]+Src.size()); } else { GraphPrintCheckerState = this; GraphPrintSourceManager = &getContext().getSourceManager(); llvm::ViewGraph(*G.roots_begin(), "GRExprEngine"); GraphPrintCheckerState = NULL; GraphPrintSourceManager = NULL; } #endif } void GRExprEngine::ViewGraph(NodeTy** Beg, NodeTy** End) { #ifndef NDEBUG GraphPrintCheckerState = this; GraphPrintSourceManager = &getContext().getSourceManager(); std::auto_ptr<GRExprEngine::GraphTy> TrimmedG(G.Trim(Beg, End).first); if (!TrimmedG.get()) llvm::cerr << "warning: Trimmed ExplodedGraph is empty.\n"; else llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedGRExprEngine"); GraphPrintCheckerState = NULL; GraphPrintSourceManager = NULL; #endif } <file_sep>/test/CodeGen/static-forward-decl-fun.c // RUN: clang-cc %s -emit-llvm -o %t static int staticfun(void); int (*staticuse1)(void) = staticfun; static int staticfun() {return 1;} int (*staticuse2)(void) = staticfun; <file_sep>/test/Analysis/cfref_rdar6080742.c // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -analyzer-constraints=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=basic -analyzer-constraints=range -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -analyzer-constraints=basic -verify %s && // RUN: clang-cc -analyze -checker-cfref -analyzer-store=region -analyzer-constraints=range -verify %s // This test case was reported in <rdar:problem/6080742>. // It tests path-sensitivity with respect to '!(cfstring != 0)' (negation of inequality). int printf(const char *restrict,...); typedef unsigned long UInt32; typedef signed long SInt32; typedef SInt32 OSStatus; typedef unsigned char Boolean; enum { noErr = 0}; typedef const void *CFTypeRef; typedef const struct __CFString *CFStringRef; typedef const struct __CFAllocator *CFAllocatorRef; extern void CFRelease(CFTypeRef cf); typedef UInt32 CFStringEncoding; enum { kCFStringEncodingMacRoman = 0, kCFStringEncodingWindowsLatin1 = 0x0500, kCFStringEncodingISOLatin1 = 0x0201, kCFStringEncodingNextStepLatin = 0x0B01, kCFStringEncodingASCII = 0x0600, kCFStringEncodingUnicode = 0x0100, kCFStringEncodingUTF8 = 0x08000100, kCFStringEncodingNonLossyASCII = 0x0BFF, kCFStringEncodingUTF16 = 0x0100, kCFStringEncodingUTF16BE = 0x10000100, kCFStringEncodingUTF16LE = 0x14000100, kCFStringEncodingUTF32 = 0x0c000100, kCFStringEncodingUTF32BE = 0x18000100, kCFStringEncodingUTF32LE = 0x1c000100}; extern CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding); enum { memROZWarn = -99, memROZError = -99, memROZErr = -99, memFullErr = -108, nilHandleErr = -109, memWZErr = -111, memPurErr = -112, memAdrErr = -110, memAZErr = -113, memPCErr = -114, memBCErr = -115, memSCErr = -116, memLockedErr = -117}; #define DEBUG1 void DebugStop(const char *format,...); void DebugTraceIf(unsigned int condition, const char *format,...); Boolean DebugDisplayOSStatusMsg(OSStatus status, const char *statusStr, const char *fileName, unsigned long lineNumber); #define Assert(condition)if (!(condition)) { DebugStop("Assertion failure: %s [File: %s, Line: %lu]", #condition, __FILE__, __LINE__); } #define AssertMsg(condition, message)if (!(condition)) { DebugStop("Assertion failure: %s (%s) [File: %s, Line: %lu]", #condition, message, __FILE__, __LINE__); } #define Require(condition)if (!(condition)) { DebugStop("Assertion failure: %s [File: %s, Line: %lu]", #condition, __FILE__, __LINE__); } #define RequireAction(condition, action)if (!(condition)) { DebugStop("Assertion failure: %s [File: %s, Line: %lu]", #condition, __FILE__, __LINE__); action } #define RequireActionSilent(condition, action)if (!(condition)) { action } #define AssertNoErr(err){ DebugDisplayOSStatusMsg((err), #err, __FILE__, __LINE__); } #define RequireNoErr(err, action){ if( DebugDisplayOSStatusMsg((err), #err, __FILE__, __LINE__) ) { action }} void DebugStop(const char *format,...); /* Not an abort function. */ int main(int argc, char *argv[]) { CFStringRef cfString; OSStatus status = noErr; cfString = CFStringCreateWithCString(0, "hello", kCFStringEncodingUTF8); RequireAction(cfString != 0, return memFullErr;) //no - warning printf("cfstring %p\n", cfString); Exit: CFRelease(cfString); return 0; } <file_sep>/tools/driver/CMakeLists.txt set(LLVM_NO_RTTI 1) set( LLVM_USED_LIBS clangDriver clangBasic ) set(LLVM_LINK_COMPONENTS system support bitreader bitwriter) add_clang_executable(clang driver.cpp ) <file_sep>/test/CodeGen/functions.c // RUN: clang-cc %s -emit-llvm -o %t && int g(); int foo(int i) { return g(i); } int g(int i) { return g(i); } // rdar://6110827 typedef void T(void); void test3(T f) { f(); } int a(int); int a() {return 1;} // RUN: grep 'define void @f0()' %t && void f0() {} void f1(); // RUN: grep 'call void (...)\* bitcast (void ()\* @f1' %t && void f2(void) { f1(1, 2, 3); } // RUN: grep 'define void @f1()' %t && void f1() {} // RUN: grep 'define .* @f3' %t | not grep -F '...' struct foo { int X, Y, Z; } f3() { } <file_sep>/utils/test/TestRunner.py #!/usr/bin/python # # TestRunner.py - This script is used to run arbitrary unit tests. Unit # tests must contain the command used to run them in the input file, starting # immediately after a "RUN:" string. # # This runner recognizes and replaces the following strings in the command: # # %s - Replaced with the input name of the program, or the program to # execute, as appropriate. # %S - Replaced with the directory where the input resides. # %llvmgcc - llvm-gcc command # %llvmgxx - llvm-g++ command # %prcontext - prcontext.tcl script # %t - temporary file name (derived from testcase name) # import os import sys import subprocess import errno import re class TestStatus: Pass = 0 XFail = 1 Fail = 2 XPass = 3 NoRunLine = 4 Invalid = 5 kNames = ['Pass','XFail','Fail','XPass','NoRunLine','Invalid'] @staticmethod def getName(code): return TestStatus.kNames[code] def mkdir_p(path): if not path: pass elif os.path.exists(path): pass else: parent = os.path.dirname(path) if parent != path: mkdir_p(parent) try: os.mkdir(path) except OSError,e: if e.errno != errno.EEXIST: raise def remove(path): try: os.remove(path) except OSError: pass def cat(path, output): f = open(path) output.writelines(f) f.close() def runOneTest(FILENAME, SUBST, OUTPUT, TESTNAME, CLANG, useValgrind=False, useDGCompat=False, useScript=None, output=sys.stdout): if useValgrind: VG_OUTPUT = '%s.vg'%(OUTPUT,) if os.path.exists: remove(VG_OUTPUT) CLANG = 'valgrind --leak-check=full --quiet --log-file=%s %s'%(VG_OUTPUT, CLANG) # Create the output directory if it does not already exist. mkdir_p(os.path.dirname(OUTPUT)) # FIXME #ulimit -t 40 # FIXME: Load script once # FIXME: Support "short" script syntax if useScript: scriptFile = useScript else: # See if we have a per-dir test script. dirScriptFile = os.path.join(os.path.dirname(FILENAME), 'test.script') if os.path.exists(dirScriptFile): scriptFile = dirScriptFile else: scriptFile = FILENAME # Verify the script contains a run line. for ln in open(scriptFile): if 'RUN:' in ln: break else: print >>output, "******************** TEST '%s' HAS NO RUN LINE! ********************"%(TESTNAME,) output.flush() return TestStatus.NoRunLine OUTPUT = os.path.abspath(OUTPUT) FILENAME = os.path.abspath(FILENAME) SCRIPT = OUTPUT + '.script' TEMPOUTPUT = OUTPUT + '.tmp' substitutions = [('%s',SUBST), ('%S',os.path.dirname(SUBST)), ('%llvmgcc','llvm-gcc -emit-llvm -w'), ('%llvmgxx','llvm-g++ -emit-llvm -w'), ('%prcontext','prcontext.tcl'), ('%t',TEMPOUTPUT), ('clang',CLANG)] scriptLines = [] xfailLines = [] for ln in open(scriptFile): if 'RUN:' in ln: # Isolate run parameters index = ln.index('RUN:') ln = ln[index+4:] # Apply substitutions for a,b in substitutions: ln = ln.replace(a,b) if useDGCompat: ln = re.sub(r'\{(.*)\}', r'"\1"', ln) scriptLines.append(ln) elif 'XFAIL' in ln: xfailLines.append(ln) if xfailLines: print >>output, "XFAILED '%s':"%(TESTNAME,) output.writelines(xfailLines) # Write script file f = open(SCRIPT,'w') f.write(''.join(scriptLines)) f.close() outputFile = open(OUTPUT,'w') p = None try: p = subprocess.Popen(["/bin/sh",SCRIPT], cwd=os.path.dirname(FILENAME), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() outputFile.write(out) outputFile.write(err) SCRIPT_STATUS = p.wait() except KeyboardInterrupt: if p is not None: os.kill(p.pid) raise outputFile.close() if xfailLines: SCRIPT_STATUS = not SCRIPT_STATUS if useValgrind: VG_STATUS = len(list(open(VG_OUTPUT))) else: VG_STATUS = 0 if SCRIPT_STATUS or VG_STATUS: print >>output, "******************** TEST '%s' FAILED! ********************"%(TESTNAME,) print >>output, "Command: " output.writelines(scriptLines) if not SCRIPT_STATUS: print >>output, "Output:" else: print >>output, "Incorrect Output:" cat(OUTPUT, output) if VG_STATUS: print >>output, "Valgrind Output:" cat(VG_OUTPUT, output) print >>output, "******************** TEST '%s' FAILED! ********************"%(TESTNAME,) output.flush() if xfailLines: return TestStatus.XPass else: return TestStatus.Fail if xfailLines: return TestStatus.XFail else: return TestStatus.Pass def main(): _,path = sys.argv command = path # Use hand concatentation here because we want to override # absolute paths. output = 'Output/' + path + '.out' testname = path # Determine which clang to use. CLANG = os.getenv('CLANG') if not CLANG: CLANG = 'clang' res = runOneTest(path, command, output, testname, CLANG, useValgrind=bool(os.getenv('VG')), useDGCompat=bool(os.getenv('DG_COMPAT')), useScript=os.getenv("TEST_SCRIPT")) sys.exit(res == TestStatus.Fail or res == TestStatus.XPass) if __name__=='__main__': main() <file_sep>/include/clang/Analysis/PathSensitive/ExplodedGraph.h //=-- ExplodedGraph.h - Local, Path-Sens. "Exploded Graph" -*- C++ -*-------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the template classes ExplodedNode and ExplodedGraph, // which represent a path-sensitive, intra-procedural "exploded graph." // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ANALYSIS_EXPLODEDGRAPH #define LLVM_CLANG_ANALYSIS_EXPLODEDGRAPH #include "clang/Analysis/ProgramPoint.h" #include "clang/AST/Decl.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Support/Allocator.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/GraphTraits.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/Support/Casting.h" namespace clang { class GRCoreEngineImpl; class ExplodedNodeImpl; class CFG; class ASTContext; class GRStmtNodeBuilderImpl; class GRBranchNodeBuilderImpl; class GRIndirectGotoNodeBuilderImpl; class GRSwitchNodeBuilderImpl; class GREndPathNodebuilderImpl; //===----------------------------------------------------------------------===// // ExplodedGraph "implementation" classes. These classes are not typed to // contain a specific kind of state. Typed-specialized versions are defined // on top of these classes. //===----------------------------------------------------------------------===// class ExplodedNodeImpl : public llvm::FoldingSetNode { protected: friend class ExplodedGraphImpl; friend class GRCoreEngineImpl; friend class GRStmtNodeBuilderImpl; friend class GRBranchNodeBuilderImpl; friend class GRIndirectGotoNodeBuilderImpl; friend class GRSwitchNodeBuilderImpl; friend class GREndPathNodeBuilderImpl; class NodeGroup { enum { Size1 = 0x0, SizeOther = 0x1, AuxFlag = 0x2, Mask = 0x3 }; uintptr_t P; unsigned getKind() const { return P & 0x1; } void* getPtr() const { assert (!getFlag()); return reinterpret_cast<void*>(P & ~Mask); } ExplodedNodeImpl* getNode() const { return reinterpret_cast<ExplodedNodeImpl*>(getPtr()); } public: NodeGroup() : P(0) {} ~NodeGroup(); ExplodedNodeImpl** begin() const; ExplodedNodeImpl** end() const; unsigned size() const; bool empty() const { return size() == 0; } void addNode(ExplodedNodeImpl* N); void setFlag() { assert (P == 0); P = AuxFlag; } bool getFlag() const { return P & AuxFlag ? true : false; } }; /// Location - The program location (within a function body) associated /// with this node. const ProgramPoint Location; /// State - The state associated with this node. const void* State; /// Preds - The predecessors of this node. NodeGroup Preds; /// Succs - The successors of this node. NodeGroup Succs; /// Construct a ExplodedNodeImpl with the provided location and state. explicit ExplodedNodeImpl(const ProgramPoint& loc, const void* state) : Location(loc), State(state) {} /// addPredeccessor - Adds a predecessor to the current node, and /// in tandem add this node as a successor of the other node. void addPredecessor(ExplodedNodeImpl* V); public: /// getLocation - Returns the edge associated with the given node. ProgramPoint getLocation() const { return Location; } unsigned succ_size() const { return Succs.size(); } unsigned pred_size() const { return Preds.size(); } bool succ_empty() const { return Succs.empty(); } bool pred_empty() const { return Preds.empty(); } bool isSink() const { return Succs.getFlag(); } void markAsSink() { Succs.setFlag(); } // For debugging. public: class Auditor { public: virtual ~Auditor(); virtual void AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst) = 0; }; static void SetAuditor(Auditor* A); }; template <typename StateTy> struct GRTrait { static inline void Profile(llvm::FoldingSetNodeID& ID, const StateTy* St) { St->Profile(ID); } }; template <typename StateTy> class ExplodedNode : public ExplodedNodeImpl { public: /// Construct a ExplodedNodeImpl with the given node ID, program edge, /// and state. explicit ExplodedNode(const ProgramPoint& loc, const StateTy* St) : ExplodedNodeImpl(loc, St) {} /// getState - Returns the state associated with the node. inline const StateTy* getState() const { return static_cast<const StateTy*>(State); } // Profiling (for FoldingSet). static inline void Profile(llvm::FoldingSetNodeID& ID, const ProgramPoint& Loc, const StateTy* state) { ID.Add(Loc); GRTrait<StateTy>::Profile(ID, state); } inline void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, getLocation(), getState()); } void addPredecessor(ExplodedNode* V) { ExplodedNodeImpl::addPredecessor(V); } // Iterators over successor and predecessor vertices. typedef ExplodedNode** succ_iterator; typedef const ExplodedNode* const * const_succ_iterator; typedef ExplodedNode** pred_iterator; typedef const ExplodedNode* const * const_pred_iterator; pred_iterator pred_begin() { return (ExplodedNode**) Preds.begin(); } pred_iterator pred_end() { return (ExplodedNode**) Preds.end(); } const_pred_iterator pred_begin() const { return const_cast<ExplodedNode*>(this)->pred_begin(); } const_pred_iterator pred_end() const { return const_cast<ExplodedNode*>(this)->pred_end(); } succ_iterator succ_begin() { return (ExplodedNode**) Succs.begin(); } succ_iterator succ_end() { return (ExplodedNode**) Succs.end(); } const_succ_iterator succ_begin() const { return const_cast<ExplodedNode*>(this)->succ_begin(); } const_succ_iterator succ_end() const { return const_cast<ExplodedNode*>(this)->succ_end(); } }; class InterExplodedGraphMapImpl; class ExplodedGraphImpl { protected: friend class GRCoreEngineImpl; friend class GRStmtNodeBuilderImpl; friend class GRBranchNodeBuilderImpl; friend class GRIndirectGotoNodeBuilderImpl; friend class GRSwitchNodeBuilderImpl; friend class GREndPathNodeBuilderImpl; // Type definitions. typedef llvm::SmallVector<ExplodedNodeImpl*,2> RootsTy; typedef llvm::SmallVector<ExplodedNodeImpl*,10> EndNodesTy; /// Roots - The roots of the simulation graph. Usually there will be only /// one, but clients are free to establish multiple subgraphs within a single /// SimulGraph. Moreover, these subgraphs can often merge when paths from /// different roots reach the same state at the same program location. RootsTy Roots; /// EndNodes - The nodes in the simulation graph which have been /// specially marked as the endpoint of an abstract simulation path. EndNodesTy EndNodes; /// Allocator - BumpPtrAllocator to create nodes. llvm::BumpPtrAllocator Allocator; /// cfg - The CFG associated with this analysis graph. CFG& cfg; /// CodeDecl - The declaration containing the code being analyzed. This /// can be a FunctionDecl or and ObjCMethodDecl. Decl& CodeDecl; /// Ctx - The ASTContext used to "interpret" CodeDecl. ASTContext& Ctx; /// NumNodes - The number of nodes in the graph. unsigned NumNodes; /// getNodeImpl - Retrieve the node associated with a (Location,State) /// pair, where 'State' is represented as an opaque void*. This method /// is intended to be used only by GRCoreEngineImpl. virtual ExplodedNodeImpl* getNodeImpl(const ProgramPoint& L, const void* State, bool* IsNew) = 0; virtual ExplodedGraphImpl* MakeEmptyGraph() const = 0; /// addRoot - Add an untyped node to the set of roots. ExplodedNodeImpl* addRoot(ExplodedNodeImpl* V) { Roots.push_back(V); return V; } /// addEndOfPath - Add an untyped node to the set of EOP nodes. ExplodedNodeImpl* addEndOfPath(ExplodedNodeImpl* V) { EndNodes.push_back(V); return V; } // ctor. ExplodedGraphImpl(CFG& c, Decl& cd, ASTContext& ctx) : cfg(c), CodeDecl(cd), Ctx(ctx), NumNodes(0) {} public: virtual ~ExplodedGraphImpl() {} unsigned num_roots() const { return Roots.size(); } unsigned num_eops() const { return EndNodes.size(); } bool empty() const { return NumNodes == 0; } unsigned size() const { return NumNodes; } llvm::BumpPtrAllocator& getAllocator() { return Allocator; } CFG& getCFG() { return cfg; } ASTContext& getContext() { return Ctx; } Decl& getCodeDecl() { return CodeDecl; } const Decl& getCodeDecl() const { return CodeDecl; } const FunctionDecl* getFunctionDecl() const { return llvm::dyn_cast<FunctionDecl>(&CodeDecl); } typedef llvm::DenseMap<const ExplodedNodeImpl*, ExplodedNodeImpl*> NodeMap; ExplodedGraphImpl* Trim(const ExplodedNodeImpl* const * NBeg, const ExplodedNodeImpl* const * NEnd, InterExplodedGraphMapImpl *M, llvm::DenseMap<const void*, const void*> *InverseMap) const; }; class InterExplodedGraphMapImpl { llvm::DenseMap<const ExplodedNodeImpl*, ExplodedNodeImpl*> M; friend class ExplodedGraphImpl; void add(const ExplodedNodeImpl* From, ExplodedNodeImpl* To); protected: ExplodedNodeImpl* getMappedImplNode(const ExplodedNodeImpl* N) const; InterExplodedGraphMapImpl(); public: virtual ~InterExplodedGraphMapImpl() {} }; //===----------------------------------------------------------------------===// // Type-specialized ExplodedGraph classes. //===----------------------------------------------------------------------===// template <typename STATE> class InterExplodedGraphMap : public InterExplodedGraphMapImpl { public: InterExplodedGraphMap() {}; ~InterExplodedGraphMap() {}; ExplodedNode<STATE>* getMappedNode(const ExplodedNode<STATE>* N) const { return static_cast<ExplodedNode<STATE>*>(getMappedImplNode(N)); } }; template <typename STATE> class ExplodedGraph : public ExplodedGraphImpl { public: typedef STATE StateTy; typedef ExplodedNode<StateTy> NodeTy; typedef llvm::FoldingSet<NodeTy> AllNodesTy; protected: /// Nodes - The nodes in the graph. AllNodesTy Nodes; protected: virtual ExplodedNodeImpl* getNodeImpl(const ProgramPoint& L, const void* State, bool* IsNew) { return getNode(L, static_cast<const StateTy*>(State), IsNew); } virtual ExplodedGraphImpl* MakeEmptyGraph() const { return new ExplodedGraph(cfg, CodeDecl, Ctx); } public: ExplodedGraph(CFG& c, Decl& cd, ASTContext& ctx) : ExplodedGraphImpl(c, cd, ctx) {} /// getNode - Retrieve the node associated with a (Location,State) pair, /// where the 'Location' is a ProgramPoint in the CFG. If no node for /// this pair exists, it is created. IsNew is set to true if /// the node was freshly created. NodeTy* getNode(const ProgramPoint& L, const StateTy* State, bool* IsNew = NULL) { // Profile 'State' to determine if we already have an existing node. llvm::FoldingSetNodeID profile; void* InsertPos = 0; NodeTy::Profile(profile, L, State); NodeTy* V = Nodes.FindNodeOrInsertPos(profile, InsertPos); if (!V) { // Allocate a new node. V = (NodeTy*) Allocator.Allocate<NodeTy>(); new (V) NodeTy(L, State); // Insert the node into the node set and return it. Nodes.InsertNode(V, InsertPos); ++NumNodes; if (IsNew) *IsNew = true; } else if (IsNew) *IsNew = false; return V; } // Iterators. typedef NodeTy** roots_iterator; typedef const NodeTy** const_roots_iterator; typedef NodeTy** eop_iterator; typedef const NodeTy** const_eop_iterator; typedef typename AllNodesTy::iterator node_iterator; typedef typename AllNodesTy::const_iterator const_node_iterator; node_iterator nodes_begin() { return Nodes.begin(); } node_iterator nodes_end() { return Nodes.end(); } const_node_iterator nodes_begin() const { return Nodes.begin(); } const_node_iterator nodes_end() const { return Nodes.end(); } roots_iterator roots_begin() { return reinterpret_cast<roots_iterator>(Roots.begin()); } roots_iterator roots_end() { return reinterpret_cast<roots_iterator>(Roots.end()); } const_roots_iterator roots_begin() const { return const_cast<ExplodedGraph>(this)->roots_begin(); } const_roots_iterator roots_end() const { return const_cast<ExplodedGraph>(this)->roots_end(); } eop_iterator eop_begin() { return reinterpret_cast<eop_iterator>(EndNodes.begin()); } eop_iterator eop_end() { return reinterpret_cast<eop_iterator>(EndNodes.end()); } const_eop_iterator eop_begin() const { return const_cast<ExplodedGraph>(this)->eop_begin(); } const_eop_iterator eop_end() const { return const_cast<ExplodedGraph>(this)->eop_end(); } std::pair<ExplodedGraph*, InterExplodedGraphMap<STATE>*> Trim(const NodeTy* const* NBeg, const NodeTy* const* NEnd, llvm::DenseMap<const void*, const void*> *InverseMap = 0) const { if (NBeg == NEnd) return std::make_pair((ExplodedGraph*) 0, (InterExplodedGraphMap<STATE>*) 0); assert (NBeg < NEnd); const ExplodedNodeImpl* const* NBegImpl = (const ExplodedNodeImpl* const*) NBeg; const ExplodedNodeImpl* const* NEndImpl = (const ExplodedNodeImpl* const*) NEnd; llvm::OwningPtr<InterExplodedGraphMap<STATE> > M(new InterExplodedGraphMap<STATE>()); ExplodedGraphImpl* G = ExplodedGraphImpl::Trim(NBegImpl, NEndImpl, M.get(), InverseMap); return std::make_pair(static_cast<ExplodedGraph*>(G), M.take()); } }; template <typename StateTy> class ExplodedNodeSet { typedef ExplodedNode<StateTy> NodeTy; typedef llvm::SmallPtrSet<NodeTy*,5> ImplTy; ImplTy Impl; public: ExplodedNodeSet(NodeTy* N) { assert (N && !static_cast<ExplodedNodeImpl*>(N)->isSink()); Impl.insert(N); } ExplodedNodeSet() {} inline void Add(NodeTy* N) { if (N && !static_cast<ExplodedNodeImpl*>(N)->isSink()) Impl.insert(N); } typedef typename ImplTy::iterator iterator; typedef typename ImplTy::const_iterator const_iterator; inline unsigned size() const { return Impl.size(); } inline bool empty() const { return Impl.empty(); } inline void clear() { Impl.clear(); } inline iterator begin() { return Impl.begin(); } inline iterator end() { return Impl.end(); } inline const_iterator begin() const { return Impl.begin(); } inline const_iterator end() const { return Impl.end(); } }; } // end clang namespace // GraphTraits namespace llvm { template<typename StateTy> struct GraphTraits<clang::ExplodedNode<StateTy>*> { typedef clang::ExplodedNode<StateTy> NodeType; typedef typename NodeType::succ_iterator ChildIteratorType; typedef llvm::df_iterator<NodeType*> nodes_iterator; static inline NodeType* getEntryNode(NodeType* N) { return N; } static inline ChildIteratorType child_begin(NodeType* N) { return N->succ_begin(); } static inline ChildIteratorType child_end(NodeType* N) { return N->succ_end(); } static inline nodes_iterator nodes_begin(NodeType* N) { return df_begin(N); } static inline nodes_iterator nodes_end(NodeType* N) { return df_end(N); } }; template<typename StateTy> struct GraphTraits<const clang::ExplodedNode<StateTy>*> { typedef const clang::ExplodedNode<StateTy> NodeType; typedef typename NodeType::succ_iterator ChildIteratorType; typedef llvm::df_iterator<NodeType*> nodes_iterator; static inline NodeType* getEntryNode(NodeType* N) { return N; } static inline ChildIteratorType child_begin(NodeType* N) { return N->succ_begin(); } static inline ChildIteratorType child_end(NodeType* N) { return N->succ_end(); } static inline nodes_iterator nodes_begin(NodeType* N) { return df_begin(N); } static inline nodes_iterator nodes_end(NodeType* N) { return df_end(N); } }; } // end llvm namespace #endif <file_sep>/test/Preprocessor/if_warning.c // RUN: clang-cc %s -E -Wundef -Werror 2>&1 | grep error | count 1 && // RUN: clang-cc %s -E -Werror 2>&1 | not grep error #if foo // Should generate an warning #endif #ifdef foo #endif #if defined(foo) #endif <file_sep>/test/Sema/text-diag.c // RUN: clang-cc -fsyntax-only %s unsigned char *foo = "texto\ que continua\ e continua"; <file_sep>/test/CodeGen/blocks.c // RUN: clang-cc %s -emit-llvm -o %t -fblocks void (^f)(void) = ^{}; // rdar://6768379 int f0(int (^a0)()) { return a0(1, 2, 3); } <file_sep>/test/Sema/implicit-def.c /* RUN: clang-cc -fsyntax-only %s -std=c89 && * RUN: not clang-cc -fsyntax-only %s -std=c99 -pedantic-errors */ int A() { return X(); } <file_sep>/test/CodeGen/mmintrin-test.c // RUN: clang-cc -triple i386-apple-darwin9 -emit-llvm -o %t %s && // RUN: grep define %t | count 1 && // RUN: clang-cc -triple i386-apple-darwin9 -g -emit-llvm -o %t %s && // RUN: grep define %t | count 1 #include <mmintrin.h> #include <stdio.h> int main(int argc, char *argv[]) { int array[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; __m64 *p = (__m64 *)array; __m64 accum = _mm_setzero_si64(); for (int i=0; i<8; ++i) accum = _mm_add_pi32(p[i], accum); __m64 accum2 = _mm_unpackhi_pi32(accum, accum); accum = _mm_add_pi32(accum, accum2); int result = _mm_cvtsi64_si32(accum); _mm_empty(); printf("%d\n", result ); return 0; } <file_sep>/lib/AST/ExprCXX.cpp //===--- ExprCXX.cpp - (C++) Expression AST Node Implementation -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the subclesses of Expr class declared in ExprCXX.h // //===----------------------------------------------------------------------===// #include "clang/Basic/IdentifierTable.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/ExprCXX.h" using namespace clang; void CXXConditionDeclExpr::Destroy(ASTContext& C) { // FIXME: Cannot destroy the decl here, because it is linked into the // DeclContext's chain. //getVarDecl()->Destroy(C); this->~CXXConditionDeclExpr(); C.Deallocate(this); } //===----------------------------------------------------------------------===// // Child Iterators for iterating over subexpressions/substatements //===----------------------------------------------------------------------===// // CXXTypeidExpr - has child iterators if the operand is an expression Stmt::child_iterator CXXTypeidExpr::child_begin() { return isTypeOperand() ? child_iterator() : &Operand.Ex; } Stmt::child_iterator CXXTypeidExpr::child_end() { return isTypeOperand() ? child_iterator() : &Operand.Ex+1; } // CXXBoolLiteralExpr Stmt::child_iterator CXXBoolLiteralExpr::child_begin() { return child_iterator(); } Stmt::child_iterator CXXBoolLiteralExpr::child_end() { return child_iterator(); } // CXXThisExpr Stmt::child_iterator CXXThisExpr::child_begin() { return child_iterator(); } Stmt::child_iterator CXXThisExpr::child_end() { return child_iterator(); } // CXXThrowExpr Stmt::child_iterator CXXThrowExpr::child_begin() { return &Op; } Stmt::child_iterator CXXThrowExpr::child_end() { // If Op is 0, we are processing throw; which has no children. return Op ? &Op+1 : &Op; } // CXXDefaultArgExpr Stmt::child_iterator CXXDefaultArgExpr::child_begin() { return child_iterator(); } Stmt::child_iterator CXXDefaultArgExpr::child_end() { return child_iterator(); } // CXXTemporaryObjectExpr Stmt::child_iterator CXXTemporaryObjectExpr::child_begin() { return child_iterator(Args); } Stmt::child_iterator CXXTemporaryObjectExpr::child_end() { return child_iterator(Args + NumArgs); } // CXXZeroInitValueExpr Stmt::child_iterator CXXZeroInitValueExpr::child_begin() { return child_iterator(); } Stmt::child_iterator CXXZeroInitValueExpr::child_end() { return child_iterator(); } // CXXConditionDeclExpr Stmt::child_iterator CXXConditionDeclExpr::child_begin() { return getVarDecl(); } Stmt::child_iterator CXXConditionDeclExpr::child_end() { return child_iterator(); } // CXXNewExpr CXXNewExpr::CXXNewExpr(bool globalNew, FunctionDecl *operatorNew, Expr **placementArgs, unsigned numPlaceArgs, bool parenTypeId, Expr *arraySize, CXXConstructorDecl *constructor, bool initializer, Expr **constructorArgs, unsigned numConsArgs, FunctionDecl *operatorDelete, QualType ty, SourceLocation startLoc, SourceLocation endLoc) : Expr(CXXNewExprClass, ty, ty->isDependentType(), ty->isDependentType()), GlobalNew(globalNew), ParenTypeId(parenTypeId), Initializer(initializer), Array(arraySize), NumPlacementArgs(numPlaceArgs), NumConstructorArgs(numConsArgs), OperatorNew(operatorNew), OperatorDelete(operatorDelete), Constructor(constructor), StartLoc(startLoc), EndLoc(endLoc) { unsigned TotalSize = Array + NumPlacementArgs + NumConstructorArgs; SubExprs = new Stmt*[TotalSize]; unsigned i = 0; if (Array) SubExprs[i++] = arraySize; for (unsigned j = 0; j < NumPlacementArgs; ++j) SubExprs[i++] = placementArgs[j]; for (unsigned j = 0; j < NumConstructorArgs; ++j) SubExprs[i++] = constructorArgs[j]; assert(i == TotalSize); } Stmt::child_iterator CXXNewExpr::child_begin() { return &SubExprs[0]; } Stmt::child_iterator CXXNewExpr::child_end() { return &SubExprs[0] + Array + getNumPlacementArgs() + getNumConstructorArgs(); } // CXXDeleteExpr Stmt::child_iterator CXXDeleteExpr::child_begin() { return &Argument; } Stmt::child_iterator CXXDeleteExpr::child_end() { return &Argument+1; } // UnresolvedFunctionNameExpr Stmt::child_iterator UnresolvedFunctionNameExpr::child_begin() { return child_iterator(); } Stmt::child_iterator UnresolvedFunctionNameExpr::child_end() { return child_iterator(); } // UnaryTypeTraitExpr Stmt::child_iterator UnaryTypeTraitExpr::child_begin() { return child_iterator(); } Stmt::child_iterator UnaryTypeTraitExpr::child_end() { return child_iterator(); } // UnresolvedDeclRefExpr StmtIterator UnresolvedDeclRefExpr::child_begin() { return child_iterator(); } StmtIterator UnresolvedDeclRefExpr::child_end() { return child_iterator(); } bool UnaryTypeTraitExpr::EvaluateTrait() const { switch(UTT) { default: assert(false && "Unknown type trait or not implemented"); case UTT_IsPOD: return QueriedType->isPODType(); case UTT_IsClass: // Fallthrough case UTT_IsUnion: if (const RecordType *Record = QueriedType->getAsRecordType()) { bool Union = Record->getDecl()->isUnion(); return UTT == UTT_IsUnion ? Union : !Union; } return false; case UTT_IsEnum: return QueriedType->isEnumeralType(); case UTT_IsPolymorphic: if (const RecordType *Record = QueriedType->getAsRecordType()) { // Type traits are only parsed in C++, so we've got CXXRecords. return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic(); } return false; case UTT_IsAbstract: if (const RecordType *RT = QueriedType->getAsRecordType()) return cast<CXXRecordDecl>(RT->getDecl())->isAbstract(); return false; case UTT_HasTrivialConstructor: if (const RecordType *RT = QueriedType->getAsRecordType()) return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor(); return false; } } SourceRange CXXOperatorCallExpr::getSourceRange() const { OverloadedOperatorKind Kind = getOperator(); if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) { if (getNumArgs() == 1) // Prefix operator return SourceRange(getOperatorLoc(), getArg(0)->getSourceRange().getEnd()); else // Postfix operator return SourceRange(getArg(0)->getSourceRange().getEnd(), getOperatorLoc()); } else if (Kind == OO_Call) { return SourceRange(getArg(0)->getSourceRange().getBegin(), getRParenLoc()); } else if (Kind == OO_Subscript) { return SourceRange(getArg(0)->getSourceRange().getBegin(), getRParenLoc()); } else if (getNumArgs() == 1) { return SourceRange(getOperatorLoc(), getArg(0)->getSourceRange().getEnd()); } else if (getNumArgs() == 2) { return SourceRange(getArg(0)->getSourceRange().getBegin(), getArg(1)->getSourceRange().getEnd()); } else { return SourceRange(); } } Expr *CXXMemberCallExpr::getImplicitObjectArgument() { if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(getCallee()->IgnoreParens())) return MemExpr->getBase(); // FIXME: Will eventually need to cope with member pointers. return 0; } //===----------------------------------------------------------------------===// // Named casts //===----------------------------------------------------------------------===// /// getCastName - Get the name of the C++ cast being used, e.g., /// "static_cast", "dynamic_cast", "reinterpret_cast", or /// "const_cast". The returned pointer must not be freed. const char *CXXNamedCastExpr::getCastName() const { switch (getStmtClass()) { case CXXStaticCastExprClass: return "static_cast"; case CXXDynamicCastExprClass: return "dynamic_cast"; case CXXReinterpretCastExprClass: return "reinterpret_cast"; case CXXConstCastExprClass: return "const_cast"; default: return "<invalid cast>"; } } CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(CXXConstructorDecl *Cons, QualType writtenTy, SourceLocation tyBeginLoc, Expr **Args, unsigned NumArgs, SourceLocation rParenLoc) : Expr(CXXTemporaryObjectExprClass, writtenTy, writtenTy->isDependentType(), (writtenTy->isDependentType() || CallExpr::hasAnyValueDependentArguments(Args, NumArgs))), TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc), Constructor(Cons), Args(0), NumArgs(NumArgs) { if (NumArgs > 0) { this->Args = new Stmt*[NumArgs]; for (unsigned i = 0; i < NumArgs; ++i) this->Args[i] = Args[i]; } } CXXTemporaryObjectExpr::~CXXTemporaryObjectExpr() { delete [] Args; } <file_sep>/test/CodeGen/weak-global.c // RUN: clang-cc -emit-llvm < %s | grep common int i; <file_sep>/include/clang/Driver/Options.h //===--- Options.h - Option info & table ------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef CLANG_DRIVER_OPTIONS_H_ #define CLANG_DRIVER_OPTIONS_H_ namespace clang { namespace driver { namespace options { enum ID { OPT_INVALID = 0, // This is not an option ID. OPT_INPUT, // Reserved ID for input option. OPT_UNKNOWN, // Reserved ID for unknown option. #define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ HELPTEXT, METAVAR) OPT_##ID, #include "clang/Driver/Options.def" LastOption #undef OPTION }; } class Arg; class InputArgList; class Option; /// OptTable - Provide access to the Option info table. /// /// The OptTable class provides a layer of indirection which allows /// Option instance to be created lazily. In the common case, only a /// few options will be needed at runtime; the OptTable class /// maintains enough information to parse command lines without /// instantiating Options, while letting other parts of the driver /// still use Option instances where convient. class OptTable { /// The table of options which have been constructed, indexed by /// option::ID - 1. mutable Option **Options; /// The index of the first option which can be parsed (i.e., is /// not a special option like 'input' or 'unknown', and is not an /// option group). unsigned FirstSearchableOption; Option *constructOption(options::ID id) const; public: OptTable(); ~OptTable(); unsigned getNumOptions() const; const char *getOptionName(options::ID id) const; /// getOption - Get the given \arg id's Option instance, lazily /// creating it if necessary. const Option *getOption(options::ID id) const; /// getOptionKind - Get the kind of the given option. unsigned getOptionKind(options::ID id) const; /// getOptionHelpText - Get the help text to use to describe this /// option. const char *getOptionHelpText(options::ID id) const; /// getOptionMetaVar - Get the meta-variable name to use when /// describing this options values in the help text. const char *getOptionMetaVar(options::ID id) const; /// parseOneArg - Parse a single argument; returning the new /// argument and updating Index. /// /// \param [in] [out] Index - The current parsing position in the /// argument string list; on return this will be the index of the /// next argument string to parse. /// /// \return - The parsed argument, or 0 if the argument is missing /// values (in which case Index still points at the conceptual /// next argument string to parse). Arg *ParseOneArg(const InputArgList &Args, unsigned &Index) const; }; } } #endif <file_sep>/tools/ccc/Makefile ##===- tools/ccc/Makefile ----------------------------------*- Makefile -*-===## # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # ##===----------------------------------------------------------------------===## LEVEL = ../../../.. include $(LEVEL)/Makefile.common install-local:: $(PROJ_bindir)/ccc $(PROJ_bindir)/ccclib Extra := $(wildcard $(PROJ_SRC_ROOT)/tools/clang/tools/ccc/ccclib/*.py) $(PROJ_bindir)/ccclib : $(Extra) $(Echo) Installing ccclib. $(Verb) mkdir -p "$(PROJ_bindir)/ccclib" $(Verb) cp -p $? "$(PROJ_bindir)/ccclib" $(Verb) python -m compileall -d "$(PROJ_prefix)/bin/ccclib" "$(PROJ_bindir)/ccclib" $(Verb) touch "$(PROJ_bindir)/ccclib" $(PROJ_bindir)/ccc : ccc $(Echo) Installing $< shell script. $(Verb) cat $< > "$@" $(Verb) chmod 0755 "$@" <file_sep>/tools/ccc/ccclib/Jobs.py import Arguments import Util class Job(object): """Job - A set of commands to execute as a single task.""" def iterjobs(self): abstract class Command(Job): """Command - Represent the information needed to execute a single process. This currently assumes that the executable will always be the first argument.""" def __init__(self, executable, args): assert Util.all_true(args, lambda x: isinstance(x, str)) self.executable = executable self.args = args def __repr__(self): return Util.prefixAndPPrint(self.__class__.__name__, (self.executable, self.args)) def getArgv(self): return [self.executable] + self.args def iterjobs(self): yield self class PipedJob(Job): """PipedJob - A sequence of piped commands.""" def __init__(self, commands): assert Util.all_true(commands, lambda x: isinstance(x, Arguments.Command)) self.commands = list(commands) def addJob(self, job): assert isinstance(job, Command) self.commands.append(job) def __repr__(self): return Util.prefixAndPPrint(self.__class__.__name__, (self.commands,)) class JobList(Job): """JobList - A sequence of jobs to perform.""" def __init__(self, jobs=[]): self.jobs = list(jobs) def addJob(self, job): self.jobs.append(job) def __repr__(self): return Util.prefixAndPPrint(self.__class__.__name__, (self.jobs,)) def iterjobs(self): for j in self.jobs: yield j <file_sep>/test/Sema/vla.c // RUN: clang-cc %s -verify -fsyntax-only -pedantic int test1() { typedef int x[test1()]; // vla static int y = sizeof(x); // expected-error {{not a compile-time constant}} } // PR2347 void f (unsigned int m) { int e[2][m]; e[0][0] = 0; } // PR3048 int x = sizeof(struct{char qq[x];}); // expected-error {{fields must have a constant size}} // PR2352 void f2(unsigned int m) { extern int e1[2][m]; // expected-error {{variable length array declaration can not have 'extern' linkage}} e1[0][0] = 0; } // PR2361 int i; int c[][i]; // expected-error {{variably modified type declaration not allowed at file scope}} int d[i]; // expected-error {{variable length array declaration not allowed at file scope}} int (*e)[i]; // expected-error {{variably modified type declaration not allowed at file scope}} void f3() { static int a[i]; // expected-error {{variable length array declaration can not have 'static' storage duration}} extern int b[i]; // expected-error {{variable length array declaration can not have 'extern' linkage}} extern int (*c1)[i]; // expected-error {{variably modified type declaration can not have 'extern' linkage}} static int (*d)[i]; } // PR3663 static const unsigned array[((2 * (int)((((4) / 2) + 1.0/3.0) * (4) - 1e-8)) + 1)]; // expected-warning {{size of static array must be an integer constant expression}} <file_sep>/test/SemaCXX/condition.cpp // RUN: clang-cc -fsyntax-only -verify %s void test() { int x; if (x) ++x; if (int x=0) ++x; typedef int arr[10]; while (arr x=0) ; // expected-error {{an array type is not allowed here}} expected-error {{initialization with '{...}' expected for array}} while (int f()=0) ; // expected-error {{a function type is not allowed here}} struct S {} s; if (s) ++x; // expected-error {{value of type 'struct S' is not contextually convertible to 'bool'}} while (struct S x=s) ; // expected-error {{value of type 'struct S' is not contextually convertible to 'bool'}} do ; while (s); // expected-error {{value of type 'struct S' is not contextually convertible to 'bool'}} for (;s;) ; // expected-error {{value of type 'struct S' is not contextually convertible to 'bool'}} switch (s) {} // expected-error {{statement requires expression of integer type ('struct S' invalid)}} while (struct S {} x=0) ; // expected-error {{types may not be defined in conditions}} expected-error {{cannot initialize 'x' with an rvalue of type 'int'}} expected-error {{value of type 'struct S' is not contextually convertible to 'bool'}} while (struct {} x=0) ; // expected-error {{types may not be defined in conditions}} expected-error {{cannot initialize 'x' with an rvalue of type 'int'}} expected-error {{value of type 'struct <anonymous>' is not contextually convertible to 'bool'}} switch (enum {E} x=0) ; // expected-error {{types may not be defined in conditions}} expected-error {{incompatible type}} if (int x=0) { // expected-note 2 {{previous definition is here}} int x; // expected-error {{redefinition of 'x'}} } else int x; // expected-error {{redefinition of 'x'}} while (int x=0) int x; // expected-error {{redefinition of 'x'}} expected-note {{previous definition is here}} while (int x=0) { int x; } // expected-error {{redefinition of 'x'}} expected-note {{previous definition is here}} for (int x; int x=0; ) ; // expected-error {{redefinition of 'x'}} expected-note {{previous definition is here}} for (int x; ; ) int x; // expected-error {{redefinition of 'x'}} expected-note {{previous definition is here}} for (; int x=0; ) int x; // expected-error {{redefinition of 'x'}} expected-note {{previous definition is here}} for (; int x=0; ) { int x; } // expected-error {{redefinition of 'x'}} expected-note {{previous definition is here}} switch (int x=0) { default: int x; } // expected-error {{redefinition of 'x'}} expected-note {{previous definition is here}} } <file_sep>/test/Lexer/number.c // RUN: clang-cc %s -fsyntax-only float X = 1.17549435e-38F; float Y = 08.123456; // PR2252 #if -0x8000000000000000 // should not warn. #endif <file_sep>/tools/ccc/ccclib/Tools.py import os import sys # FIXME: Shouldn't be needed. import Arguments import Jobs import Phases import Types class Tool(object): """Tool - A concrete implementation of an action.""" eFlagsPipedInput = 1 << 0 eFlagsPipedOutput = 1 << 1 eFlagsIntegratedCPP = 1 << 2 def __init__(self, name, toolChain, flags = 0): self.name = name self.toolChain = toolChain self.flags = flags def acceptsPipedInput(self): return not not (self.flags & Tool.eFlagsPipedInput) def canPipeOutput(self): return not not (self.flags & Tool.eFlagsPipedOutput) def hasIntegratedCPP(self): return not not (self.flags & Tool.eFlagsIntegratedCPP) class GCC_Common_Tool(Tool): def getGCCExtraArgs(self): return [] def constructJob(self, phase, arch, jobs, inputs, output, outputType, arglist, linkingOutput): cmd_args = [] for arg in arglist.args: if arg.opt.forwardToGCC(): cmd_args.extend(arglist.render(arg)) cmd_args.extend(self.getGCCExtraArgs()) # If using a driver driver, force the arch. if self.toolChain.driver.hostInfo.useDriverDriver(): # FIXME: Remove this branch once ok. cmd_args.append('-arch') cmd_args.append(self.toolChain.archName) if isinstance(output, Jobs.PipedJob): cmd_args.extend(['-o', '-']) elif isinstance(phase.phase, Phases.SyntaxOnlyPhase): cmd_args.append('-fsyntax-only') else: assert output cmd_args.extend(arglist.render(output)) if (isinstance(self, GCC_LinkTool) and linkingOutput): cmd_args.append('-Wl,-arch_multiple') cmd_args.append('-Wl,-final_output,' + arglist.getValue(linkingOutput)) # Only pass -x if gcc will understand it; otherwise hope gcc # understands the suffix correctly. The main use case this # would go wrong in is for linker inputs if they happened to # have an odd suffix; really the only way to get this to # happen is a command like '-x foobar a.c' which will treat # a.c like a linker input. # # FIXME: For the linker case specifically, can we safely # convert inputs into '-Wl,' options? for input in inputs: if input.type.canBeUserSpecified: cmd_args.extend(['-x', input.type.name]) if isinstance(input.source, Jobs.PipedJob): cmd_args.append('-') else: assert isinstance(input.source, Arguments.Arg) # If this is a linker input then assume we can forward # just by rendering. if input.source.opt.isLinkerInput: cmd_args.extend(arglist.render(input.source)) else: cmd_args.extend(arglist.renderAsInput(input.source)) jobs.addJob(Jobs.Command('gcc', cmd_args)) class GCC_PreprocessTool(GCC_Common_Tool): def __init__(self, toolChain): super(GCC_PreprocessTool, self).__init__('gcc (cpp)', toolChain, (Tool.eFlagsPipedInput | Tool.eFlagsPipedOutput)) def getGCCExtraArgs(self): return ['-E'] class GCC_CompileTool(GCC_Common_Tool): def __init__(self, toolChain): super(GCC_CompileTool, self).__init__('gcc (cc1)', toolChain, (Tool.eFlagsPipedInput | Tool.eFlagsPipedOutput | Tool.eFlagsIntegratedCPP)) def getGCCExtraArgs(self): return ['-S'] class GCC_PrecompileTool(GCC_Common_Tool): def __init__(self, toolChain): super(GCC_PrecompileTool, self).__init__('gcc (pch)', toolChain, (Tool.eFlagsPipedInput | Tool.eFlagsIntegratedCPP)) def getGCCExtraArgs(self): return [] class GCC_AssembleTool(GCC_Common_Tool): def __init__(self, toolChain): # Assume that gcc will do any magic necessary to let the # assembler take piped input. super(GCC_AssembleTool, self).__init__('gcc (as)', toolChain, Tool.eFlagsPipedInput) def getGCCExtraArgs(self): return ['-c'] class GCC_LinkTool(GCC_Common_Tool): def __init__(self, toolChain): super(GCC_LinkTool, self).__init__('gcc (ld)', toolChain) class Darwin_AssembleTool(Tool): def __init__(self, toolChain): super(Darwin_AssembleTool, self).__init__('as', toolChain, Tool.eFlagsPipedInput) def constructJob(self, phase, arch, jobs, inputs, output, outputType, arglist, linkingOutput): assert len(inputs) == 1 assert outputType is Types.ObjectType input = inputs[0] cmd_args = [] # Bit of a hack, this is only used for original inputs. if input.isOriginalInput(): if arglist.getLastArg(arglist.parser.gGroup): cmd_args.append('--gstabs') # Derived from asm spec. cmd_args.append('-arch') cmd_args.append(self.toolChain.archName) cmd_args.append('-force_cpusubtype_ALL') if (arglist.getLastArg(arglist.parser.m_kernelOption) or arglist.getLastArg(arglist.parser.staticOption) or arglist.getLastArg(arglist.parser.f_appleKextOption)): if not arglist.getLastArg(arglist.parser.dynamicOption): cmd_args.append('-static') for arg in arglist.getArgs2(arglist.parser.WaOption, arglist.parser.XassemblerOption): cmd_args.extend(arglist.getValues(arg)) cmd_args.extend(arglist.render(output)) if isinstance(input.source, Jobs.PipedJob): pass else: cmd_args.extend(arglist.renderAsInput(input.source)) # asm_final spec is empty. jobs.addJob(Jobs.Command(self.toolChain.getProgramPath('as'), cmd_args)) class Clang_CompileTool(Tool): def __init__(self, toolChain): super(Clang_CompileTool, self).__init__('clang', toolChain, (Tool.eFlagsPipedInput | Tool.eFlagsPipedOutput | Tool.eFlagsIntegratedCPP)) def constructJob(self, phase, arch, jobs, inputs, output, outputType, arglist, linkingOutput): cmd_args = [] if isinstance(phase.phase, Phases.AnalyzePhase): assert outputType is Types.PlistType cmd_args.append('-analyze') elif isinstance(phase.phase, Phases.SyntaxOnlyPhase): assert outputType is Types.NothingType cmd_args.append('-fsyntax-only') elif outputType is Types.LLVMAsmType: cmd_args.append('-emit-llvm') elif outputType is Types.LLVMBCType: cmd_args.append('-emit-llvm-bc') elif outputType is Types.AsmTypeNoPP: # FIXME: This is hackish, it would be better if we had the # action instead of just looking at types. assert len(inputs) == 1 if inputs[0].type is Types.AsmType: cmd_args.append('-E') else: cmd_args.append('-S') elif (inputs[0].type.preprocess and outputType is inputs[0].type.preprocess): cmd_args.append('-E') elif outputType is Types.PCHType: # No special option needed, driven by -x. # # FIXME: Don't drive this by -x, that is gross. pass else: raise ValueError,"Unexpected output type for clang tool." # The make clang go fast button. cmd_args.append('-disable-free') if isinstance(phase.phase, Phases.AnalyzePhase): # Add default argument set. # # FIXME: Move into clang? cmd_args.extend(['-warn-dead-stores', '-checker-cfref', '-analyzer-eagerly-assume', '-warn-objc-methodsigs', # Do not enable the missing -dealloc check. # '-warn-objc-missing-dealloc', '-warn-objc-unused-ivars']) cmd_args.append('-analyzer-output=plist') # Add -Xanalyzer arguments when running as analyzer. for arg in arglist.getArgs(arglist.parser.XanalyzerOption): cmd_args.extend(arglist.getValues(arg)) else: # Perform argument translation for LLVM backend. This # takes some care in reconciling with llvm-gcc. The # issue is that llvm-gcc translates these options based on # the values in cc1, whereas we are processing based on # the driver arguments. # # FIXME: This is currently broken for -f flags when -fno # variants are present. # This comes from the default translation the driver + cc1 # would do to enable flag_pic. # # FIXME: Centralize this code. picEnabled = (arglist.getLastArg(arglist.parser.f_PICOption) or arglist.getLastArg(arglist.parser.f_picOption) or arglist.getLastArg(arglist.parser.f_PIEOption) or arglist.getLastArg(arglist.parser.f_pieOption)) picDisabled = (arglist.getLastArg(arglist.parser.m_kernelOption) or arglist.getLastArg(arglist.parser.staticOption)) model = self.toolChain.getForcedPicModel() if not model: if arglist.getLastArg(arglist.parser.m_dynamicNoPicOption): model = 'dynamic-no-pic' elif picDisabled: model = 'static' elif picEnabled: model = 'pic' else: model = self.toolChain.getDefaultRelocationModel() cmd_args.append('--relocation-model') cmd_args.append(model) if arglist.getLastArg(arglist.parser.f_timeReportOption): cmd_args.append('--time-passes') # FIXME: Set --enable-unsafe-fp-math. if not arglist.getLastArg(arglist.parser.f_omitFramePointerOption): cmd_args.append('--disable-fp-elim') if not arglist.hasFFlag(arglist.parser.f_zeroInitializedInBssOption, arglist.parser.f_noZeroInitializedInBssOption, True): cmd_args.append('--nozero-initialized-in-bss') if arglist.getLastArg(arglist.parser.dAOption): cmd_args.append('--asm-verbose') if arglist.getLastArg(arglist.parser.f_debugPassStructureOption): cmd_args.append('--debug-pass=Structure') if arglist.getLastArg(arglist.parser.f_debugPassArgumentsOption): cmd_args.append('--debug-pass=Arguments') # FIXME: set --inline-threshhold=50 if (optimize_size || optimize < 3) cmd_args.append('--unwind-tables=%d' % arglist.hasFFlag(arglist.parser.f_unwindTablesOption, arglist.parser.f_noUnwindTablesOption, self.toolChain.isUnwindTablesDefault())) if not arglist.hasFFlag(arglist.parser.m_redZoneOption, arglist.parser.m_noRedZoneOption, True): cmd_args.append('--disable-red-zone') if arglist.hasFFlag(arglist.parser.m_softFloatOption, arglist.parser.m_noSoftFloatOption, False): cmd_args.append('--soft-float') # FIXME: Need target hooks. if self.toolChain.driver.getHostSystemName() == 'darwin': if self.toolChain.archName == 'x86_64': cmd_args.append('--mcpu=core2') elif self.toolChain.archName == 'i386': cmd_args.append('--mcpu=yonah') else: pass # FIXME: Ignores ordering attrs = [] for pos,neg,flag in [(arglist.parser.m_mmxOption, arglist.parser.m_noMmxOption, 'mmx'), (arglist.parser.m_sseOption, arglist.parser.m_noSseOption, 'sse'), (arglist.parser.m_sse2Option, arglist.parser.m_noSse2Option, 'sse2'), (arglist.parser.m_sse3Option, arglist.parser.m_noSse3Option, 'sse3'), (arglist.parser.m_ssse3Option, arglist.parser.m_noSsse3Option, 'ssse3'), (arglist.parser.m_sse41Option, arglist.parser.m_noSse41Option, 'sse41'), (arglist.parser.m_sse42Option, arglist.parser.m_noSse42Option, 'sse42'), (arglist.parser.m_sse4aOption, arglist.parser.m_noSse4aOption, 'sse4a'), (arglist.parser.m_3dnowOption, arglist.parser.m_no3dnowOption, '3dnow'), (arglist.parser.m_3dnowaOption, arglist.parser.m_no3dnowaOption, '3dnowa'), ]: if arglist.getLastArg(pos): attrs.append('+' + flag) elif arglist.getLastArg(neg): attrs.append('-' + flag) if attrs: cmd_args.append('--mattr=%s' % ','.join(attrs)) if arglist.hasFFlag(arglist.parser.f_mathErrnoOption, arglist.parser.f_noMathErrnoOption, self.toolChain.isMathErrnoDefault()): cmd_args.append('--fmath-errno=1') else: cmd_args.append('--fmath-errno=0') arg = arglist.getLastArg(arglist.parser.f_limitedPrecisionOption) if arg: cmd_args.append('--limit-float-precision') cmd_args.append(arglist.getValue(arg)) # FIXME: Add --stack-protector-buffer-size=<xxx> on -fstack-protect. arglist.addLastArg(cmd_args, arglist.parser.MDOption) arglist.addLastArg(cmd_args, arglist.parser.MMDOption) arglist.addAllArgs(cmd_args, arglist.parser.MFOption) arglist.addLastArg(cmd_args, arglist.parser.MPOption) arglist.addAllArgs(cmd_args, arglist.parser.MTOption) unsupported = (arglist.getLastArg(arglist.parser.MOption) or arglist.getLastArg(arglist.parser.MMOption) or arglist.getLastArg(arglist.parser.MGOption) or arglist.getLastArg(arglist.parser.MQOption)) if unsupported: raise NotImplementedError('clang support for "%s"' % unsupported.opt.name) arglist.addAllArgs(cmd_args, arglist.parser.vOption) arglist.addAllArgs2(cmd_args, arglist.parser.DOption, arglist.parser.UOption) arglist.addAllArgs2(cmd_args, arglist.parser.IGroup, arglist.parser.FOption) arglist.addLastArg(cmd_args, arglist.parser.POption) arglist.addAllArgs(cmd_args, arglist.parser.m_macosxVersionMinOption) # Special case debug options to only pass -g to clang. This is # wrong. if arglist.getLastArg(arglist.parser.gGroup): cmd_args.append('-g') arglist.addLastArg(cmd_args, arglist.parser.nostdincOption) # FIXME: Clang isn't going to accept just anything here. # Add i* options and automatically translate to -include-pth # for transparent PCH support. It's wonky, but we include # looking for .gch so we can support seamless replacement into # a build system already set up to be generating .gch files. for arg in arglist.getArgs(arglist.parser.iGroup): if arg.opt.matches(arglist.parser.includeOption): for suffix in ('.pth','.gch'): pthPath = arglist.getValue(arg) + suffix if os.path.exists(pthPath): cmd_args.append('-include-pth') cmd_args.append(pthPath) break else: cmd_args.extend(arglist.render(arg)) else: cmd_args.extend(arglist.render(arg)) # Manually translate -O to -O1; let clang reject others. arg = arglist.getLastArg(arglist.parser.OOption) if arg: if arglist.getValue(arg) == '': cmd_args.append('-O1') else: cmd_args.extend(arglist.render(arg)) arglist.addAllArgs2(cmd_args, arglist.parser.ClangWGroup, arglist.parser.pedanticGroup) arglist.addLastArg(cmd_args, arglist.parser.wOption) arglist.addAllArgs3(cmd_args, arglist.parser.stdOption, arglist.parser.ansiOption, arglist.parser.trigraphsOption) arg = arglist.getLastArg(arglist.parser.f_templateDepthOption) if arg: cmd_args.append('-ftemplate-depth') cmd_args.append(arglist.getValue(arg)) arglist.addAllArgs(cmd_args, arglist.parser.Clang_fGroup) arglist.addLastArg(cmd_args, arglist.parser.dMOption) for arg in arglist.getArgs(arglist.parser.XclangOption): cmd_args.extend(arglist.getValues(arg)) # FIXME: We should always pass this once it is always known. if self.toolChain.archName: cmd_args.append('-arch') cmd_args.append(self.toolChain.archName) if isinstance(output, Jobs.PipedJob): cmd_args.extend(['-o', '-']) elif output: cmd_args.extend(arglist.render(output)) for input in inputs: cmd_args.append('-x') cmd_args.append(input.type.name) if isinstance(input.source, Jobs.PipedJob): cmd_args.append('-') else: cmd_args.extend(arglist.renderAsInput(input.source)) jobs.addJob(Jobs.Command(self.toolChain.getProgramPath('clang-cc'), cmd_args)) class Darwin_X86_CC1Tool(Tool): def getCC1Name(self, type): """getCC1Name(type) -> name, use-cpp, is-cxx""" # FIXME: Get bool results from elsewhere. if type is Types.AsmType: return 'cc1',True,False elif type is Types.CType or type is Types.CHeaderType: return 'cc1',True,False elif type is Types.CTypeNoPP or type is Types.CHeaderNoPPType: return 'cc1',False,False elif type is Types.ObjCType or type is Types.ObjCHeaderType: return 'cc1obj',True,False elif type is Types.ObjCTypeNoPP or type is Types.ObjCHeaderNoPPType: return 'cc1obj',True,False elif type is Types.CXXType or type is Types.CXXHeaderType: return 'cc1plus',True,True elif type is Types.CXXTypeNoPP or type is Types.CXXHeaderNoPPType: return 'cc1plus',False,True elif type is Types.ObjCXXType or type is Types.ObjCXXHeaderType: return 'cc1objplus',True,True elif type is Types.ObjCXXTypeNoPP or type is Types.ObjCXXHeaderNoPPType: return 'cc1objplus',False,True else: raise ValueError,"Unexpected type for Darwin compile tool." def addCC1Args(self, cmd_args, arch, arglist): # Derived from cc1 spec. # FIXME: -fapple-kext seems to disable this too. Investigate. if (not arglist.getLastArg(arglist.parser.m_kernelOption) and not arglist.getLastArg(arglist.parser.staticOption) and not arglist.getLastArg(arglist.parser.m_dynamicNoPicOption)): cmd_args.append('-fPIC') # FIXME: Remove mthumb # FIXME: Remove mno-thumb # FIXME: As with ld, something else is going on. My best guess # is gcc is faking an -mmacosx-version-min # somewhere. Investigate. # if (not arglist.getLastArg(arglist.parser.m_macosxVersionMinOption) and # not arglist.getLastArg(arglist.parser.m_iphoneosVersionMinOption)): # cmd_args.append('-mmacosx-version-min=' + # self.toolChain.getMacosxVersionMin()) # FIXME: Remove faltivec # FIXME: Remove mno-fused-madd # FIXME: Remove mlong-branch # FIXME: Remove mlongcall # FIXME: Remove mcpu=G4 # FIXME: Remove mcpu=G5 if (arglist.getLastArg(arglist.parser.gOption) and not arglist.getLastArg(arglist.parser.f_noEliminateUnusedDebugSymbolsOption)): cmd_args.append('-feliminate-unused-debug-symbols') def addCC1OptionsArgs(self, cmd_args, arch, arglist, inputs, output_args, isCXX): # Derived from cc1_options spec. if (arglist.getLastArg(arglist.parser.fastOption) or arglist.getLastArg(arglist.parser.fastfOption) or arglist.getLastArg(arglist.parser.fastcpOption)): cmd_args.append('-O3') if (arglist.getLastArg(arglist.parser.pgOption) and arglist.getLastArg(arglist.parser.f_omitFramePointerOption)): raise Arguments.InvalidArgumentsError("-pg and -fomit-frame-pointer are incompatible") self.addCC1Args(cmd_args, arch, arglist) if not arglist.getLastArg(arglist.parser.QOption): cmd_args.append('-quiet') cmd_args.append('-dumpbase') cmd_args.append(self.getBaseInputName(inputs, arglist)) arglist.addAllArgs(cmd_args, arglist.parser.dGroup) arglist.addAllArgs(cmd_args, arglist.parser.mGroup) arglist.addAllArgs(cmd_args, arglist.parser.aGroup) # FIXME: The goal is to use the user provided -o if that is # our final output, otherwise to drive from the original input # name. Find a clean way to go about this. if (arglist.getLastArg(arglist.parser.cOption) or arglist.getLastArg(arglist.parser.SOption)): outputOpt = arglist.getLastArg(arglist.parser.oOption) if outputOpt: cmd_args.append('-auxbase-strip') cmd_args.append(arglist.getValue(outputOpt)) else: cmd_args.append('-auxbase') cmd_args.append(self.getBaseInputStem(inputs, arglist)) else: cmd_args.append('-auxbase') cmd_args.append(self.getBaseInputStem(inputs, arglist)) arglist.addAllArgs(cmd_args, arglist.parser.gGroup) arglist.addAllArgs(cmd_args, arglist.parser.OOption) # FIXME: -Wall is getting some special treatment. Investigate. arglist.addAllArgs2(cmd_args, arglist.parser.WGroup, arglist.parser.pedanticGroup) arglist.addLastArg(cmd_args, arglist.parser.wOption) arglist.addAllArgs3(cmd_args, arglist.parser.stdOption, arglist.parser.ansiOption, arglist.parser.trigraphsOption) if arglist.getLastArg(arglist.parser.vOption): cmd_args.append('-version') if arglist.getLastArg(arglist.parser.pgOption): cmd_args.append('-p') arglist.addLastArg(cmd_args, arglist.parser.pOption) # ccc treats -fsyntax-only specially. arglist.addAllArgs2(cmd_args, arglist.parser.fGroup, arglist.parser.syntaxOnlyOption) arglist.addAllArgs(cmd_args, arglist.parser.undefOption) if arglist.getLastArg(arglist.parser.QnOption): cmd_args.append('-fno-ident') # FIXME: This isn't correct. #arglist.addLastArg(cmd_args, arglist.parser._helpOption) #arglist.addLastArg(cmd_args, arglist.parser._targetHelpOption) if output_args: cmd_args.extend(output_args) # FIXME: Still don't get what is happening here. Investigate. arglist.addAllArgs(cmd_args, arglist.parser._paramOption) if (arglist.getLastArg(arglist.parser.f_mudflapOption) or arglist.getLastArg(arglist.parser.f_mudflapthOption)): cmd_args.append('-fno-builtin') cmd_args.append('-fno-merge-constants') if arglist.getLastArg(arglist.parser.coverageOption): cmd_args.append('-fprofile-arcs') cmd_args.append('-ftest-coverage') if isCXX: cmd_args.append('-D__private_extern__=extern') def getBaseInputName(self, inputs, arglist): # FIXME: gcc uses a temporary name here when the base # input is stdin, but only in auxbase. Investigate. baseInputValue = arglist.getValue(inputs[0].baseInput) return os.path.basename(baseInputValue) def getBaseInputStem(self, inputs, arglist): return os.path.splitext(self.getBaseInputName(inputs, arglist))[0] def getOutputArgs(self, arglist, output, isCPP=False): if isinstance(output, Jobs.PipedJob): if isCPP: return [] else: return ['-o', '-'] elif output is None: return ['-o', '/dev/null'] else: return arglist.render(output) def addCPPOptionsArgs(self, cmd_args, arch, arglist, inputs, output_args, isCXX): # Derived from cpp_options. self.addCPPUniqueOptionsArgs(cmd_args, arch, arglist, inputs) cmd_args.extend(output_args) self.addCC1Args(cmd_args, arch, arglist) # NOTE: The code below has some commonality with cpp_options, # but in classic gcc style ends up sending things in different # orders. This may be a good merge candidate once we drop # pedantic compatibility. arglist.addAllArgs(cmd_args, arglist.parser.mGroup) arglist.addAllArgs3(cmd_args, arglist.parser.stdOption, arglist.parser.ansiOption, arglist.parser.trigraphsOption) arglist.addAllArgs2(cmd_args, arglist.parser.WGroup, arglist.parser.pedanticGroup) arglist.addLastArg(cmd_args, arglist.parser.wOption) # ccc treats -fsyntax-only specially. arglist.addAllArgs2(cmd_args, arglist.parser.fGroup, arglist.parser.syntaxOnlyOption) if (arglist.getLastArg(arglist.parser.gGroup) and not arglist.getLastArg(arglist.parser.g0Option) and not arglist.getLastArg(arglist.parser.f_noWorkingDirectoryOption)): cmd_args.append('-fworking-directory') arglist.addAllArgs(cmd_args, arglist.parser.OOption) arglist.addAllArgs(cmd_args, arglist.parser.undefOption) if arglist.getLastArg(arglist.parser.saveTempsOption): cmd_args.append('-fpch-preprocess') def addCPPUniqueOptionsArgs(self, cmd_args, arch, arglist, inputs): # Derived from cpp_unique_options. if (arglist.getLastArg(arglist.parser.COption) or arglist.getLastArg(arglist.parser.CCOption)): if not arglist.getLastArg(arglist.parser.EOption): raise Arguments.InvalidArgumentsError("-C or -CC is not supported without -E") if not arglist.getLastArg(arglist.parser.QOption): cmd_args.append('-quiet') arglist.addAllArgs(cmd_args, arglist.parser.nostdincOption) arglist.addLastArg(cmd_args, arglist.parser.vOption) arglist.addAllArgs2(cmd_args, arglist.parser.IGroup, arglist.parser.FOption) arglist.addLastArg(cmd_args, arglist.parser.POption) # FIXME: Handle %I properly. if self.toolChain.archName == 'x86_64': cmd_args.append('-imultilib') cmd_args.append('x86_64') if arglist.getLastArg(arglist.parser.MDOption): cmd_args.append('-MD') # FIXME: Think about this more. outputOpt = arglist.getLastArg(arglist.parser.oOption) if outputOpt: base,ext = os.path.splitext(arglist.getValue(outputOpt)) cmd_args.append(base+'.d') else: cmd_args.append(self.getBaseInputStem(inputs, arglist)+'.d') if arglist.getLastArg(arglist.parser.MMDOption): cmd_args.append('-MMD') # FIXME: Think about this more. outputOpt = arglist.getLastArg(arglist.parser.oOption) if outputOpt: base,ext = os.path.splitext(arglist.getValue(outputOpt)) cmd_args.append(base+'.d') else: cmd_args.append(self.getBaseInputStem(inputs, arglist)+'.d') arglist.addLastArg(cmd_args, arglist.parser.MOption) arglist.addLastArg(cmd_args, arglist.parser.MMOption) arglist.addAllArgs(cmd_args, arglist.parser.MFOption) arglist.addLastArg(cmd_args, arglist.parser.MGOption) arglist.addLastArg(cmd_args, arglist.parser.MPOption) arglist.addAllArgs(cmd_args, arglist.parser.MQOption) arglist.addAllArgs(cmd_args, arglist.parser.MTOption) if (not arglist.getLastArg(arglist.parser.MOption) and not arglist.getLastArg(arglist.parser.MMOption) and (arglist.getLastArg(arglist.parser.MDOption) or arglist.getLastArg(arglist.parser.MMDOption))): outputOpt = arglist.getLastArg(arglist.parser.oOption) if outputOpt: cmd_args.append('-MQ') cmd_args.append(arglist.getValue(outputOpt)) arglist.addLastArg(cmd_args, arglist.parser.remapOption) if arglist.getLastArg(arglist.parser.g3Option): cmd_args.append('-dD') arglist.addLastArg(cmd_args, arglist.parser.HOption) self.addCPPArgs(cmd_args, arch, arglist) arglist.addAllArgs3(cmd_args, arglist.parser.DOption, arglist.parser.UOption, arglist.parser.AOption) arglist.addAllArgs(cmd_args, arglist.parser.iGroup) for input in inputs: if isinstance(input.source, Jobs.PipedJob): cmd_args.append('-') else: cmd_args.extend(arglist.renderAsInput(input.source)) for arg in arglist.getArgs2(arglist.parser.WpOption, arglist.parser.XpreprocessorOption): cmd_args.extend(arglist.getValues(arg)) if arglist.getLastArg(arglist.parser.f_mudflapOption): cmd_args.append('-D_MUDFLAP') cmd_args.append('-include') cmd_args.append('mf-runtime.h') if arglist.getLastArg(arglist.parser.f_mudflapthOption): cmd_args.append('-D_MUDFLAP') cmd_args.append('-D_MUDFLAPTH') cmd_args.append('-include') cmd_args.append('mf-runtime.h') def addCPPArgs(self, cmd_args, arch, arglist): # Derived from cpp spec. if arglist.getLastArg(arglist.parser.staticOption): # The gcc spec is broken here, it refers to dynamic but # that has been translated. Start by being bug compatible. # if not arglist.getLastArg(arglist.parser.dynamicOption): cmd_args.append('-D__STATIC__') else: cmd_args.append('-D__DYNAMIC__') if arglist.getLastArg(arglist.parser.pthreadOption): cmd_args.append('-D_REENTRANT') class Darwin_X86_PreprocessTool(Darwin_X86_CC1Tool): def __init__(self, toolChain): super(Darwin_X86_PreprocessTool, self).__init__('cpp', toolChain, (Tool.eFlagsPipedInput | Tool.eFlagsPipedOutput)) def constructJob(self, phase, arch, jobs, inputs, output, outputType, arglist, linkingOutput): inputType = inputs[0].type assert not [i for i in inputs if i.type != inputType] cc1Name,usePP,isCXX = self.getCC1Name(inputType) cmd_args = ['-E'] if (arglist.getLastArg(arglist.parser.traditionalOption) or arglist.getLastArg(arglist.parser.f_traditionalOption) or arglist.getLastArg(arglist.parser.traditionalCPPOption)): cmd_args.append('-traditional-cpp') output_args = self.getOutputArgs(arglist, output, isCPP=True) self.addCPPOptionsArgs(cmd_args, arch, arglist, inputs, output_args, isCXX) arglist.addAllArgs(cmd_args, arglist.parser.dGroup) jobs.addJob(Jobs.Command(self.toolChain.getProgramPath(cc1Name), cmd_args)) class Darwin_X86_CompileTool(Darwin_X86_CC1Tool): def __init__(self, toolChain): super(Darwin_X86_CompileTool, self).__init__('cc1', toolChain, (Tool.eFlagsPipedInput | Tool.eFlagsPipedOutput | Tool.eFlagsIntegratedCPP)) def constructJob(self, phase, arch, jobs, inputs, output, outputType, arglist, linkingOutput): inputType = inputs[0].type assert not [i for i in inputs if i.type != inputType] cc1Name,usePP,isCXX = self.getCC1Name(inputType) cmd_args = [] if (arglist.getLastArg(arglist.parser.traditionalOption) or arglist.getLastArg(arglist.parser.f_traditionalOption)): raise Arguments.InvalidArgumentsError("-traditional is not supported without -E") if outputType is Types.PCHType: pass elif outputType is Types.AsmTypeNoPP: pass elif outputType is Types.LLVMAsmType: cmd_args.append('-emit-llvm') elif outputType is Types.LLVMBCType: cmd_args.append('-emit-llvm-bc') if outputType is Types.PCHType: output_args = [] else: output_args = self.getOutputArgs(arglist, output) # There is no need for this level of compatibility, but it # makes diffing easier. if (not arglist.getLastArg(arglist.parser.syntaxOnlyOption) and not arglist.getLastArg(arglist.parser.SOption)): early_output_args, end_output_args = [], output_args else: early_output_args, end_output_args = output_args, [] if usePP: self.addCPPUniqueOptionsArgs(cmd_args, arch, arglist, inputs) self.addCC1OptionsArgs(cmd_args, arch, arglist, inputs, early_output_args, isCXX) cmd_args.extend(end_output_args) else: cmd_args.append('-fpreprocessed') # FIXME: There is a spec command to remove # -fpredictive-compilation args here. Investigate. for input in inputs: if isinstance(input.source, Jobs.PipedJob): cmd_args.append('-') else: cmd_args.extend(arglist.renderAsInput(input.source)) self.addCC1OptionsArgs(cmd_args, arch, arglist, inputs, early_output_args, isCXX) cmd_args.extend(end_output_args) if outputType is Types.PCHType: assert output is not None and not isinstance(output, Jobs.PipedJob) cmd_args.append('-o') # NOTE: gcc uses a temp .s file for this, but there # doesn't seem to be a good reason. cmd_args.append('/dev/null') cmd_args.append('--output-pch=') cmd_args.append(arglist.getValue(output)) jobs.addJob(Jobs.Command(self.toolChain.getProgramPath(cc1Name), cmd_args)) class Darwin_X86_LinkTool(Tool): def __init__(self, toolChain): super(Darwin_X86_LinkTool, self).__init__('collect2', toolChain) def getMacosxVersionTuple(self, arglist): arg = arglist.getLastArg(arglist.parser.m_macosxVersionMinOption) if arg: version = arglist.getValue(arg) components = version.split('.') try: return tuple(map(int, components)) except: raise Arguments.InvalidArgumentsError("invalid version number %r" % version) else: major,minor,minorminor = self.toolChain.darwinVersion return (10, major-4, minor) def addDarwinArch(self, cmd_args, arch, arglist): # Derived from darwin_arch spec. cmd_args.append('-arch') cmd_args.append(self.toolChain.archName) def addDarwinSubArch(self, cmd_args, arch, arglist): # Derived from darwin_subarch spec, not sure what the # distinction exists for but at least for this chain it is the same. return self.addDarwinArch(cmd_args, arch, arglist) def addLinkArgs(self, cmd_args, arch, arglist): # Derived from link spec. arglist.addAllArgs(cmd_args, arglist.parser.staticOption) if not arglist.getLastArg(arglist.parser.staticOption): cmd_args.append('-dynamic') if arglist.getLastArg(arglist.parser.f_gnuRuntimeOption): # FIXME: Replace -lobjc in forward args with # -lobjc-gnu. How do we wish to handle such things? pass if not arglist.getLastArg(arglist.parser.dynamiclibOption): if arglist.getLastArg(arglist.parser.force_cpusubtype_ALLOption): self.addDarwinArch(cmd_args, arch, arglist) cmd_args.append('-force_cpusubtype_ALL') else: self.addDarwinSubArch(cmd_args, arch, arglist) if arglist.getLastArg(arglist.parser.bundleOption): cmd_args.append('-bundle') arglist.addAllArgsTranslated(cmd_args, arglist.parser.bundle_loaderOption, '-bundle_loader') arglist.addAllArgs(cmd_args, arglist.parser.client_nameOption) if arglist.getLastArg(arglist.parser.compatibility_versionOption): # FIXME: Where should diagnostics go? print >>sys.stderr, "-compatibility_version only allowed with -dynamiclib" sys.exit(1) if arglist.getLastArg(arglist.parser.current_versionOption): print >>sys.stderr, "-current_version only allowed with -dynamiclib" sys.exit(1) if arglist.getLastArg(arglist.parser.force_flat_namespaceOption): cmd_args.append('-force_flat_namespace') if arglist.getLastArg(arglist.parser.install_nameOption): print >>sys.stderr, "-install_name only allowed with -dynamiclib" sys.exit(1) arglist.addLastArg(cmd_args, arglist.parser.keep_private_externsOption) arglist.addLastArg(cmd_args, arglist.parser.private_bundleOption) else: cmd_args.append('-dylib') if arglist.getLastArg(arglist.parser.bundleOption): print >>sys.stderr, "-bundle not allowed with -dynamiclib" sys.exit(1) if arglist.getLastArg(arglist.parser.bundle_loaderOption): print >>sys.stderr, "-bundle_loader not allowed with -dynamiclib" sys.exit(1) if arglist.getLastArg(arglist.parser.client_nameOption): print >>sys.stderr, "-client_name not allowed with -dynamiclib" sys.exit(1) arglist.addAllArgsTranslated(cmd_args, arglist.parser.compatibility_versionOption, '-dylib_compatibility_version') arglist.addAllArgsTranslated(cmd_args, arglist.parser.current_versionOption, '-dylib_current_version') if arglist.getLastArg(arglist.parser.force_cpusubtype_ALLOption): self.addDarwinArch(cmd_args, arch, arglist) # NOTE: We don't add -force_cpusubtype_ALL on this path. Ok. else: self.addDarwinSubArch(cmd_args, arch, arglist) if arglist.getLastArg(arglist.parser.force_flat_namespaceOption): print >>sys.stderr, "-force_flat_namespace not allowed with -dynamiclib" sys.exit(1) arglist.addAllArgsTranslated(cmd_args, arglist.parser.install_nameOption, '-dylib_install_name') if arglist.getLastArg(arglist.parser.keep_private_externsOption): print >>sys.stderr, "-keep_private_externs not allowed with -dynamiclib" sys.exit(1) if arglist.getLastArg(arglist.parser.private_bundleOption): print >>sys.stderr, "-private_bundle not allowed with -dynamiclib" sys.exit(1) if arglist.getLastArg(arglist.parser.all_loadOption): cmd_args.append('-all_load') arglist.addAllArgsTranslated(cmd_args, arglist.parser.allowable_clientOption, '-allowable_client') if arglist.getLastArg(arglist.parser.bind_at_loadOption): cmd_args.append('-bind_at_load') if arglist.getLastArg(arglist.parser.dead_stripOption): cmd_args.append('-dead_strip') if arglist.getLastArg(arglist.parser.no_dead_strip_inits_and_termsOption): cmd_args.append('-no_dead_strip_inits_and_terms') arglist.addAllArgsTranslated(cmd_args, arglist.parser.dylib_fileOption, '-dylib_file') if arglist.getLastArg(arglist.parser.dynamicOption): cmd_args.append('-dynamic') arglist.addAllArgsTranslated(cmd_args, arglist.parser.exported_symbols_listOption, '-exported_symbols_list') if arglist.getLastArg(arglist.parser.flat_namespaceOption): cmd_args.append('-flat_namespace') arglist.addAllArgs(cmd_args, arglist.parser.headerpad_max_install_namesOption) arglist.addAllArgsTranslated(cmd_args, arglist.parser.image_baseOption, '-image_base') arglist.addAllArgsTranslated(cmd_args, arglist.parser.initOption, '-init') if not arglist.getLastArg(arglist.parser.m_macosxVersionMinOption): if not arglist.getLastArg(arglist.parser.m_iphoneosVersionMinOption): # FIXME: I don't understand what is going on # here. This is supposed to come from # darwin_ld_minversion, but gcc doesn't seem to be # following that; it must be getting over-ridden # somewhere. cmd_args.append('-macosx_version_min') cmd_args.append(self.toolChain.getMacosxVersionMin()) else: # addAll doesn't make sense here but this is what gcc # does. arglist.addAllArgsTranslated(cmd_args, arglist.parser.m_macosxVersionMinOption, '-macosx_version_min') arglist.addAllArgsTranslated(cmd_args, arglist.parser.m_iphoneosVersionMinOption, '-iphoneos_version_min') arglist.addLastArg(cmd_args, arglist.parser.nomultidefsOption) if arglist.getLastArg(arglist.parser.multi_moduleOption): cmd_args.append('-multi_module') if arglist.getLastArg(arglist.parser.single_moduleOption): cmd_args.append('-single_module') arglist.addAllArgsTranslated(cmd_args, arglist.parser.multiply_definedOption, '-multiply_defined') arglist.addAllArgsTranslated(cmd_args, arglist.parser.multiply_defined_unusedOption, '-multiply_defined_unused') if arglist.getLastArg(arglist.parser.f_pieOption): cmd_args.append('-pie') arglist.addLastArg(cmd_args, arglist.parser.prebindOption) arglist.addLastArg(cmd_args, arglist.parser.noprebindOption) arglist.addLastArg(cmd_args, arglist.parser.nofixprebindingOption) arglist.addLastArg(cmd_args, arglist.parser.prebind_all_twolevel_modulesOption) arglist.addLastArg(cmd_args, arglist.parser.read_only_relocsOption) arglist.addAllArgs(cmd_args, arglist.parser.sectcreateOption) arglist.addAllArgs(cmd_args, arglist.parser.sectorderOption) arglist.addAllArgs(cmd_args, arglist.parser.seg1addrOption) arglist.addAllArgs(cmd_args, arglist.parser.segprotOption) arglist.addAllArgsTranslated(cmd_args, arglist.parser.segaddrOption, '-segaddr') arglist.addAllArgsTranslated(cmd_args, arglist.parser.segs_read_only_addrOption, '-segs_read_only_addr') arglist.addAllArgsTranslated(cmd_args, arglist.parser.segs_read_write_addrOption, '-segs_read_write_addr') arglist.addAllArgsTranslated(cmd_args, arglist.parser.seg_addr_tableOption, '-seg_addr_table') arglist.addAllArgsTranslated(cmd_args, arglist.parser.seg_addr_table_filenameOption, '-seg_addr_table_filename') arglist.addAllArgs(cmd_args, arglist.parser.sub_libraryOption) arglist.addAllArgs(cmd_args, arglist.parser.sub_umbrellaOption) arglist.addAllArgsTranslated(cmd_args, arglist.parser.isysrootOption, '-syslibroot') arglist.addLastArg(cmd_args, arglist.parser.twolevel_namespaceOption) arglist.addLastArg(cmd_args, arglist.parser.twolevel_namespace_hintsOption) arglist.addAllArgsTranslated(cmd_args, arglist.parser.umbrellaOption, '-umbrella') arglist.addAllArgs(cmd_args, arglist.parser.undefinedOption) arglist.addAllArgsTranslated(cmd_args, arglist.parser.unexported_symbols_listOption, '-unexported_symbols_list') arglist.addAllArgsTranslated(cmd_args, arglist.parser.weak_reference_mismatchesOption, '-weak_reference_mismatches') if not arglist.getLastArg(arglist.parser.weak_reference_mismatchesOption): cmd_args.append('-weak_reference_mismatches') cmd_args.append('non-weak') arglist.addLastArg(cmd_args, arglist.parser.XOption) arglist.addAllArgs(cmd_args, arglist.parser.yOption) arglist.addLastArg(cmd_args, arglist.parser.wOption) arglist.addAllArgs(cmd_args, arglist.parser.pagezero_sizeOption) arglist.addAllArgs(cmd_args, arglist.parser.segs_read_Option) arglist.addLastArg(cmd_args, arglist.parser.seglinkeditOption) arglist.addLastArg(cmd_args, arglist.parser.noseglinkeditOption) arglist.addAllArgs(cmd_args, arglist.parser.sectalignOption) arglist.addAllArgs(cmd_args, arglist.parser.sectobjectsymbolsOption) arglist.addAllArgs(cmd_args, arglist.parser.segcreateOption) arglist.addLastArg(cmd_args, arglist.parser.whyloadOption) arglist.addLastArg(cmd_args, arglist.parser.whatsloadedOption) arglist.addAllArgs(cmd_args, arglist.parser.dylinker_install_nameOption) arglist.addLastArg(cmd_args, arglist.parser.dylinkerOption) arglist.addLastArg(cmd_args, arglist.parser.MachOption) def constructJob(self, phase, arch, jobs, inputs, output, outputType, arglist, linkingOutput): assert outputType is Types.ImageType # The logic here is derived from gcc's behavior; most of which # comes from specs (starting with link_command). Consult gcc # for more information. # FIXME: gcc's spec controls when this is done; certain things # like -filelist or -Wl, still trigger a link stage. I don't # quite understand how gcc decides to execute the linker, # investigate. Also, the spec references -fdump= which seems # to have disappeared? cmd_args = [] # Not sure why this particular decomposition exists in gcc. self.addLinkArgs(cmd_args, arch, arglist) # This toolchain never accumlates options in specs, the only # place this gets used is to add -ObjC. if (arglist.getLastArg(arglist.parser.ObjCOption) or arglist.getLastArg(arglist.parser.f_objcOption)): cmd_args.append('-ObjC') if arglist.getLastArg(arglist.parser.ObjCXXOption): cmd_args.append('-ObjC') # FIXME: gcc has %{x} in here. How could this ever happen? # Cruft? arglist.addAllArgs(cmd_args, arglist.parser.dOption) arglist.addAllArgs(cmd_args, arglist.parser.sOption) arglist.addAllArgs(cmd_args, arglist.parser.tOption) arglist.addAllArgs(cmd_args, arglist.parser.ZOption) arglist.addAllArgs(cmd_args, arglist.parser.uGroup) arglist.addAllArgs(cmd_args, arglist.parser.AOption) arglist.addLastArg(cmd_args, arglist.parser.eOption) arglist.addAllArgs(cmd_args, arglist.parser.mSeparate) arglist.addAllArgs(cmd_args, arglist.parser.rOption) cmd_args.extend(arglist.render(output)) macosxVersion = self.getMacosxVersionTuple(arglist) if (not arglist.getLastArg(arglist.parser.AOption) and not arglist.getLastArg(arglist.parser.nostdlibOption) and not arglist.getLastArg(arglist.parser.nostartfilesOption)): # Derived from startfile spec. if arglist.getLastArg(arglist.parser.dynamiclibOption): # Derived from darwin_dylib1 spec. if arglist.getLastArg(arglist.parser.m_iphoneosVersionMinOption): cmd_args.append('-ldylib1.o') else: if macosxVersion < (10,5): cmd_args.append('-ldylib1.o') else: cmd_args.append('-ldylib1.10.5.o') else: if arglist.getLastArg(arglist.parser.bundleOption): if not arglist.getLastArg(arglist.parser.staticOption): cmd_args.append('-lbundle1.o') else: if arglist.getLastArg(arglist.parser.pgOption): if arglist.getLastArg(arglist.parser.staticOption): cmd_args.append('-lgcrt0.o') else: if arglist.getLastArg(arglist.parser.objectOption): cmd_args.append('-lgcrt0.o') else: if arglist.getLastArg(arglist.parser.preloadOption): cmd_args.append('-lgcrt0.o') else: cmd_args.append('-lgcrt1.o') # darwin_crt2 spec is empty. pass else: if arglist.getLastArg(arglist.parser.staticOption): cmd_args.append('-lcrt0.o') else: if arglist.getLastArg(arglist.parser.objectOption): cmd_args.append('-lcrt0.o') else: if arglist.getLastArg(arglist.parser.preloadOption): cmd_args.append('-lcrt0.o') else: # Derived from darwin_crt1 spec. if arglist.getLastArg(arglist.parser.m_iphoneosVersionMinOption): cmd_args.append('-lcrt1.o') else: if macosxVersion < (10,5): cmd_args.append('-lcrt1.o') else: cmd_args.append('-lcrt1.10.5.o') # darwin_crt2 spec is empty. pass if arglist.getLastArg(arglist.parser.sharedLibgccOption): if not arglist.getLastArg(arglist.parser.m_iphoneosVersionMinOption): if macosxVersion < (10,5): cmd_args.append(self.toolChain.getFilePath('crt3.o')) arglist.addAllArgs(cmd_args, arglist.parser.LOption) if arglist.getLastArg(arglist.parser.f_openmpOption): # This is more complicated in gcc... cmd_args.append('-lgomp') # FIXME: Derive these correctly. tcDir = self.toolChain.getToolChainDir() if self.toolChain.archName == 'x86_64': cmd_args.extend(["-L/usr/lib/gcc/%s/x86_64" % tcDir, "-L/usr/lib/gcc/%s/x86_64" % tcDir]) cmd_args.extend(["-L/usr/lib/%s" % tcDir, "-L/usr/lib/gcc/%s" % tcDir, "-L/usr/lib/gcc/%s" % tcDir, "-L/usr/lib/gcc/%s/../../../%s" % (tcDir,tcDir), "-L/usr/lib/gcc/%s/../../.." % tcDir]) for input in inputs: cmd_args.extend(arglist.renderAsInput(input.source)) if linkingOutput: cmd_args.append('-arch_multiple') cmd_args.append('-final_output') cmd_args.append(arglist.getValue(linkingOutput)) if (arglist.getLastArg(arglist.parser.f_profileArcsOption) or arglist.getLastArg(arglist.parser.f_profileGenerateOption) or arglist.getLastArg(arglist.parser.f_createProfileOption) or arglist.getLastArg(arglist.parser.coverageOption)): cmd_args.append('-lgcov') if arglist.getLastArg(arglist.parser.f_nestedFunctionsOption): cmd_args.append('-allow_stack_execute') if (not arglist.getLastArg(arglist.parser.nostdlibOption) and not arglist.getLastArg(arglist.parser.nodefaultlibsOption)): # link_ssp spec is empty. # Derived from libgcc spec. if arglist.getLastArg(arglist.parser.staticOption): cmd_args.append('-lgcc_static') elif arglist.getLastArg(arglist.parser.staticLibgccOption): cmd_args.append('-lgcc_eh') cmd_args.append('-lgcc') elif arglist.getLastArg(arglist.parser.m_iphoneosVersionMinOption): # Derived from darwin_iphoneos_libgcc spec. cmd_args.append('-lgcc_s.10.5') cmd_args.append('-lgcc') elif (arglist.getLastArg(arglist.parser.sharedLibgccOption) or arglist.getLastArg(arglist.parser.f_exceptionsOption) or arglist.getLastArg(arglist.parser.f_gnuRuntimeOption)): if macosxVersion < (10,5): cmd_args.append('-lgcc_s.10.4') else: cmd_args.append('-lgcc_s.10.5') cmd_args.append('-lgcc') else: if macosxVersion < (10,5) and macosxVersion >= (10,3,9): cmd_args.append('-lgcc_s.10.4') if macosxVersion >= (10,5): cmd_args.append('-lgcc_s.10.5') cmd_args.append('-lgcc') # Derived from lib spec. if not arglist.getLastArg(arglist.parser.staticOption): cmd_args.append('-lSystem') if (not arglist.getLastArg(arglist.parser.AOption) and not arglist.getLastArg(arglist.parser.nostdlibOption) and not arglist.getLastArg(arglist.parser.nostartfilesOption)): # endfile_spec is empty. pass arglist.addAllArgs(cmd_args, arglist.parser.TGroup) arglist.addAllArgs(cmd_args, arglist.parser.FOption) jobs.addJob(Jobs.Command(self.toolChain.getProgramPath('collect2'), cmd_args)) if (arglist.getLastArg(arglist.parser.gGroup) and not arglist.getLastArg(arglist.parser.gstabsOption) and not arglist.getLastArg(arglist.parser.g0Option)): # FIXME: This is gross, but matches gcc. The test only # considers the suffix (not the -x type), and then only of the # first input. inputSuffix = os.path.splitext(arglist.getValue(inputs[0].baseInput))[1] if inputSuffix in ('.c','.cc','.C','.cpp','.cp', '.c++','.cxx','.CPP','.m','.mm'): jobs.addJob(Jobs.Command('dsymutil', arglist.renderAsInput(output))) class LipoTool(Tool): def __init__(self, toolChain): super(LipoTool, self).__init__('lipo', toolChain) def constructJob(self, phase, arch, jobs, inputs, output, outputType, arglist, linkingOutput): assert outputType in (Types.ObjectType, Types.ImageType) cmd_args = ['-create'] cmd_args.extend(arglist.render(output)) for input in inputs: cmd_args.extend(arglist.renderAsInput(input.source)) jobs.addJob(Jobs.Command('lipo', cmd_args))
2f2b80d82461e05a0fc8a209c3a7839de54835cd
[ "CMake", "HTML", "Makefile", "Python", "Text", "C", "C++", "Shell" ]
491
C
bratsche/clang
77c7d34ab7344a7cb55595cdbc38bc9febe6b11f
e6ac7531a4ad777402e556c5d2ac043234520e07
refs/heads/master
<repo_name>BoyuanYan/Optical-Fiber-Course-Design<file_sep>/butterfly.cpp #include "butterfly.h" #include <math.h> const static double PI=3.1416; //static bool pre = 0; Butterfly::Butterfly(QObject *parent) : QObject(parent) { up = 1234; pix_up.load("C://keshe/交换图片/1234 111111.png"); //pix_down.load("C://keshe/交换图片/1234 111111.png"); startTimer(50);//刷新频率20Hz } QRectF Butterfly::boundingRect() const { qreal adjust =2; return QRectF(-pix_up.width()/2-adjust,-pix_up.height()/2-adjust,pix_up.width()+adjust*2,pix_up.height()+adjust*2); } void Butterfly::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { switch(up) { case 1234: pix_up.load("C://keshe/交换图片/1234 111111.png"); break; case 1243: pix_up.load("C://keshe/交换图片/1243 101111.png"); break; case 1324: pix_up.load("C://keshe/交换图片/1324 101010.png"); break; case 1342: pix_up.load("C://keshe/交换图片/1342 101011.png"); break; case 1423: pix_up.load("C://keshe/交换图片/1423 111010.png"); break; case 1432: pix_up.load("C://keshe/交换图片/1432 111011.png"); break; case 2134: pix_up.load("C://keshe/交换图片/2134 111101.png"); break; case 2143: pix_up.load("C://keshe/交换图片/2143 111100.png"); break; case 2314: pix_up.load("C://keshe/交换图片/2314 110101.png"); break; case 2341: pix_up.load("C://keshe/交换图片/2341 110100.png"); break; case 2413: pix_up.load("C://keshe/交换图片/2413 100101.png"); break; case 2431: pix_up.load("C://keshe/交换图片/2431 100100.png"); break; case 3124: pix_up.load("C://keshe/交换图片/3124 101000.png"); break; case 3142: pix_up.load("C://keshe/交换图片/3142 101001.png"); break; case 3214: pix_up.load("C://keshe/交换图片/3214 001000.png"); break; case 3241: pix_up.load("C://keshe/交换图片/3241 001001.png"); break; case 3412: pix_up.load("C://keshe/交换图片/3412 000000.png"); break; case 3421: pix_up.load("C://keshe/交换图片/3421 000001.png"); break; case 4123: pix_up.load("C://keshe/交换图片/4123 000111.png"); break; case 4132: pix_up.load("C://keshe/交换图片/4132 000110.png"); break; case 4213: pix_up.load("C://keshe/交换图片/4213 100111.png"); break; case 4231: pix_up.load("C://keshe/交换图片/4231 100110.png"); break; case 4312: pix_up.load("C://keshe/交换图片/4312 100011.png"); break; case 4321: pix_up.load("C://keshe/交换图片/4321 100010.png"); break; default: //此处应弹出错误信息框 break; } painter->drawPixmap(boundingRect().topLeft(),pix_up); } void Butterfly::timerEvent(QTimerEvent *) { update(); } <file_sep>/README.md 本程序是专门为光纤通信课程设计所做的前台应用程序。 使用IDE:Qt Creator 5.3 (MingGW) 注意:加载显示图片的路径为“C://keshe/*”,应改为当前目录下的"/交换图片"。 <file_sep>/main.cpp #include "mainwindow.h" #include <QApplication> #include <QSplashScreen> #include <QPixmap> int main(int argc, char *argv[]) { QApplication a(argc, argv); //显示启动画面 QPixmap pixmap("C://keshe/startup.png"); QSplashScreen splash(pixmap); splash.show(); Qt::Alignment topRight = Qt::AlignRight | Qt::AlignTop; splash.showMessage(QObject::tr("《光纤通信》课程设计第一组作品\n程序加载中...\n\\*^o^*// "), topRight, Qt::black); a.processEvents();//使程序在显示启动画面的同时仍然能够响应鼠标等其他事件。 MainWindow w; w.show(); splash.finish(&w); return a.exec(); } <file_sep>/mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QApplication> #include "butterfly.h" #include <QGraphicsScene> #include <QMessageBox>//ch2 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->closeMyComBtn->setEnabled(false); ui->sendMsgBtn->setEnabled(false); /**********以下是交换逻辑显示部分**********/ QGraphicsScene *scene = new QGraphicsScene; scene->setSceneRect(QRectF(-330,-120,700,250)); butterfly = new Butterfly; butterfly->setPos(0,0); scene->addItem(butterfly); ui->graphicsView->setScene(scene); ui->graphicsView->resize(700,250); ui->graphicsView->show(); /**********以上是交换逻辑显示部分**********/ ui->Reset_Btn->setEnabled(false);//默认设置下不能复位,即“重置”不可用 //ui->Output1->currentIndex();//获取Output1当前的index值,从0到3对应选项的1-4。 Sleep(2000);//休眠2s,用于显示程序启动画面 } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_Confirm_Btn_clicked()//ch1 { int a,b,c,d,out; a = ui->Output1->currentIndex(); b = ui->Output2->currentIndex(); c = ui->Output3->currentIndex(); d = ui->Output4->currentIndex(); out = (a+1)*1000 + (b+1)*100 + (c+1)*10 +(d+1); butterfly->up = out; if(out == 1234) { ui->Reset_Btn->setEnabled(false); } else { ui->Reset_Btn->setEnabled(true); } switch(out) { case 1234: //myCom->write("abcdef"); myCom->write("a"); break; case 1243: //myCom->write("aBcdef"); myCom->write("b"); break; case 1324: //myCom->write("aBcDeF"); myCom->write("c"); break; case 1342: //myCom->write("aBcDef"); myCom->write("d"); break; case 1423: //myCom->write("abcDeF"); myCom->write("e"); break; case 1432: //myCom->write("abcDef"); myCom->write("f"); break; case 2134: //myCom->write("abcdEf"); myCom->write("g"); break; case 2143: //myCom->write("abcdEF"); myCom->write("h"); break; case 2314: //myCom->write("abCdEf"); myCom->write("i"); break; case 2341: //myCom->write("abCdEF"); myCom->write("j"); break; case 2413: //myCom->write("aBCdEf"); myCom->write("k"); break; case 2431: //myCom->write("aBCdEF"); myCom->write("l"); break; case 3124: //myCom->write("aBcDEF"); myCom->write("m"); break; case 3142: //myCom->write("aBcDEf"); myCom->write("n"); break; case 3214: //myCom->write("ABcDEF"); myCom->write("o"); break; case 3241: //myCom->write("ABcDEf"); myCom->write("p"); break; case 3412: //myCom->write("ABCDEF"); myCom->write("q"); break; case 3421: //myCom->write("ABCDEf"); myCom->write("r"); break; case 4123: //myCom->write("ABCdef"); myCom->write("s"); break; case 4132: //myCom->write("ABCdeF"); myCom->write("t"); break; case 4213: //myCom->write("aBCdef"); myCom->write("u"); break; case 4231: //myCom->write("aBCdeF"); myCom->write("v"); break; case 4312: //myCom->write("aBCDef"); myCom->write("w"); break; case 4321: //myCom->write("aBCDeF"); myCom->write("x"); break; default: //此处应弹出错误框 break; } } void MainWindow::on_Reset_Btn_clicked() { ui->Output1->setCurrentIndex(0); ui->Output2->setCurrentIndex(1); ui->Output3->setCurrentIndex(2); ui->Output4->setCurrentIndex(3); ui->Reset_Btn->setEnabled(false); butterfly->up = 1234; //发送控制消息 myCom->write("a"); } void MainWindow::on_actionReference_triggered() { QMessageBox *ref = new QMessageBox; ref->information(NULL,tr("隔离度参考"),tr(" 高电平交叉(dB) 低电平平行(dB)\n\ A1-A3 -7.3 A1-A2 -7.35\n\n\ A4-A2 -7.46 A4-A3 -7.35\n\n\ B1-B3 -7.85 B1-B2 -8.37\n\n\ B4-B2 -8.78 B4-B3 -7.67\n\n\ C1-C3 -7.65 C1-C2 -7.95\n\n\ C4-C2 -7.48 C4-C3 -8.32\n\n\ D1-D3 -7.89 D1-D2 -8.93\n\n\ D4-D2 -7.78 D4-D3 -9.03\n\n\ E1-E3 -7.99 E1-E2 -7.27\n\n\ E4-E2 -7.89 E4-E3 -7.37\n\n\ F1-F3 -8.02 F1-F2 -8.00\n\n\ F4-F2 -8.00 F4-F3 -7.92\n\n ")); } void MainWindow::on_actionAbout_Version_triggered() { QMessageBox *ver = new QMessageBox; ver->information(NULL,tr("Version"),tr("Version 1.0\n\n请注意:作者不再维护该应用!\n")); } void MainWindow::on_actionContact_triggered() { QMessageBox *con = new QMessageBox; con->information(NULL,tr("联系我们"),tr("作者:闫伯元\n\ngithub:https://github.com/BoyuanYan/Optical-Fiber-Course-Design\n\n联系方式:yanliuzhangyan@163.com\n")); } void MainWindow::readMyCom() { QByteArray temp = myCom->readAll(); ui->textBrowser->insertPlainText(temp); } void MainWindow::on_openMyComBtn_clicked() { struct PortSettings myComSetting = {BAUD19200, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 500}; myCom = new Win_QextSerialPort("com3", myComSetting, QextSerialBase::EventDriven);//com3 // struct PortSettings myComSetting = {BAUD9600, DATA_7, PAR_NONE, STOP_1, FLOW_OFF, 500}; // myCom = new Win_QextSerialPort("com6", myComSetting, QextSerialBase::EventDriven); myCom->open(QIODevice::ReadWrite); connect(myCom, SIGNAL(readyRead()), this, SLOT(readMyCom())); ui->openMyComBtn->setEnabled(false); ui->closeMyComBtn->setEnabled(true); ui->sendMsgBtn->setEnabled(true); } void MainWindow::on_closeMyComBtn_clicked() { myCom->close(); ui->openMyComBtn->setEnabled(true); ui->closeMyComBtn->setEnabled(false); ui->sendMsgBtn->setEnabled(false); } void MainWindow::on_sendMsgBtn_clicked() { myCom->write(ui->sendMsgLineEdit->text().toLatin1()); }
db5476736d0076ff1433d55ac4bcce62d5e6b878
[ "Markdown", "C++" ]
4
C++
BoyuanYan/Optical-Fiber-Course-Design
604366a1b142687d749e189093ddc67e49680c6e
ca4f7ab2b35819599df45492b03e96a713cc5aac
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; namespace VillaCorano.App_Start { public class BugFixFriendlyUrlResolver : Microsoft.AspNet.FriendlyUrls.Resolvers.WebFormsFriendlyUrlResolver { protected override bool TrySetMobileMasterPage(HttpContextBase httpContext, Page page, string mobileSuffix) { return false; //return base.TrySetMobileMasterPage(httpContext, page, mobileSuffix); } } }<file_sep>using System; using System.Configuration; using System.Net.Mail; using System.Text; using System.Web.UI; using WebGrease.Css.Extensions; namespace VillaCorano { public partial class Ordini : Page { } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Web; namespace VillaCorano { public static class MailUtilities { private static string mailVillaCorano = System.Configuration.ConfigurationManager.AppSettings["MailTo"]; private static string pwd = System.Configuration.ConfigurationManager.AppSettings["Pwd"]; private static string host = System.Configuration.ConfigurationManager.AppSettings["Host"]; private static string iban = System.Configuration.ConfigurationManager.AppSettings["Iban"]; public static bool SendOrderToCustomer(string nomeCliente, string cognomeCliente, string mailTo, List<string> listaProdotti, string metodoDiPagamento, string totale, string nazione, string via, string cap, string civico, string citta, bool isFatturazione, string ragioneSociale, string pIva, string fVia, string codiceFiscale,string sede) { bool send = false; try { MailMessage message =new MailMessage() { From = new MailAddress(mailVillaCorano) }; SmtpClient client = new SmtpClient { Port = 587, Credentials = new System.Net.NetworkCredential(mailVillaCorano, pwd), Host = host, EnableSsl = true }; StringBuilder sb = new StringBuilder(); sb.Append("Gentile Cliente: " + nomeCliente + " " + cognomeCliente + ", "); sb.AppendLine(); sb.AppendLine("Di seguito i dettagli del suo ordine"); listaProdotti.ForEach(p=>sb.AppendLine(p +" bottiglie.")); sb.AppendLine(); sb.AppendLine("Metodo di pagamento scelto: " + metodoDiPagamento); sb.AppendLine("Totale Ordine: " + totale + " €"); sb.AppendLine("Indirizzo di Spedizione: "); sb.AppendLine("Nazione: " + nazione); sb.AppendLine("Città: " + citta); sb.AppendLine("Via: " + via); sb.AppendLine("Civico: " + civico); sb.AppendLine("Cap: " + cap); if (metodoDiPagamento.Contains("Bonifico")) { sb.AppendLine( "Avete scelto di pagare tramite bonifico bancario di seguito le coordinate a cui potete effettuare il bonifico."); sb.AppendLine(); sb.AppendLine(" Intestatario: <NAME>"); sb.AppendLine(" IBAN: " + iban); sb.AppendLine(); sb.AppendLine("La preghiamo di mandarci co" + "nferma non appena effettuato il bonifico così da procedere alla spedizione della merce"); } if (isFatturazione) { sb.AppendLine("L'indirizzo di fatturazione indicatoci è:"); sb.AppendLine("Ragione Sociale: "+ragioneSociale); sb.AppendLine("Partita Iva: " +pIva); sb.AppendLine("Via: " +fVia); if (!string.IsNullOrEmpty(codiceFiscale)) { sb.AppendLine("Codice Fiscale: " + codiceFiscale); } sb.AppendLine("la preghiamo di segnalarci al più presto, eventuali incongurenze."); } sb.AppendLine(); sb.AppendLine(); sb.AppendLine("Lo staff di <NAME> la ringrazia per averci accordato la sua preferenza"); sb.AppendLine("A presto!"); sb.AppendLine(); sb.AppendLine(); sb.AppendLine("Contatti: "); sb.AppendLine("Tel./Fax: 0564 - 61.44.64"); sb.AppendLine("Cell.349-50.16.047"); sb.AppendLine("Indirizzo: S.R 74, <NAME>vest Km. 46,760"); sb.AppendLine(); sb.AppendLine(); message.To.Add(new MailAddress(mailTo)); message.Subject = "Villa Corano: Conferma Ordine!"; message.Body = sb.ToString(); client.Send(message); return send = true; } catch (Exception ex) { return send = false; } } public static bool SendOrderToHost(string nomeCliente, string cognomeCliente, List<string> listaProdotti, string metodoDiPagamento,string numeroTelefono, string emailCliente, string nazione, string citta, string cap, string via, string civico, string prezzoTotale, bool isFatturazione, string pIva, string fVia, string ragioneSociale, string codiceFiscale,string sede) { bool send = false; try { MailMessage message = new MailMessage() { From = new MailAddress(mailVillaCorano) }; SmtpClient client = new SmtpClient { Port = 587, Credentials = new System.Net.NetworkCredential(mailVillaCorano, pwd), Host = host, EnableSsl = true }; StringBuilder sb = new StringBuilder(); sb.Append("Nuovo Ordine: "); sb.AppendLine(); sb.AppendLine("Hai ricevuto un nuovo ordine. Di seguito i dettagli:"); sb.AppendLine("Cliente: " + nomeCliente + " " + cognomeCliente); sb.AppendLine("N° Telefono: " + numeroTelefono); sb.AppendLine("Email Cliente: " + emailCliente); sb.AppendLine(); sb.AppendLine("Quantità: "); listaProdotti.ForEach(p => sb.AppendLine(p + " bottiglie.")); sb.AppendLine("Metodo di pagamento scelto: " + metodoDiPagamento); sb.AppendLine(); sb.AppendLine("Indirizzo di Spedizione:"); sb.AppendLine("Nazione: " + nazione); sb.AppendLine("Città: " + citta); sb.AppendLine("Via: " + via); sb.AppendLine("N° Civico: " + civico); sb.AppendLine("CAP: " + cap); if (isFatturazione) { sb.AppendLine(); sb.AppendLine("Il cliente ha indicato un indirizzo di fatturazione diverso da quello di spedizione."); sb.AppendLine(); sb.AppendLine("Di seguito i dettagli: "); sb.AppendLine(); sb.AppendLine("Ragione Sociale: " + ragioneSociale); sb.AppendLine("Partita Iva: " + pIva); sb.AppendLine("Sede: " + sede); sb.AppendLine("Via: " + fVia); if (!string.IsNullOrEmpty(codiceFiscale)) { sb.AppendLine("Codice Fiscale: " + codiceFiscale); } } sb.AppendLine("Costo Totale: " + prezzoTotale + "€"); sb.AppendLine(); sb.AppendLine(); message.From = new MailAddress(mailVillaCorano); message.To.Add(new MailAddress(mailVillaCorano)); message.Subject = "Nuovo Ordine!"; message.Body = sb.ToString(); client.Send(message); return send = true; } catch (Exception ex) { return send = false; } } } }<file_sep>using System; using System.Collections.Generic; using System.Web; using System.Web.Routing; using Microsoft.AspNet.FriendlyUrls; using VillaCorano.App_Start; namespace VillaCorano { public static class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { var settings = new FriendlyUrlSettings(); settings.AutoRedirectMode = RedirectMode.Permanent; routes.EnableFriendlyUrls(settings,new BugFixFriendlyUrlResolver()); } } } <file_sep>using System.Web.UI; namespace VillaCorano.Account { public partial class ResetPasswordConfirmation : Page { } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace VillaCorano.Controls { public partial class SimpleSideBar : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e) { e.IsValid = privacyCheck.Checked; } protected void CompletaOrdine_OnClick(object sender, EventArgs e) { try { string nome = txtNome.Text; string cognome = txtCognome.Text; string email = txtEmail.Text; string numeroTel = txtTelefono.Text; string metodoDiPagamento = ddlMetodoDiPagamento.SelectedItem.Text; string tot = hfPrezzo.Value; string nazione = txtNazione.Text; string via = txtVia.Text; string cap = txtCap.Text; string civico = txtCivico.Text; string citta = txtCitta.Text; string ragSoc = txtRagSoc.Text; bool isFatturazione = !string.IsNullOrEmpty(ragSoc); string pIva = txtIva.Text; string fVia = txtSVia.Text; string sede = txtSede.Text; string codiceFiscale = txtCF.Text; List<string> ordini= new List<string>(); if (Page.IsValid) { hfOrdine.Value.Split(';').ToList().ForEach(o => { if (o.Contains("Prezzo")) { var ord = o.Split(new[] {"Prezzo"}, StringSplitOptions.RemoveEmptyEntries)[0].Replace( "Quantità:", String.Empty); ordini.Add(ord); } }); bool sentToHost = MailUtilities.SendOrderToHost(nome, cognome, ordini, metodoDiPagamento, numeroTel, email, nazione, citta, cap, via, civico, tot, isFatturazione, pIva, fVia, ragSoc, codiceFiscale, sede); if (sentToHost) { bool sentToCustomer = MailUtilities.SendOrderToCustomer(nome, cognome, email, ordini, metodoDiPagamento, tot, nazione, via, cap, civico, citta, isFatturazione, ragSoc, pIva, fVia, codiceFiscale, sede); if (sentToCustomer) { string message = "Gentile Ospite, le confermiamo l invio dell ordine. A breve riceverà una email di conferma." + "A presto, <NAME>"; Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true); } else { string message = "Gentile Cliente, le confermiamo l invio dell ordine," + "Grazie. " + "A presto, <NAME>"; Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true); } } else { throw new Exception(); } } } catch(Exception ex) { string message = "Gentile Cliente, non è stato possibile completare l ordine. La invitiamo a riprovare o a contattarci telefonicamente." + "Grazie. <NAME>"; Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true); } } } }
200d1b7fe5eae368fa4f4ca73d2c15031dc31b31
[ "C#" ]
6
C#
GabrieleisCoding/VillaCorano
fcd75948525439ca1744deca97d6c3f0e762a4c7
03f743b9e8de73c8c1d1d33b578e7dcc7bbd0631
refs/heads/master
<repo_name>maasencioh/generator-mljs-packages<file_sep>/README.md # generator-mljs-packages [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][daviddm-image]][daviddm-url] [![Coverage percentage][coveralls-image]][coveralls-url] [![npm download][download-image]][download-url] > Generator for ml.js packages ## :warning: Deprecated! Instead you should use [generator-cheminfo](https://github.com/cheminfo/generator-cheminfo), it's the modern version of this package ## Description The generator will prompt for the next fields: * __Your project name__: the package name, without the `ml-` start * __Your name__: your [NPM name](https://docs.npmjs.com/files/package.json#people-fields-author-contributors) * __Your email__: your email * __Your package description__: A description to show in [NPM](https://docs.npmjs.com/files/package.json#description-1) * __Your package version__: The package version. The default value is `0.0.1` * __Do you want to install coverage tool?__: Add the coveralls badge and scripts. The default value is `false` * __Run NPM install?__: Run `npm install` after the template generation When the generator finish there will be the following files: ``` . ├── .eslintrc.yml ├── .gitignore ├── .travis.yml ├── History.md ├── LICENSE ├── README.md ├── package.json ├── tonic.js ├── src │   └── index.js └── test └── test.js ``` ## Contributors * [<NAME>](https://github.com/maasencioh) ## License [MIT](./LICENSE) [npm-image]: https://badge.fury.io/js/generator-mljs-packages.svg [npm-url]: https://npmjs.org/package/generator-mljs-packages [travis-image]: https://travis-ci.org/mljs/generator-mljs-packages.svg?branch=master [travis-url]: https://travis-ci.org/mljs/generator-mljs-packages [daviddm-image]: https://david-dm.org/mljs/generator-mljs-packages.svg?theme=shields.io [daviddm-url]: https://david-dm.org/mljs/generator-mljs-packages [coveralls-image]: https://coveralls.io/repos/github/mljs/generator-mljs-packages/badge.svg?branch=master [coveralls-url]: https://coveralls.io/github/mljs/generator-mljs-packages?branch=master [download-image]: https://img.shields.io/npm/dm/generator-mljs-packages.svg?style=flat-square [download-url]: https://npmjs.org/package/generator-mljs-packages <file_sep>/app/templates/README.md # <%= name %> [![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] <% if (coveralls) { %>[![Test coverage][coveralls-image]][coveralls-url]<% } %> [![David deps][david-image]][david-url] [![npm download][download-image]][download-url] <%= description %> ## Installation ``` $ npm install ml-<%= name %> ``` ## [API Documentation](https://mljs.github.io/<%= name %>/) ## License [MIT](./LICENSE) [npm-image]: https://img.shields.io/npm/v/ml-<%= name %>.svg?style=flat-square [npm-url]: https://npmjs.org/package/ml-<%= name %> [travis-image]: https://img.shields.io/travis/mljs/<%= name %>/master.svg?style=flat-square [travis-url]: https://travis-ci.org/mljs/<%= name %> <% if (coveralls) { %>[coveralls-image]: https://img.shields.io/coveralls/mljs/<%= name %>.svg?style=flat-square [coveralls-url]: https://coveralls.io/github/mljs/<%= name %><% } %> [david-image]: https://img.shields.io/david/mljs/<%= name %>.svg?style=flat-square [david-url]: https://david-dm.org/mljs/<%= name %> [download-image]: https://img.shields.io/npm/dm/ml-<%= name %>.svg?style=flat-square [download-url]: https://npmjs.org/package/ml-<%= name %> <file_sep>/History.md <a name="1.9.4"></a> ## [1.9.4](https://github.com/mljs/generator-mljs-packages/compare/v1.9.3...v1.9.4) (2016-11-08) <a name="1.9.3"></a> ## [1.9.3](https://github.com/mljs/generator-mljs-packages/compare/v1.9.2...v1.9.3) (2016-10-04) ### Bug Fixes * good rendering of the username and add url link as npm describes ([9947076](https://github.com/mljs/generator-mljs-packages/commit/9947076)), closes [#9](https://github.com/mljs/generator-mljs-packages/issues/9) <a name="1.9.2"></a> ## [1.9.2](https://github.com/mljs/generator-mljs-packages/compare/v1.9.1...v1.9.2) (2016-10-04) ### Bug Fixes * good rendering of the username and add url link as npm describes ([5388526](https://github.com/mljs/generator-mljs-packages/commit/5388526)), closes [#9](https://github.com/mljs/generator-mljs-packages/issues/9) <a name="1.9.1"></a> ## [1.9.1](https://github.com/mljs/generator-mljs-packages/compare/v1.9.0...v1.9.1) (2016-09-22) ### Bug Fixes * trail space after coverage ([4fe637a](https://github.com/mljs/generator-mljs-packages/commit/4fe637a)) <a name="1.9.0"></a> # [1.9.0](https://github.com/mljs/generator-mljs-packages/compare/v1.8.1...v1.9.0) (2016-09-22) ### Features * add coverage options ([06ea7d1](https://github.com/mljs/generator-mljs-packages/commit/06ea7d1)) <a name="1.8.1"></a> ## [1.8.1](https://github.com/mljs/generator-mljs-packages/compare/v1.8.0...v1.8.1) (2016-09-06) ### Bug Fixes * notify when git config fails ([20570c9](https://github.com/mljs/generator-mljs-packages/commit/20570c9)) <a name="1.8.0"></a> # [1.8.0](https://github.com/mljs/generator-mljs-packages/compare/v1.7.0...v1.8.0) (2016-08-30) ### Features * **test:** add the tonic file, and add the camel case name to test and index ([a498d72](https://github.com/mljs/generator-mljs-packages/commit/a498d72)) <a name="1.7.0"></a> # [1.7.0](https://github.com/mljs/generator-mljs-packages/compare/v1.6.0...v1.7.0) (2016-08-30) ### Features * **test:** create empty test template ([bafbde0](https://github.com/mljs/generator-mljs-packages/commit/bafbde0)) <a name="1.6.0"></a> # [1.6.0](https://github.com/mljs/generator-mljs-packages/compare/v1.5.0...v1.6.0) (2016-08-02) ### Features * update mocha to v3.x ([8210299](https://github.com/mljs/generator-mljs-packages/commit/8210299)) <a name="1.5.0"></a> # [1.5.0](https://github.com/mljs/generator-mljs-packages/compare/v1.4.1...v1.5.0) (2016-07-29) ### Bug Fixes * keep dashes in package name ([beaff21](https://github.com/mljs/generator-mljs-packages/commit/beaff21)) ### Features * use git username by default ([22faddf](https://github.com/mljs/generator-mljs-packages/commit/22faddf)) <a name="1.4.1"></a> ## [1.4.1](https://github.com/mljs/generator-mljs-packages/compare/v1.4.0...v1.4.1) (2016-07-26) ### Bug Fixes * add peer dependency for eslint ([1a4eacb](https://github.com/mljs/generator-mljs-packages/commit/1a4eacb)) * don't test on old and unsupported node ([a279cfc](https://github.com/mljs/generator-mljs-packages/commit/a279cfc)) <a name="1.4.0"></a> # [1.4.0](https://github.com/mljs/generator-mljs-packages/compare/v1.3.0...v1.4.0) (2016-07-18) ### Bug Fixes * remove History.md ([#5](https://github.com/mljs/generator-mljs-packages/issues/5)) ([40b927b](https://github.com/mljs/generator-mljs-packages/commit/40b927b)) ### Features * apply eslint to test directory ([58356ad](https://github.com/mljs/generator-mljs-packages/commit/58356ad)) <a name="1.3.0"></a> # [1.3.0](https://github.com/mljs/generator-mljs-packages/compare/v1.2.0...v1.3.0) (2016-07-18) ### Features * bump dependency versions in template ([a799dc6](https://github.com/mljs/generator-mljs-packages/commit/a799dc6)) * use eslint-config-cheminfo ([86f7c01](https://github.com/mljs/generator-mljs-packages/commit/86f7c01)) <a name="1.2.0"></a> # [1.2.0](https://github.com/mljs/generator-mljs-packages/compare/v1.1.0...v1.2.0) (2016-07-18) ### Bug Fixes * wrong use strict ([023f819](https://github.com/mljs/generator-mljs-packages/commit/023f819)) ### Features * don't test on old versions of node ([b28ae71](https://github.com/mljs/generator-mljs-packages/commit/b28ae71)) * use latest version of eslint ([7018ccd](https://github.com/mljs/generator-mljs-packages/commit/7018ccd)) <a name="1.1.0"></a> # [1.1.0](https://github.com/mljs/generator-mljs-packages/compare/v1.0.12...v1.1.0) (2016-06-22) <a name="1.0.12"></a> ## [1.0.12](https://github.com/mljs/generator-mljs-packages/compare/v1.0.11...v1.0.12) (2016-06-21) <a name="1.0.11"></a> ## [1.0.11](https://github.com/mljs/generator-mljs-packages/compare/v1.0.10...v1.0.11) (2016-06-21) <a name="1.0.10"></a> ## [1.0.10](https://github.com/mljs/generator-mljs-packages/compare/v1.0.9...v1.0.10) (2016-06-21) <a name="1.0.9"></a> ## [1.0.9](https://github.com/mljs/generator-mljs-packages/compare/v1.0.8...v1.0.9) (2016-06-21) <a name="1.0.8"></a> ## [1.0.8](https://github.com/mljs/generator-mljs-packages/compare/v1.0.7...v1.0.8) (2016-06-21) <a name="1.0.7"></a> ## [1.0.7](https://github.com/mljs/generator-mljs-packages/compare/v1.0.6...v1.0.7) (2016-06-21) <a name="1.0.6"></a> ## [1.0.6](https://github.com/mljs/generator-mljs-packages/compare/v1.0.5...v1.0.6) (2016-06-20) <a name="1.0.5"></a> ## [1.0.5](https://github.com/mljs/generator-mljs-packages/compare/v1.0.4...v1.0.5) (2016-06-20) <a name="1.0.4"></a> ## [1.0.4](https://github.com/mljs/generator-mljs-packages/compare/v1.0.3...v1.0.4) (2016-06-20) <a name="1.0.3"></a> ## [1.0.3](https://github.com/mljs/generator-mljs-packages/compare/v1.0.2...v1.0.3) (2016-06-20) <a name="1.0.2"></a> ## [1.0.2](https://github.com/mljs/generator-mljs-packages/compare/v1.0.1...v1.0.2) (2016-06-20) <a name="1.0.1"></a> ## [1.0.1](https://github.com/mljs/generator-mljs-packages/compare/v1.0.0...v1.0.1) (2016-06-20) <a name="1.0.0"></a> # 1.0.0 (2016-06-20) <file_sep>/test/app.js 'use strict'; const path = require('path'); const assert = require('yeoman-assert'); const helpers = require('yeoman-test'); describe('generator-mljs-packages:app', function () { before(function () { return helpers.run(path.join(__dirname, '../app')) .withPrompts({ userName: 'cheminfo', description: 'test' }) .toPromise(); }); it('creates files', function () { assert.file([ '.gitignore', '.travis.yml', '.eslintrc.yml', 'src/index.js', 'test/test.js', 'LICENSE', 'package.json', 'tonic.js', 'README.md' ]); }); });
f8cec63ebf8c2c33fb6ec2190ac7c40a69453e57
[ "Markdown", "JavaScript" ]
4
Markdown
maasencioh/generator-mljs-packages
aa4d98998ee080c67cf8d5600e22633d150bd892
575c514e629201fe996392bd13e798285a59a112
refs/heads/master
<file_sep>export default function tripPlan(origin, destination, data) { this.origin = origin; this.transferStation = false; this.tertiaryStation = false; this.destination = destination; this.data = data; this.date = new Date(); this.day = this.date.getDay(); this.time = this.getTime(); this.transferArrival = false; this.transferDeparture = false; this.tertiaryArrival = false; this.tertiaryDeparture = false; this.departureTime = false; this.arrivalTime = false; this.transferStations = ['West Oakland', 'Balboa Park', 'MacArthur', 'Oakland Coliseum']; } tripPlan.prototype.findRoutes = function(startTime) { var junctions = this.findJunctions(this.origin, this.destination); try { var possibleTrips = this.planDirect(startTime, this.origin, this.destination); this.getLastStation(possibleTrips[0]); if (possibleTrips.length === 0) { throw new Error('no trips..'); } else { this.departureTime = parseInt(this.getTripTime(possibleTrips[0], this.origin).split(':').join('')); this.arrivalTime = parseInt(this.getTripTime(possibleTrips[0], this.destination).split(':').join('')); return { day: this.day, departureTime: this.departureTime, origin: this.origin, firstTrip: possibleTrips[0], arrivalTime: this.arrivalTime, destination: this.destination, firstDest: this.getLastStation(possibleTrips[0]) }; } } catch(ex) { try { return this.tryJunction(startTime, junctions[0]); } catch(ex) { try { return this.tryJunction(startTime, junctions[1]); } catch(ex) { try { return this.tryJunction(startTime, junctions[2]); } catch(ex) { try { return this.tryJunction(startTime, junctions[3]); } catch(ex) { try { return this.findTertiaryRoute(startTime); } catch(ex) { return {firstLeg: false, day: this.day}; console.log('Sorry, there were no available routes.') } } } } } } finally { console.log('Finished search.'); } } // Route Finding - these functions plot entire routes based on the origin, destination, and transfer station. tripPlan.prototype.tryJunction = function(startTime, transferStation) { this.transferStation = transferStation; var possibleTrips = this.planJunctionRoute(startTime, transferStation); if (possibleTrips.length === 0) { throw new Error('no trips..'); } else { var firstTrip = possibleTrips.firstLeg[0]; var secondTrip = possibleTrips.secondLeg[0]; return { day: this.day, departureTime: this.departureTime, origin: this.origin, firstTrip, secondTrip, transferStation, transferArrival: this.transferArrival, transferDeparture: this.transferDeparture, destination: this.destination, arrivalTime: this.arrivalTime, firstDest: this.getLastStation(firstTrip), secondDest: this.getLastStation(secondTrip) }; } } tripPlan.prototype.findTertiaryRoute = function(startTime) { var destJunction = this.findClosestJunction(this.destination); var originJunction = this.findJunctions(this.origin, destJunction)[0]; this.transferStation = originJunction; this.tertiaryStation = destJunction; var possibleTrips = this.planTertiaryRoute(startTime, originJunction, destJunction); var firstTrip = possibleTrips.firstLeg[0]; var secondTrip = possibleTrips.secondLeg[0]; var thirdTrip = possibleTrips.thirdLeg[0]; return { day: this.day, departureTime: this.departureTime, origin: this.origin, firstTrip, secondTrip, thirdTrip, transferStation: this.transferStation, transferArrival: this.transferArrival, transferDeparture: this.transferDeparture, tertiaryStation: this.tertiaryStation, tertiaryArrival: this.tertiaryArrival, tertiaryDeparture: this.tertiaryDeparture, destination: this.destination, arrivalTime: this.arrivalTime, firstDest: this.getLastStation(firstTrip), secondDest: this.getLastStation(secondTrip), thirdDest: this.getLastStation(thirdTrip) }; } tripPlan.prototype.planTertiaryRoute = function(startTime, firstTransfer, secondTransfer) { var firstLeg = this.planDirect(startTime, this.origin, firstTransfer); this.departureTime = parseInt(this.getTripTime(firstLeg[0], this.origin).split(':').join('')); this.transferArrival = parseInt(this.getTripTime(firstLeg[0], firstTransfer).split(':').join('')); var secondLeg = this.planDirect(this.transferArrival, firstTransfer, secondTransfer); this.transferDeparture = parseInt(this.getTripTime(secondLeg[0], firstTransfer).split(':').join('')); this.tertiaryArrival = parseInt(this.getTripTime(secondLeg[0], secondTransfer).split(':').join('')); var thirdLeg = this.planDirect(this.tertiaryArrival, secondTransfer, this.destination); this.tertiaryDeparture = parseInt(this.getTripTime(thirdLeg[0], secondTransfer).split(':').join('')); this.arrivalTime = parseInt(this.getTripTime(thirdLeg[0], this.destination).split(':').join('')); return { firstLeg, secondLeg, thirdLeg } } tripPlan.prototype.planJunctionRoute = function(startTime, transferStation) { // Returns an object containing an array of possible trips to and from the transfer var firstLeg = this.planDirect(startTime, this.origin, transferStation); this.departureTime = parseInt(this.getTripTime(firstLeg[0], this.origin).split(':').join('')); this.transferArrival = parseInt(this.getTripTime(firstLeg[0], transferStation).split(':').join('')); var secondLeg = this.planDirect(this.transferArrival, transferStation, this.destination); this.transferDeparture = parseInt(this.getTripTime(secondLeg[0], transferStation).split(':').join('')); this.arrivalTime = parseInt(this.getTripTime(secondLeg[0], this.destination).split(':').join('')); return { firstLeg, secondLeg }; } tripPlan.prototype.planDirect = function(time, origin, destination) { // Returns an array of possible trips to the destination var initialTrips = this.findDirectTrips(origin, destination); var correctDirection = this.filterDirection(initialTrips, origin, destination); return this.filterTime(correctDirection, time, origin); } // Trip filtrations tripPlan.prototype.findDirectTrips = function(origin, destination) { // Finds all trips connecting two stations return Object.keys(this.data.trips).filter(function(key) { if (this.data.trips[key].stations[origin] != undefined && this.data.trips[key].stations[destination] != undefined) { return true; } else { return false; } }.bind(this)); } tripPlan.prototype.filterDirection = function(trips, origin, destination) { // Filter connecting trips to make sure they are in the correct direction return trips.filter(function(trip) { if (this.data.trips[trip].stations[destination] - this.data.trips[trip].stations[origin] > 0) { return true; } else { return false; } }.bind(this)); } tripPlan.prototype.filterTime = function(trips, time, station) { // Filters an array of trips based on whether or not they leave after (time) from a particular station return trips.filter(function(trip) { return (this.data.trips[trip]['days'][this.day]); }.bind(this)).filter(function(trip) { var tripTime = parseInt(this.data.stations[station][trip].split(':').join('')); return (tripTime > time); }.bind(this)).sort(function(a, b) { var aTime = parseInt(this.data.stations[station][a].split(':').join('')); var bTime = parseInt(this.data.stations[station][b].split(':').join('')); return (aTime - bTime); }.bind(this)) } // Basic Utility Functions tripPlan.prototype.findClosestJunction = function(origin) { var transferStations = this.transferStations.filter(function(transfer) { return (this.data.transfers[transfer][origin]); }.bind(this)); return transferStations.sort(function(a, b) { var aDistance = this.getDistance(origin, a); var bDistance = this.getDistance(origin, b); return (aDistance - bDistance); }.bind(this))[0]; } tripPlan.prototype.findJunctions = function(origin, destination) { // Returns an array of transfer stations connecting origin and destination var transferStations = this.transferStations.filter(function(transfer) { return (this.data.transfers[transfer][origin] && this.data.transfers[transfer][destination]); }.bind(this)); var sorted = transferStations.sort(function(a, b) { var aDistance = this.getDistance(origin, a); var bDistance = this.getDistance(origin, b); return (aDistance - bDistance); }.bind(this)); return sorted; } tripPlan.prototype.getDistance = function(origin, destination) { // Returns the distance (number of stations) between two stops var directTrips = this.findDirectTrips(origin, destination); var trips = this.filterDirection(directTrips, origin, destination); return this.data.trips[trips[0]].stations[destination] - this.data.trips[trips[0]].stations[origin]; } tripPlan.prototype.getTime = function() { // Returns an integer representing the current time var hour = (this.date.getHours() < 10 ? `0${this.date.getHours()}` : this.date.getHours()); var minute = (this.date.getMinutes() < 10 ? `0${this.date.getMinutes()}` : this.date.getMinutes()); var second = (this.date.getSeconds() < 10 ? `0${this.date.getSeconds()}` : this.date.getSeconds()); return parseInt(`${hour}${minute}${second}`); } tripPlan.prototype.getTripTime = function(trip, station) { // Returns the arrival/departure time given a particular trips and station return this.data.stations[station][trip]; } tripPlan.prototype.getLastStation = function(trip) { // Returns the last station (destination) for a particular trip return Object.keys(this.data.trips[trip].stations).sort(function(aKey, bKey) { return (this.data.trips[trip].stations[bKey] - this.data.trips[trip].stations[aKey]); }.bind(this))[0]; } export const stationKey = { '12th St. Oakland City Center': '12TH', '16th St. Mission': '16TH', '19th St. Oakland': '19TH', '24th St. Mission': '24TH', 'Ashby': 'ASHB', 'Balboa Park': 'BALB', 'Bay Fair': 'BAYF', 'Castro Valley': 'CAST', 'Civic Center/UN Plaza': 'CIVC', 'Oakland Coliseum': 'COLS', 'Colma': 'Colma', 'Concord': 'CONC', 'Daly City': 'DALY', 'Downtown Berkeley': 'DBRK', 'Dublin/Pleasanton': 'DUBL', 'El Cerrito del Norte': 'DELN', 'El Cerrito Plaza': 'PLZA', 'Embarcadero': 'EMBR', 'Fremont': 'FRMT', 'Fruitvale': 'FTVL', 'Glen Park': 'GLEN', 'Hayward': 'HAYW', 'Lafayette': 'LAFY', 'Lake Merritt': 'LAKE', 'MacArthur': 'MCAR', 'Millbrae': 'MLBR', 'Montgomery St.': 'MONT', 'North Berkeley': 'NBRK', 'North Concord/Martinez': 'NCON', 'Oakland Airport': 'OAKL', 'Orinda': 'ORIN', 'Pittsburg/Bay Point': 'PITT', 'Pleasant Hill': 'PHIL', 'Powell St.': 'POWL', 'Richmond': 'RICH', 'Rockridge': 'ROCK', 'San Bruno': 'SBRN', 'San Francisco Airport': 'SFIA', 'San Leandro': 'SANL', 'South Hayward': 'SHAY', 'South San Francisco': 'SSAN', 'Union City': 'UCTY', 'Walnut Creek': 'WCRK', 'West Dublin/Pleasanton': 'WDUB', 'West Oakland': 'WOAK' } <file_sep>import { PLAN_TRIP } from '../actions/index'; export default function (state = {}, action) { switch(action.type) { case PLAN_TRIP: const rawTrip = action.payload; if (rawTrip.thirdTrip) { document.title = 'BayTripr - It took me so long to find out. And I found out'; return 'soLong'; } else if (rawTrip.secondTrip) { document.title = 'BayTripr - She took you half the way there.'; return 'half'; } else if (rawTrip.firstTrip) { document.title = 'BayTripr - A one way ticket, yeah.'; return 'oneWay'; } else { document.title = 'BayTripr - She\'s a real teaser'; return 'teaser'; } } const d = new Date(); if (d.getDay() === 0) { document.title = 'BayTripr - A Sunday driver, yeah.'; return 'sunday'; } else { document.title = 'BayTripr - Taking the easy way out.'; return 'easy'; } } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; export default class Origin extends Component { constructor(props){ super(props); } render() { const origin = this.props.selected.origin; const stations = this.props.stations; if (stations[origin]) { return ( <div className="content-section-b"> <div className="container"> <div className="row"> <div className="col-lg-5 col-lg-offset-1 col-sm-push-6 col-sm-6"> <hr className="section-heading-spacer" /> <div className="clearfix"></div> <h2 className="section-heading">{stations[origin].title}</h2> <p className="lead">{stations[origin].description}</p> </div> <div className="col-lg-5 col-sm-pull-6 col-sm-6"> <img className="img-responsive" src={stations[origin].img} alt="" /> </div> </div> </div> </div> ) } else { return <div />; } } } function mapStateToProps({ stations, selected }) { return { stations, selected } } export default connect(mapStateToProps)(Origin); <file_sep>import React, { Component } from 'react'; export default class NavButton extends Component { constructor(props) { super(props); } render() { return ( <button type="button" className="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" onClick={this.props.toggleMenu}> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> ) } } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Table } from 'react-bootstrap'; export default class TimeTable extends Component { constructor(props) { super(props); } render() { const tripLegs = this.props.tripText.map(function(tripObj) { return ( <tr key={tripObj.id}> <td>{tripObj.origin}</td> <td>{processTime(tripObj.depTime)}</td> <td>{tripObj.destination}</td> <td>{processTime(tripObj.arrTime)}</td> </tr> ) }) return ( <Table striped bordered condensed hover> <thead> <tr> <th>Departure Station</th> <th>Dept. Time</th> <th>Arrival Station</th> <th>Arr. Time</th> </tr> </thead> <tbody> {tripLegs} </tbody> </Table> ) } } function processTime(time) { var charArray = time.toString().split(''); var truncTime = parseInt(charArray.slice(0, -2).join('')); if (truncTime >= 1300) { var formatTime = (truncTime - 1200).toString().split(''); formatTime.splice(-2, 0, ':'); return `${formatTime.join('')} PM`; } else { var formatTime = truncTime.toString().split(''); formatTime.splice(-2, 0, ':'); return `${formatTime.join('')} AM`; } } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Table } from 'react-bootstrap'; import { stationKey } from '../utilities/tripPlanner.js'; export default class Delays extends Component { constructor(props) { super(props); this.state = { delayText: '' } } componentWillMount() { const trips = this.props.tripText; const trip = trips[0]; this.setState({delayText: `Checking for delays between ${trips[0].origin} and ${trips[trips.length - 1].destination}..`}) fetch(`https://api.bart.gov/api/etd.aspx?cmd=etd&orig=${stationKey[trip.origin]}&key=<KEY>`).then(response => response.text()) .then(function(text) { this.setState({delayText: processBartResp(trip, text)}); }.bind(this)) } componentWillReceiveProps(nextProps) { if (nextProps.tripText[0].origin != this.props.tripText[0].origin && nextProps.tripText[nextProps.tripText.length - 1].destination != this.props.tripText[this.props.tripText.length - 1].destination) { const trip = nextProps.tripText[0]; fetch(`https://api.bart.gov/api/etd.aspx?cmd=etd&orig=${stationKey[trip.origin]}&key=<KEY>`) .then(response => response.text()) .catch(function(ex) { this.setState({delayText: `Couldn't fetch delays from BART server. Check your internet connection.`}) }.bind(this)) .then(function(text) { this.setState({delayText: processBartResp(trip, text)}); }.bind(this)); } } render() { const trips = this.props.tripText; return ( <p>{this.state.delayText}</p> ) } } function processBartResp(trip, text) { // Spaghetti if (text.indexOf('invalid') != -1) { console.log('failed!'); return `Couldn't retreive delay data.`; } else { const dests = text.split('<destination>'); dests.shift(); const rightWay = dests.filter((string) => (string.indexOf(trip.end) != -1)); if (rightWay[0] && rightWay[0].split('<minutes>')[1].split('</minutes>')[0] != 'Leaving') { const minsUntil = parseInt(rightWay[0].split('<minutes>')[1].split('</minutes>')[0]); const now = new Date(); const liveDep = new Date(now.getFullYear(), now.getMonth(), now.getDay(), now.getHours(), (now.getMinutes() + minsUntil)); const depArray = trip.depTime.toString().split(''); const schedDep = new Date(now.getFullYear(), now.getMonth(), now.getDay(), parseInt(depArray.slice(0, -4).join('')), parseInt(depArray.slice(-4, -2).join(''))); const delay = (liveDep.getTime() - schedDep.getTime())/1000/60; if (delay > 0) { return `Next train from ${trip.origin} towards ${trip.end} delayed by ${delay} minute(s).` } else { return `No delays from ${trip.origin} towards ${trip.end}.` } } else { console.log('no delay data found..'); return `No delay data found from ${trip.origin} towards ${trip.end}.` } } } function mapStateToProps({ tripText }) { return { tripText } } export default connect(mapStateToProps)(Delays); <file_sep>import { combineReducers } from 'redux'; import stations from './reducerStations'; import selected from './reducerSelected'; import tripText from './reducerTrip'; import subText from './reducerSubText' const rootReducer = combineReducers({ tripText, stations, selected, subText }); export default rootReducer; <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; export default class Duration extends Component { constructor(props) { super(props); } render() { const travelTime = processTime(this.props.tripText[0].depTime, this.props.tripText[this.props.tripText.length - 1].arrTime) return ( <p>Travel duration: {travelTime} minutes</p> ) } } function processTime(startTime, endTime) { const now = new Date(); const start = new Date(now.getFullYear(), now.getMonth(), now.getDay(), parseInt(startTime.toString().split('').slice(0, -4).join('')), parseInt(startTime.toString().split('').slice(-4, -2).join(''))); const end = new Date(now.getFullYear(), now.getMonth(), now.getDay(), parseInt(endTime.toString().split('').slice(0, -4).join('')), parseInt(endTime.toString().split('').slice(-4, -2).join(''))); return (end.getTime() - start.getTime())/60000; } function mapStateToProps({ tripText }) { return { tripText } } export default connect(mapStateToProps)(Duration); <file_sep>import { dbPromise } from '../utilities/idbAccess.js'; import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { planTrip } from '../actions/index'; import { connect } from 'react-redux'; import { ButtonGroup, Button } from 'react-bootstrap'; export default class tripButtons extends Component { constructor(props) { super(props); this.handleNext = this.handleNext.bind(this); this.handlePrev = this.handlePrev.bind(this); } handleNext(e) { dbPromise.then(function(db) { const tx = db.transaction('bayTripr', 'readwrite'); const bayTripr = tx.objectStore('bayTripr') bayTripr.get('data').then((data) => this.props.planTrip({ origin: this.props.tripText[0].origin, destination: this.props.tripText[this.props.tripText.length - 1].destination, data, time: this.props.tripText[0].depTime })); }.bind(this)); } handlePrev(e) { dbPromise.then(function(db) { const tx = db.transaction('bayTripr', 'readwrite'); const bayTripr = tx.objectStore('bayTripr') const newTime = ((this.props.tripText[0].depTime - 2001) % 10000 > 6000 ? (this.props.tripText[0].depTime - 6001) : (this.props.tripText[0].depTime - 2001)); bayTripr.get('data').then((data) => this.props.planTrip({ origin: this.props.tripText[0].origin, destination: this.props.tripText[this.props.tripText.length - 1].destination, data, time: (newTime) })); }.bind(this)); } render() { return ( <ButtonGroup justified> <ButtonGroup> <Button bsStyle="default" onClick={this.handlePrev}>Earlier Trip</Button> </ButtonGroup> <ButtonGroup> <Button bsStyle="default" onClick={this.handleNext}>Later Trip</Button> </ButtonGroup> </ButtonGroup> ) } } function mapStateToProps({ stations, selected }) { return { stations, selected } } function mapDispatchToProps(dispatch) { return bindActionCreators({ planTrip }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(tripButtons); <file_sep>var fs = require('fs'); var stationKey = { '12TH': '12th St. Oakland City Center', '16TH': '16th St. Mission', '19TH': '19th St. Oakland', '19TH_N': '19th St. Oakland', '24TH': '24th St. Mission', 'ASHB': 'Ashby', 'BALB': 'Balboa Park', 'BAYF': 'Bay Fair', 'CAST': 'Castro Valley', 'CIVC': 'Civic Center/UN Plaza', 'COLS': 'Oakland Coliseum', 'COLM': 'Colma', 'CONC': 'Concord', 'DALY': 'Daly City', 'DBRK': 'Downtown Berkeley', 'DUBL': 'Dublin/Pleasanton', 'DELN': 'El Cerrito del Norte', 'PLZA': 'El Cerrito Plaza', 'EMBR': 'Embarcadero', 'FRMT': 'Fremont', 'FTVL': 'Fruitvale', 'GLEN': 'Glen Park', 'HAYW': 'Hayward', 'LAFY': 'Lafayette', 'LAKE': 'Lake Merritt', 'MCAR': 'MacArthur', 'MCAR_S': 'MacArthur', 'MLBR': 'Millbrae', 'MONT': 'Montgomery St.', 'NBRK': 'North Berkeley', 'NCON': 'North Concord/Martinez', 'OAKL': 'Oakland Airport', 'ORIN': 'Orinda', 'PITT': 'Pittsburg/Bay Point', 'PHIL': 'Pleasant Hill', 'POWL': 'Powell St.', 'RICH': 'Richmond', 'ROCK': 'Rockridge', 'SBRN': 'San Bruno', 'SFIA': 'San Francisco Airport', 'SANL': 'San Leandro', 'SHAY': 'South Hayward', 'SSAN': 'South San Francisco', 'UCTY': 'Union City', 'WCRK': 'Walnut Creek', 'WDUB': 'West Dublin/Pleasanton', 'WOAK': 'West Oakland' } var readable = fs.readFile(`${__dirname}/stop_times.txt`, 'utf8', (err, data) => { if (err) throw err; scrape(data); }) function scrape(rawData) { var data = { trips: {}, stations: {} } var lines = rawData.split('\n'); var importantData = lines.map(function(line) { var split = line.split(','); return { trip: split[0], time: split[1], station: stationKey[split[3]] }; }); importantData.forEach(function(line, index) { if (!data.trips[line.trip]) { data.trips[line.trip] = { days: [false, false, false, false, false, false, false], stations: [line.station] } var lastThree = line.trip.split('').filter((char, index, array) => index >= array.length - 3).join(''); if (lastThree === 'SUN') { data.trips[line.trip].days[0] = true; } else if (lastThree === 'SAT'){ data.trips[line.trip].days[6] = true; } else { data.trips[line.trip].days = [false, true, true, true, true, true, false]; } } else { data.trips[line.trip].stations.push(line.station); } if (!data.stations[line.station]) { data.stations[line.station] = {} data.stations[line.station][line.trip] = line.time; } else { data.stations[line.station][line.trip] = line.time; } }) writeJSON(data); } function writeJSON(data) { fs.writeFile(`${__dirname}/stopData.json`, JSON.stringify(data), function(err){ if (err){ return console.log(err); } console.log(`Wrote file...`); }) } <file_sep>import React, { Component } from 'react'; export default class BurgerMenu extends Component { constructor(props) { super(props); } render() { return ( <div className="burgerMenu" onClick={this.props.toggleMenu}> <ul className="nav navbar-nav navbar-right"> <li> <a href="#schedule">Schedule</a> </li> <li> <a href="#origin">Origin</a> </li> <li> <a href="#destination">Destination</a> </li> </ul> </div> ) } } <file_sep>import { dbPromise } from '../utilities/idbAccess.js'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { setOrigin, setDestination, planTrip } from '../actions/index'; import { Form, FormGroup, FormControl, Button, ControlLabel } from 'react-bootstrap'; import Typeahead from 'react-bootstrap-typeahead'; export default class Input extends Component { constructor(props){ super(props); this.state = { origin: '', destination: '', originText: 'Origin:', destinationText: 'Destination:', originValid: false, destinationValid: false } this.handleSubmit = this.handleSubmit.bind(this); this.originChange = this.originChange.bind(this); this.destinationChange = this.destinationChange.bind(this); } handleSubmit(e) { e.preventDefault(); dbPromise.then(function(db) { const tx = db.transaction('bayTripr', 'readwrite'); const bayTripr = tx.objectStore('bayTripr') bayTripr.get('data').then((data) => this.props.planTrip({ origin: this.state.origin, destination: this.state.destination, data })); }.bind(this)); this.props.setOrigin(this.state.origin); this.props.setDestination(this.state.destination); this.refs.originInput.getInstance().clear(); this.refs.destinationInput.getInstance().clear(); window.location = `${window.location.origin}${window.location.pathname}#schedule`; } originChange(origin) { if (this.props.stations[origin]) { this.setState({...this.state, origin, originText: 'Origin:', originValid: true }) } else { this.setState({...this.state, originText: 'Please enter a valid origin:', originValid: false }) } } destinationChange(destination) { if (this.props.stations[destination]) { this.setState({...this.state, destination, destinationText: 'Destination:', destinationValid: true }) } else { this.setState({...this.state, destinationText: 'Please enter a valid destination:', destinationValid: false }) } } render() { const optionData = Object.keys(this.props.stations).map((key) => this.props.stations[key]); return ( <Form inline> <FormGroup controlId="origin"> <ControlLabel>{this.state.originText}</ControlLabel> {' '} <Typeahead labelKey="title" options={optionData} onInputChange={this.originChange} ref="originInput" /> </FormGroup> {' '} <FormGroup controlId="destination"> <ControlLabel>{this.state.destinationText}</ControlLabel> {' '} <Typeahead labelKey="title" options={optionData} onInputChange={this.destinationChange} ref="destinationInput" /> </FormGroup> {' '} <Button type="submit" onClick={this.handleSubmit} disabled={this.state.originValid && this.state.destinationValid ? false : true}> Go </Button> </Form> ) } } function mapStateToProps({ stations, selected }) { return { stations, selected } } function mapDispatchToProps(dispatch) { return bindActionCreators({ setOrigin, setDestination, planTrip }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Input); <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import Origin from './origin'; import Destination from './destination'; import Input from './input'; import Schedule from './schedule'; import NavButton from './navButton'; import BurgerMenu from './burger'; require("../../css/burgerMenu.scss"); export default class App extends Component { constructor(props) { super(props); this.state = { menuUp: false } this.toggleMenu = this.toggleMenu.bind(this); } toggleMenu() { console.log('User wants to toggle the menu.'); this.setState({menuUp: !this.state.menuUp}); } render() { console.log const subText = function() { switch(this.props.subText) { case 'soLong': return (<h3>It took me so long to find out.<br />And I found out.</h3>); break; case 'half': return (<h3>She took you half the way there.</h3>); break; case 'oneWay': return (<h3>A one way ticket, yeah.</h3>); break; case 'teaser': return (<h3>Shes a real teaser.</h3>); break; case 'sunday': return (<h3>A Sunday driver, yeah.</h3>); break; default: return (<h3>Taking the easy way out.</h3>); } }.bind(this); return ( <div> <nav className="navbar navbar-default navbar-fixed-top topnav" role="navigation"> <div className="container topnav"> <div className="navbar-header"> <NavButton toggleMenu={this.toggleMenu} /> <a className="navbar-brand topnav" href="#">BayTripr</a> </div> <ReactCSSTransitionGroup transitionName='burger' transitionEnterTimeout={300} transitionLeaveTimeout={300}> {this.state.menuUp ? <BurgerMenu toggleMenu={this.toggleMenu} /> : ''} </ReactCSSTransitionGroup> <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul className="nav navbar-nav navbar-right"> <li> <a href="#schedule">Schedule</a> </li> <li> <a href="#origin">Origin</a> </li> <li> <a href="#destination">Destination</a> </li> </ul> </div> </div> </nav> <a name="submit"></a> <div className="intro-header"> <div className="container"> <div className="row"> <div className="col-lg-12"> <div className="intro-message"> <h1>BayTripr</h1> {subText()} <hr className="intro-divider" /> <Input /> </div> </div> </div> </div> </div> <a name="schedule"></a> <Schedule /> <a name="origin"></a> <Origin /> <a name="destination"></a> <Destination /> <footer> <div className="container"> <div className="row"> <div className="col-lg-12"> <ul className="list-inline"> <li> <a href="#submit">Search</a> </li> <li className="footer-menu-divider">&sdot;</li> <li> <a href="#schedule">Schedule</a> </li> <li className="footer-menu-divider">&sdot;</li> <li> <a href="#origin">Origin</a> </li> <li className="footer-menu-divider">&sdot;</li> <li> <a href="#destination">Destination</a> </li> </ul> <p className="copyright text-muted small">Copyright &copy; <a href="http://nicksenger.org"><NAME></a> 2016. All Rights Reserved</p> </div> </div> </div> </footer> </div> ) } } function mapStateToProps({ subText }) { return { subText } } export default connect(mapStateToProps)(App); <file_sep>var path = require('path'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var webpack = require('webpack'); module.exports = { context: __dirname, entry: "./src/js/app.js", resolveLoader: { root: path.resolve(__dirname, 'node_modules') }, output: { path: "./build", filename: "bundle.js" }, module: { loaders: [{ test: /\.js$/, loader: "babel-loader" }, { test: /\.jsx$/, loader: "babel-loader" }, { test: /\.json$/, loader: "json-loader" },{ test: /\.scss$/, loader: ExtractTextPlugin.extract('css!sass') }, { test: /\.css$/, loader: ExtractTextPlugin.extract('css') }, { test: /\.html$/, loader: "raw-loader" }, { test: /\.(eot|svg|ttf|woff|woff2)(\?.*$|$)/, loader: 'file?name=fonts/[name].[ext]' }, { test: /\.(jpg|png|gif)$/, loader: 'file?name=img/[name].[ext]' }] }, plugins: [ new ExtractTextPlugin('bundle.css', { allChunks: true }), new HtmlWebpackPlugin({ hash: true, filename: 'index.html', template: 'src/html/index.html' }) ], watch: true, devServer: { contentBase: 'build', port: 4848 } }; <file_sep>var origin = 'West Oakland'; var destination = 'Walnut Creek'; var fs = require('fs'); var readable = fs.readFile(`${__dirname}/fixedData.json`, 'utf8', (err, data) => { if (err) throw err; var parsed = JSON.parse(data); search(parsed); }) function search(data) { var matching = getMatches(data); var correctDirection = filterDirection(matching, data); var fastest = getFastest(correctDirection, data); var correctTime = filterTimes(fastest, data); correctTime.forEach(function(trip) { console.log(data.stations[origin][trip]) }) } function getMatches(data) { return Object.keys(data.trips).filter(function(key) { if (data.trips[key].stations[origin] && data.trips[key].stations[destination]) { return true; } else { return false; } }) } function filterDirection(array, data) { return array.filter(function(trip) { if (data.trips[trip].stations[destination] - data.trips[trip].stations[origin] > 0) { return true; } else { return false; } }) } function getFastest(array, data) { return array.sort(function(a, b) { var aDist = data.trips[a].stations[destination] - data.trips[a].stations[origin]; var bDist = data.trips[b].stations[destination] - data.trips[b].stations[origin]; return (aDist - bDist); }).filter(function(trip, index, array) { var thisDistance = data.trips[trip].stations[destination] - data.trips[trip].stations[origin]; var closestDistance = data.trips[array[0]].stations[destination] - data.trips[array[0]].stations[origin]; return (thisDistance === closestDistance); }) } function filterTimes(array, data) { var date = new Date(); var day = date.getDay(); var hour = (date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()); var minute = (date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()); var second = (date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()); var time = parseInt(`${hour}${minute}${second}`); return array.filter(function(trip) { return (data.trips[trip]['days'][day]); }).filter(function(trip) { var tripTime = parseInt(data.stations[origin][trip].split(':').join('')); return (tripTime > time); }) } <file_sep># BayTripr BayTripr is a React-Redux application for scheduling trips on the Bay Area Rapid Transit system. *[Sample Deployment](http://nicksenger.github.io/BayTripr/build/index.html)* ![Alt text](/screenshot.jpg?raw=true) *Thank you to Start Bootstrap for Landing-Page CSS Theme, and Wikipedia for city/station descriptions and images!* ##Installation Clone the GitHub repository to a local directory, and install the required dependencies using npm. ``` $ git clone https://github.com/nicksenger/BayTripr.git $ cd BayTripr $ npm install ``` To test the application on localhost, run the 'serve' npm script listed in package.json like so: ``` $ npm run serve ``` You can then navigate to localhost:4848 to view the page locally. ##Getting Started BayTripr is built on [React.js](https://github.com/facebook/react) and [Redux](https://github.com/reactjs/redux), and familiarity with each is recommended in order to understand the app's source code. Each has excellent documentation available, which should be referred to as needed. ###File Structure BayTripr's source code is divided into subdirectories by filetype, and further subdivided based on function. The entrypoint for the app is contained within app.js of the js directory. This file renders the BayTripr React Component to an arbitrary 'container' element of the test-page's index.html, and registers the service worker which allows for caching and offline use. Additional JavaScript files are organized as follows: - **actions**: contains Redux action creators (index.js) - **components**: contains React components - **reducers**: contains Redux reducers - **utilities**: contains service worker and indexedDB management code, and the main logic for scheduling BART trips ###Data Structure Upon initial page-load, the BART schedule is loaded into **indexedDB** via an asynchronous fetch request to *build/theData.json*. The indexedDB data object is a tree containing indices of all data relevant to planning a trip. From the top-down, the data is structured as follows: **Data**: Contains all relevant trip data -**Transfers**: Contains all the timed transfer stations (key = name of station as listed in BART GTFS data) -**Station**: Holds all stations which can be accessed directly from this Transfers -*Station*: Trues if this station can be accessed from parent transfer station -**Trips**: Contains information about each trip (key = name of trip listed in BART GTFS data) -**TripName**: Contains information about a particular trip -*Stations*: Contains all the stations stopped at in a particular trip -*StationName*: Ordered number of stop (0 is the departure station) -*Days*: Days on which this trip operates -**Stations**: Contains information about which trips stop at each station, and at what timed -**StationName**: Holds information about each trip stopping at a particular station -*TripName*: Time that this trip stops at parent station ###Components BayTripr's functionality involves the management of React components with unidirectional state-flow provided by Redux. Styling for the components is provided by either the react-bootstrap library or the Landing-Page Theme located in the CSS directory. The components are: - **App** (*app.js*): Sets up the body of the page and contains other important elements - **BurgerMenu** (*burger.js*): Provides the drop-down menu for page navigation - **Delays** (*delays.js*): Provides the text for any delays and sends the fetch request to the BART api - **Destination** (*destination.js*): Renders the 'destination' section of the page body - **Input** (*input.js*): Renders the input control for planning a new trip. Fires the action which triggers entry into *utilities/tripPlanner.js* - **NavButton** (*navButton.js*): Small navigation button at the top of the page in mobile/tablet view - **Origin** (*origin.js*): Renders the 'origin' section of the page body - **Schedule** (*schedule.js*): Renders the 'schedule' section of the page body. Contains ***Delays***, ***TimeTable*** and ***TripButtons*** - **TimeTable** (*timeTable.js*): Renders the output for the selected trip to a table - **TripButtons** (*tripButtons.js*): Renders and fires actions for the buttons to select later/earlier trips ##Contribution Contributions that address any unresolved issues or provide additional features are encouraged and appreciated! Please indicate what changes are being made in the commit message. ##License BayTripr is copyright (c) 2016, <NAME>. It is distributed under the [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause). <file_sep>import { SET_ORIGIN } from '../actions/index'; import { SET_DESTINATION } from '../actions/index'; export default function (state = {origin: '', destination: ''}, action) { switch(action.type) { case SET_ORIGIN: return {...state, origin: action.payload}; break; case SET_DESTINATION: return {...state, destination: action.payload}; break; } return state; } <file_sep>var fs = require('fs'); var stationKey = { '12TH': '12th St. Oakland City Center', '16TH': '16th St. Mission', '19TH': '19th St. Oakland', '19TH_N': '19th St. Oakland', '24TH': '24th St. Mission', 'ASHB': 'Ashby', 'BALB': 'Balboa Park', 'BAYF': 'Bay Fair', 'CAST': 'Castro Valley', 'CIVC': 'Civic Center/UN Plaza', 'COLS': 'Oakland Coliseum', 'COLM': 'Colma', 'CONC': 'Concord', 'DALY': 'Daly City', 'DBRK': 'Downtown Berkeley', 'DUBL': 'Dublin/Pleasanton', 'DELN': 'El Cerrito del Norte', 'PLZA': 'El Cerrito Plaza', 'EMBR': 'Embarcadero', 'FRMT': 'Fremont', 'FTVL': 'Fruitvale', 'GLEN': 'Glen Park', 'HAYW': 'Hayward', 'LAFY': 'Lafayette', 'LAKE': 'Lake Merritt', 'MCAR': 'MacArthur', 'MCAR_S': 'MacArthur', 'MLBR': 'Millbrae', 'MONT': 'Montgomery St.', 'NBRK': 'North Berkeley', 'NCON': 'North Concord/Martinez', 'OAKL': 'Oakland Airport', 'PITT': 'Pittsburg/Bay Point', 'PHIL': 'Pleasant Hill', 'POWL': 'Powell St.', 'RICH': 'Richmond', 'ROCK': 'Rockridge', 'SBRN': 'San Bruno', 'SFIA': 'San Francisco Airport', 'SANL': 'San Leandro', 'SHAY': 'South Hayward', 'SSAN': 'South San Francisco', 'UCTY': 'Union City', 'WCRK': 'Walnut Creek', 'WDUB': 'West Dublin/Pleasanton', 'WOAK': 'West Oakland' } var transfers = ['MacArthur', 'West Oakland', 'Balboa Park']; var readable = fs.readFile(`${__dirname}/fixedData.json`, 'utf8', (err, data) => { if (err) throw err; var parse = JSON.parse(data); populateTransfers(parse); }) function populateTransfers(data) { var newData = data; Object.keys(stationKey).forEach(function(key) { var station = stationKey[key]; transfers.forEach(function(transfer) { if (getMatches(station, transfer, data).length > 0) { newData.transfers[transfer][station] = true; } }) }) writeJSON(newData); } function getMatches(origin, destination, data) { return Object.keys(data.trips).filter(function(key) { if (data.trips[key].stations[origin] && data.trips[key].stations[destination]) { return true; } else { return false; } }) } function writeJSON(data) { fs.writeFile(`${__dirname}/theData.json`, JSON.stringify(data), function(err){ if (err){ return console.log(err); } console.log(`Wrote file...`); }) }
3ad4e9a3d00a89f36ac2b8a5176ae4da51b734ad
[ "JavaScript", "Markdown" ]
18
JavaScript
nicksenger/BayTripr
811307b079b1a65807e1eb38718acb565b6580a0
70b207eada93057f9494700b969d197a25c4a4c5
refs/heads/master
<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "08d42adcbe44caf6e4ca9911d76c5cef", "url": "/index.html" }, { "revision": "a250ca3dabd16dcd4000", "url": "/static/css/main.ec75d18e.chunk.css" }, { "revision": "19a02f0edfd296cac57c", "url": "/static/js/2.0c67da29.chunk.js" }, { "revision": "e88a3e95b5364d46e95b35ae8c0dc27d", "url": "/static/js/2.0c67da29.chunk.js.LICENSE.txt" }, { "revision": "a250ca3dabd16dcd4000", "url": "/static/js/main.1ab6f2d0.chunk.js" }, { "revision": "5f8f0ca89b8f7bf10db3", "url": "/static/js/runtime-main.d5ba2b5d.js" } ]);
92cc9b82e009a3c16999bbce2e03f67580cc1ae7
[ "JavaScript" ]
1
JavaScript
dev-athul/Quiz-App-Build
1d58918ca20b1cd7ee09f768447ad3bb8c909b13
8e280e3c5b4709fb34b2da77cc535d0fcf2b2e0b
refs/heads/master
<repo_name>marboga/mean1<file_sep>/client/js/controllers/questionsController.js console.log('in qs controller') survey_app.controller('questionsController', function($scope, pollFactory, loginFactory){ $scope.thisQuestion = {}; $scope.user = {}; function getUser(){ loginFactory.getUser(function(data){ $scope.user = data; console.log("current user is", $scope.user.name) }) } getUser(); $scope.getOneQ = function(poll){ pollFactory.get_q(poll, function(poll){ $scope.thisques = pollFactory.poll; console.log(pollFactory.poll, "^^^^^^^") }) } $scope.doVote = function(option){ console.log("vote controller, option=", option); pollFactory.update(option, function(option, pollFactory){ }) } }) <file_sep>/server/controllers/polls.js console.log('in controllers/polls.js') var mongoose = require('mongoose') var Poll = mongoose.model('Poll'); module.exports = { get_all: function(req, res){ Poll.find({}, function(err, polls){ if (err){ res.json(err) }else{ // Poll.populate(polls._user).exec(function(err, question){ // if (err){ // res.json(err) // }else{ res.json(polls) // } // }) } }) }, create: function(req, res){ console.log('data passed to server poll create function', req.body); var poll = new Poll(req.body); poll.save(function(err){ if (err){ console.log(err) res.json(err) }else{ res.redirect('/polls') } }) }, get_one: function(req, res){ console.log('made it to get one function, id=', req.params.id) Poll.findOne({_id: req.params.id}, function(err, question){ if (err){ console.log(err) }else{ console.log("successfully retrieved from db. question=", question) // Poll.populate(_user).exec(function(err, question){ // if (err){ // res.json(err) // }else{ // console.log('the creator is %s', Poll._user.name) res.json(question) // } // }) } }) }, remove_one: function(req, res){ Poll.findOneAndRemove({_id: req.params.id}, function(err){ if(err){ console.log(err) }else{ res.redirect('/polls') } }) }, update: function(req, res){ console.log('in db controller. ', req.params.option) if (req.params.option == 'option1'){ Poll.findOneAndUpdate({_id: req.params.id}, {$inc: {option1votes: +1}}, function(err, data){ if (err){ res.json(err) }else{ res.json(data) } }) } else if(req.params.option == 'option2'){ Poll.findOneAndUpdate({_id: req.params.id}, {$inc: {option2votes: +1}}, function(err, data){ if (err){ res.json(err) }else{ res.json(data) } }) } else if(req.params.option == 'option3'){ Poll.findOneAndUpdate({_id: req.params.id}, {$inc: {option3votes: +1}}, function(err, data){ if (err){ res.json(err) }else{ res.json(data) } }) } else if(req.params.option == 'option4'){ Poll.findOneAndUpdate({_id: req.params.id}, {$inc: {option4votes: +1}}, function(err, data){ if (err){ res.json(err) }else{ res.json(data) } }) } else{ res.json(err); } }, } <file_sep>/client/js/config/app.js var survey_app = angular.module('survey_app', ['ngRoute']); survey_app.constant('moment', moment) <file_sep>/server/models/poll.js console.log('in server poll model'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var PollSchema = new mongoose.Schema({ name: {type: String}, _user: {type: Schema.Types.ObjectId, ref: 'User'}, question: {type: String, required: true}, option1: {type: String, required: true}, option1votes: {type: Number, default: 0}, option2: {type: String, required: true}, option2votes: {type: Number, default: 0}, option3: {type: String, required: true}, option3votes: {type: Number, default: 0}, option4: {type: String, required: true}, option4votes: {type: Number, default: 0}, },{timestamps: true}) mongoose.model('Poll', PollSchema); <file_sep>/client/js/controllers/pollsController.js survey_app.controller('pollsController', function($scope, pollFactory, loginFactory, moment, $location){ console.log('loading controller') $scope.polls = []; $scope.user = {}; $scope.thisques = pollFactory.poll; $scope.options = pollFactory.options; function index(){ pollFactory.index(function(data){ $scope.polls = data }) } index(); function getUser(){ loginFactory.getUser(function(data){ $scope.user = data; console.log("current user==", $scope.user.name) }) } getUser(); $scope.makePoll = function(){ console.log($scope.new_poll, "new poll 'ere") console.log("SCOPE USER",$scope.user.name) $scope.new_poll._user = $scope.user._id; $scope.new_poll.name = $scope.user.name; pollFactory.create($scope.new_poll, function($scope, pollFactory){ // if(err){ // res.json(err) // $location.url('/new'); // }else{ $scope.new_poll = {} $location.url('/polls'); // } }) } $scope.removePoll = function(poll){ console.log('trying to remove', poll); pollFactory.delete(poll, function(poll, pollFactory){ }) index(); } $scope.getOneQ = function(poll){ pollFactory.get_q(poll, function(poll){ $location.url('/poll/'+poll) $scope.thisques = pollFactory.poll; $scope.options = pollFactory.options console.log(pollFactory.poll, pollFactory.options, "^^^^^^^") }) } $scope.addLike = function(option){ console.log("vote controller, option=", option); pollFactory.update(option, function(option, pollFactory){ $scope.getOneQ(option) }) } $scope.logout = function(){ loginFactory.user = "" $scope.user = {}; $location.url('/') loginFactory.logout() } })
09edebf75857fe4555f6b241a58062a7fc7091b6
[ "JavaScript" ]
5
JavaScript
marboga/mean1
98395b4e826220cc820843746d94274d7e4ffc6d
27180257d12f75bc515ab68a01e336a99f9912fe
refs/heads/master
<file_sep>import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Helper { public static void printDisplay() throws IOException { BufferedReader iStream = new BufferedReader(new FileReader("input.txt")); String string = new String(); for(int i = 0; i < 11; i++) { string = iStream.readLine(); if (i == 11) { System.out.print(string+" "); break; } System.out.println(string); } iStream.close(); } }
9cf58cdf22d4bf1a41649e57010ad696f48d44d0
[ "Java" ]
1
Java
acoehu/BankAccount
08c1f701625e028acddaa0e537af5168d2cd1acc
0a8ed562d21bbc5a4a01164935dc9e8fd3971ceb
refs/heads/main
<repo_name>ookyawsoe-dev/Brick-Ball-Out-Game<file_sep>/Main.java package Game; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.JFrame; public class Main { public Clip audioClip = null; public static Clip clip = null; // public Clip ballClip = null; // public static Clip bClip = null; public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException { JFrame obj = new JFrame(); Gameplay gamePlay = new Gameplay(); obj.setBounds(10, 10, 700, 600); obj.setTitle("Brick Breaker Game! Developed by Mr.<NAME>"); obj.setResizable(false); obj.setLocation(200, 50); obj.setVisible(true); obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); obj.add(gamePlay); obj.setVisible(true); Main main = new Main(); main.audio(); //main.ballSound(); //bClip.stop(); clip.stop(); } public void audio() throws IOException { String name = "src/banana.wav"; try { clip = AudioSystem.getClip(); this.audioClip = clip; AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File((name))); File file = new File(name); inputStream = AudioSystem.getAudioInputStream(file); clip = AudioSystem.getClip(); clip.open(inputStream); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (Exception e) { //System.out.println("Error: Can't locate sound."); e.printStackTrace(); } } // public void ballSound() { // String name = "src/sms_bells_tone.wav"; // try { // bClip = AudioSystem.getClip(); // this.ballClip = bClip; // AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File((name))); // File file = new File(name); // inputStream = AudioSystem.getAudioInputStream(file); // bClip = AudioSystem.getClip(); // bClip.open(inputStream); // clip.loop(Clip.LOOP_CONTINUOUSLY); // // } catch (Exception e) { // //System.out.println("Error: Can't locate sound."); // e.printStackTrace(); // } // } } <file_sep>/README.md # Brick-Ball-Out-Game GUIDE FOR PLAYINIG GAME: 1. Press Enter Key or Left or Right Key to start game. 2. Use left and Right Key to move bottom button as you need to hit ball.
48c3c6343ae402ddfbc33f274d4687e2e8da24dc
[ "Markdown", "Java" ]
2
Java
ookyawsoe-dev/Brick-Ball-Out-Game
ce36086bf4fe308a5b943a3882573d79ec072ca8
a8495bf4f8821f9da80c9a345277438bb701893e
refs/heads/master
<file_sep>'use strict'; var express = require('express'), bodyParser = require('body-parser'), config = require('./app/config'), mongoose = require('mongoose'), db = mongoose.connect(config.mongo.getUri(), config.mongo.options), app = express(), router = express.Router(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); // mongo connection db.connection.on('error', function (err) { console.error('MongoDB: connection error: %s', err.message); }); db.connection.once('open', function () { console.info('MongoDB: connected to "%s"', db.connection.name); }); require('./app/routes')(router, app); // some additional test app.listen(config.port, config.host, function () { console.info('Express server listening on %s:%d, in mode: %s', config.host, config.port, app.get('env')); });
840bc99411db7737f06f91c7f3bc3fee594f709e
[ "JavaScript" ]
1
JavaScript
boomde/mean-test-app
a81b9d716032dbb7cf72e26df00d3b0ef751a18d
2932c20141e8ee56003e1d68174e14663a0106fc
refs/heads/master
<file_sep>(function () { angular.module('ivanyushev') .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $stateProvider .state('main', { url: '/Main', templateUrl: 'Pages/mainPage.html', }) .state('about', { url: '/About', templateUrl: 'Pages/aboutPage.html', }) .state('specialization', { url: '/Specialization', templateUrl: 'Pages/specializationPage.html', }) .state('familyLaw', { url: '/Specialization/Family', templateUrl: 'Pages/familyLaw.html', }) .state('housingLaw', { url: '/Specialization/Housing', templateUrl: 'Pages/housingLaw.html', }) .state('laborLaw', { url: '/Specialization/Labor', templateUrl: 'Pages/laborLaw.html', }) .state('landLaw', { url: '/Specialization/Land', templateUrl: 'Pages/landLaw.html', }) .state('debtCollection', { url: '/Specialization/Debt', templateUrl: 'Pages/debtCollection.html', }) .state('succession', { url: '/Specialization/Succession', templateUrl: 'Pages/succession.html', }) .state('contractLaw', { url: '/Specialization/Contract', templateUrl: 'Pages/contractLaw.html', }) .state('services', { url: '/Services', templateUrl: 'Pages/servicesPage.html', }) .state('cost', { url: '/Cost', templateUrl: 'Pages/costPage.html', }) .state('info', { url: '/Info', templateUrl: 'Pages/infoPage.html', }) .state('contacts', { url: '/Contacts', templateUrl: 'Pages/contactsPage.html', controller: 'ContactsCtrl' }) .state('feedback', { url: '/Feedback', templateUrl: 'Pages/feedback.html', controller: 'FeedbackCtrl' }) $urlRouterProvider.otherwise('/Main'); }]) .config(["$locationProvider", function ($locationProvider) { $locationProvider.html5Mode(true); }]); }()); <file_sep><div class="container-fluid"> <div class="page-title ">Адвокат по договорному праву</div> <b>Профессиональное разрешение проблем в следующих областях:</b> <ul> <li>подготовка пакета документов для совершения сделки/li> <li>правовой анализ договоров, контрактов, соглашений</li> <li>представительство при заключении договора</li> <li>изменение договора</li> <li>расторжение договора</li> <li>переход прав кредитора к другому лицу</li> <li>перевод долга</li> <li>правовая помощь в привлечении к ответственности за нарушение обязательств</li> </ul> </div> <file_sep><div class="container-fluid"> <div class="page-title ">Адвокат по земельному праву</div> <b>Профессиональное разрешение проблем в следующих областях:</b> <ul> <li>правовая поддержка при совершении сделок с земельными участками и правами на них/li> <li>недействительность сделок с земельными участками и правами на них</li> <li>служебный земельный надел</li> <li>проблемные вопросы установления (восстановления) и закрепления границ земельного участка</li> <li>защита права собственности на землю</li> <li>защита прав землепользователей</li> <li>пожизненное наследуемое владение земельными участками</li> <li>постоянное пользование земельными участками</li> <li>временное пользование земельными участками</li> <li>аренда земельных участков</li> <li>ограничения (обременения) прав на земельные участки</li> <li>земельный сервитут</li> <li>проблемные вопросы предоставления земельных участков, находящихся в государственной собственности</li> <li>изъятие земельных участков</li> <li>представительство в земельных спорах</li> </ul> </div> <file_sep>using System; using System.Collections.Generic; using System.Net; using System.Net.Mail; using System.Web.Http; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; using MailMessage = System.Net.Mail.MailMessage; namespace Ivanushev.net.App.Controllers { public class DefaultController : ApiController { public IHttpActionResult PostMessage(Message message) { if (message == null) return BadRequest(); if (!ModelState.IsValid) return BadRequest(); const string secret = "<KEY>"; var client = new WebClient(); var reply = client.DownloadString( string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, message.Response)); var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply); if (!captchaResponse.Success) { if (captchaResponse.ErrorCodes.Count <= 0) return BadRequest(); var error = captchaResponse.ErrorCodes[0].ToLower(); switch (error) { case ("missing-input-secret"): return BadRequest("The secret parameter is missing."); case ("invalid-input-secret"): return BadRequest("The secret parameter is invalid or malformed."); case ("missing-input-response"): return BadRequest("The response parameter is missing."); case ("invalid-input-response"): return BadRequest("The response parameter is invalid or malformed."); default: return BadRequest("Error occured. Please try again"); } } var fromAddress = new MailAddress("<EMAIL>"); var fromPassword = "<PASSWORD>"; //var toAddress = new MailAddress("<EMAIL>"); var toAddress = new MailAddress("<EMAIL>"); var subject = "Сообщение c моего сайта"; try { SmtpClient smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var mes = new MailMessage(fromAddress, toAddress) { Subject = subject, IsBodyHtml = true, Body = "<b>Отправитель: </b>" + message.FullName + "<br/>" + "<b>E-mail: </b>" + message.Email + "<br/>" + "<b>Phone: </b>" + message.Phone + "<br/>" + "<b>Cодержание: </b>" + message.Content }) smtp.Send(mes); } catch (Exception ex) { return BadRequest(ex.Message); } return Ok(); } } public class CaptchaResponse { [JsonProperty("success")] public bool Success { get; set; } [JsonProperty("error-codes")] public List<string> ErrorCodes { get; set; } } public class Message { [Required] [MaxLength(30)] public string FullName { get; set; } [MaxLength(50)] public string Email { get; set; } [Required] [MaxLength(50)] public string Phone { get; set; } [Required] [MaxLength(1000)] public string Content { get; set; } [Required] public string Response { get; set; } } } <file_sep>(function () { angular.module('ivanyushev', ['ui.router', 'vcRecaptcha', 'angularSpinner']); }()); <file_sep>(function () { angular.module('ivanyushev') .controller('Main', ['$scope', 'feedbackServ', '$timeout', '$state', function ($scope, feedbackServ, $timeout, $state) { $scope.state = $state; $scope.$root.isPopUpVisible = false; $scope.$root.isCloudVisible = false; $scope.$root.isSpinerVisible = false; }]) .controller('ContactsCtrl', ['$scope', function ($scope) { function initialize() { var myLatLng = { lat: 53.904957, lng: 27.579705 }; var map = new google.maps.Map(document.getElementById('map'), { zoom: 14, center: myLatLng }); var marker = new google.maps.Marker({ position: myLatLng, map: map, title: '' }); } initialize(); }]) .controller('FeedbackCtrl', ['$scope', 'feedbackServ', '$window', function ($scope, feedbackServ, $window) { $scope.$root.captchaResolved = true; $scope.reCaptchaResponse = ""; function onloadCallback() { grecaptcha.render($('.g-recaptcha')[0], { 'sitekey': '<KEY>' }); } if (typeof grecaptcha === 'undefined') { $window.location.href = '/index.html'; } else { onloadCallback(); } function getResponseIndex() { var i = 0; var expression; while (true) { if (i === 0) { expression = $('#g-recaptcha-response')[0]; } else { expression = $('#g-recaptcha-response-' + i)[0]; } var resp = expression if (resp !== undefined) { return i; } else { i++; } } } $scope.sendFeedbackForm = function (feedback) { $scope.feedbackForm.submitted = false; if ($scope.feedbackForm.$invalid) { $scope.feedbackForm.submitted = true; } else { var responseIndex = getResponseIndex(); if (responseIndex === 0) { responseIndex = undefined; } if (grecaptcha.getResponse(responseIndex) === "") { $scope.$root.captchaResolved = false; //$timeout(function () { // $scope.$root.captchaResolved = true; //}, 5000); } else { $scope.$root.isSpinerVisible = true; window.scrollTo(0, 0); feedbackServ .sendFeedback(feedback, responseIndex) .then(function () { $scope.$root.captchaResolved = true; $scope.$root.isCloudVisible = true; $scope.$root.isPopUpVisible = true; $scope.feedback = null; grecaptcha.reset(responseIndex); $scope.$root.isSpinerVisible = false; }); } } }; $scope.closePopup = function () { $scope.$root.isPopUpVisible = false; $scope.$root.isCloudVisible = false; } var $popup = $('.popUp'); $(document).mouseup(function (e) { if ($popup && $popup.length) { var container = $popup; if (!container.is(e.target) && container.has(e.target).length === 0) { if ($scope.$root) { $scope.$root.isPopUpVisible = false; $scope.$root.isCloudVisible = false; $scope.$apply(); } } } }); }]); angular.module('ivanyushev') .service('feedbackServ', ['$http', 'vcRecaptchaService', function ($http, vcRecaptchaService) { var self = this; self.sendFeedback = function (feedback, responseIndex) { var postData = { 'FullName': feedback.FullName, 'Email': feedback.Email, 'Phone': feedback.Phone, 'Content': feedback.Content, 'Response': grecaptcha.getResponse(responseIndex) } return $http .post('/api/Default', postData) .then(function (response) { $(".success-message").removeClass("hidden"); $(".error-message").addClass("hidden"); return response; }).catch(function (e) { $(".success-message").addClass("hidden"); $(".error-message").removeClass("hidden"); }); } }]); angular.module('ivanyushev') .directive('usSpinner', ['$http', '$rootScope', function ($http, $rootScope) { return { link: function (scope, elm, attrs) { $rootScope.spinnerActive = false; scope.isLoading = function () { return $http.pendingRequests.length > 0; }; scope.$watch(scope.isLoading, function (loading) { $rootScope.spinnerActive = loading; if (loading) { elm.removeClass('ng-hide'); } else { elm.addClass('ng-hide'); } }); } }; }]); }());
f7287fed1b863e885da9eb48bdc02c85fe3d4ec9
[ "JavaScript", "C#", "HTML" ]
6
JavaScript
mishabarabolkin/ivanishev
3a554ff1d732bfcd2df0b0ebaeeadc23a60cbe6a
56132efd5afe861f0001d9c9ed3b97da7f783f30
refs/heads/master
<repo_name>Lamz0rNewb/git-multisig<file_sep>/main.py # Copyright 2015 dc-tcs # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import subprocess import os import json from decimal import Decimal import chainutils as nbtutil import sync import argparse import config parser = argparse.ArgumentParser(description="A tool to use git repositories to do multisig") parser.add_argument("--init", action="store_true") parser.add_argument("--sync", action="store_true") parser.add_argument("--nogit", action="store_true") parser.add_argument("--recipient", type=str, action="store") parser.add_argument("--amount", type=str, action="store") parser.add_argument("--burn", type=str, action="store") cli_args = parser.parse_args() def sign_and_push(raw_tx, my_addr, list_signed): #TODO s = sign_raw_transaction(raw_tx) if s: git_folder = os.path.join('.', my_git) tx_path = os.path.join('.', my_git, my_addr,'tx') with open(tx_path,'w') as f: f.writeline(s) for p in list_signed: f.writeline(p) f.writeline(my_id) git_update(git_folder) if config.GIT_ENABLED and not os.path.exists(config.DATA_DIR): subprocess.call(['git','clone',config.MY_GIT, config.DATA_DIR) a = sync.AddressSnapshot(config.ADDRESS, config.ADDRESSES) print "Updating address snapshot..." if a.sync_with_blockchain(): sync.write_snapshot(a) else: print "Blockchain sync failed. Going online..." b = a b.load_from_url() if b.last_block > a.last_block: a = b else: print "Remote snapshots not newer. Not updating." #if a.load_from_url(): # sync.write_snapshot(a) #print "Checking other channels..." #sync_multiple(a) print "Done.\n" if cli_args.amount and cli_args.recipient: print "This is your transaction hex:" print nbtutil.create_raw_transaction(cli_args.amount, a, cli_args.recipient) else: print "Please specify recipient and amount!" <file_sep>/pubconfig.py import os #ADDRESS: Multisig address #ADDRESSESS: Constituents of the Multisig address #These scripts can only track 1 address for now ADDRESS = "BqyRzFtWXDmjxrYpyJD42MLE5xc8FrB4js" ADDRESSES = set(["B<KEY>NtkvN". "BK<KEY>",\ "<KEY>sZXJ<KEY>s", "<KEY>", "<KEY>"]) PUBKEYS = ["034b0bd0f653d4ac0a2e9e81eb1863bb8e5743f6cb1ea40d845b939c225a1a80ff","02a144af74d018501f03d76ead130433335f969772792ec39ce389c8a234155259","03661a4370dfcfbcea25d1800057220f4572b6eecab95bb0670e8676a9e34451dc","<KEY>","02547427fc2ea3a0ab9ef70f5e1640ff5112b113f65696948f992bd0770b942571"] SIGN_THRESHOLD = 3 #URLs of folders from which to download address snapshots (spendable outputs etc) #Format should be like this: #REFERENCE_URLS = {"foo" : "https://bar", "foo2" : "https://bar2", "foo3" : "https://bar3"} REFERENCE_URLS = {"dc-tcs" : "https://raw.githubusercontent.com/dc-tcs/flot-operations/master", "jooize" : "https://raw.githubusercontent.com/jooize/flot-operations/master"} <file_sep>/config-example.py import os from pubconfig import * DATA_DIR = os.path.join(".","flot-operations") GIT_ENABLED = 0 #This is only used with GIT_ENABLED = 1 MY_GIT = "<EMAIL>:dc-tcs/flot-operations" #How others will identify you. Not used yet. MY_ID = "dc-tcs" #SET RPC port RPC_PORT = 14002 #TEST_RPC_PORT = 15002 #defaults: 14002 for NBT (mainnet) # 15002 for NBT (testnet) RPC_USERNAME = "nurpc" RPC_PASSWORD = "" <file_sep>/chainutils.py # Copyright 2015 dc-tcs # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import subprocess import os import json from decimal import Decimal import math import config import jsonrpc rpc_server = jsonrpc.ServiceProxy("http://" + config.RPC_USERNAME + ":" +\ config.RPC_PASSWORD + "@127.0.0.1:" + str(config.RPC_PORT)) try: s = rpc_server.addmultisigaddress(config.SIGN_THRESHOLD, config.PUBKEYS) if s == config.ADDRESS: print "Multisig address seems valid." else: print "Address does not match given public keys (note that order matters)" except: print "Error verifying multisig address!" #rpc_server.addmultisigaddress(config.SIGN_THRESHOLD, json.dumps(list(config.PUBKEYS))) def NBTJSONtoAmount(value): return Decimal(round(value * 10000))/Decimal(10000) class RPCCaller: #Deprecated? def __init__(self, param = 'nud', mode = 0): if mode == 0: self.nudpath = param self.mode = mode def __call__(self, args): if self.mode == 0: args = [str(arg) for arg in args] call_args = [self.nudpath] + args return subprocess.check_output(call_args) else: #TODO: use rpc port etc. return None class BlockchainStream: def __init__(self, start_height, monitor): self.height = start_height try: self.current_block = rpc_server.getblockhash(int(start_height)) except: self.current_block = None self.monitor = monitor def advance(self): if self.current_block: rpc_server.getblock(self.current_block) s_json = rpc_server.getblock(self.current_block) self.current_block = s_json.get(u'nextblockhash') if self.current_block: self.height += 1 return self.monitor(s_json) else: return None class UnspentMonitor: def __init__(self, address, addresses): self.address = address self.addresses = addresses def __call__(self, s_json): flag_changes = 0 unspent_minus = set() unspent_plus = set() for txid in s_json[u'tx']: t_json = rpc_server.getrawtransaction(txid, 1) if t_json[u'unit'] == u'B': #Remove used inputs: for vi_json in t_json.get(u'vin'): vin_txid = vi_json.get(u'txid') vin_tx_voutn = int(vi_json.get(u'vout')) if not vin_txid == '0000000000000000000000000000000000000000000000000000000000000000': vin_tx_json = rpc_server.getrawtransaction(vin_txid, 1) for vo_json in vin_tx_json.get(u'vout'): spk_json = vo_json.get(u'scriptPubKey') #if (vin_txid == u"b73c15c622c515c1e0bdf8d1609e5f7a9e44ce3f1930759fe1716a0687ca1237"): # print spk_json # print set(spk_json.get(u'addresses')) vout_n = int(vo_json.get(u'n')) if vout_n == vin_tx_voutn: try: vout_addresses = set(spk_json.get(u'addresses')) except: vout_addresses = set([spk_json.get(u'unparkaddress')]) if vout_addresses == self.addresses \ or vout_addresses == set([self.address]): #TODO: check actual specification of "addresses" amount = NBTJSONtoAmount(vo_json.get(u'value')) unspent_minus.add((vin_txid, amount, vout_n)) #Add new outputs: for vo_json in t_json.get(u'vout'): spk_json = vo_json.get(u'scriptPubKey') vout_addresses = set(spk_json.get(u'addresses')) if vout_addresses == self.addresses \ or vout_addresses == set([self.address]): amount = NBTJSONtoAmount(vo_json.get(u'value')) vout_n = int(vo_json.get(u'n')) unspent_plus.add((txid, amount, vout_n)) return (unspent_minus, unspent_plus) def getkbfee(): #TODO: call getfee rpc when 2.1 is ready return Decimal("0.01") def getnkb(n_vins): #overestimate number of bytes of transaction n_bytes = 126 + 44 * (n_vins-1) + 80 * config.SIGN_THRESHOLD + len(config.PUBKEYS) * 34 return int(math.ceil(n_bytes/1024)/2) def create_raw_transaction(amount, address_info, recipient): #amount should be a string or Decimal kbfee = getkbfee() #fee per byte kbsize = 1 fee = getkbfee() amount = Decimal(amount) while 1: unspent_list = sorted(address_info.unspent, key=lambda x: x[1]) my_sum = Decimal(0) i = 0 while my_sum < amount + fee and i < len(unspent_list): my_sum += unspent_list[i][1] i += 1 if my_sum < amount + fee: print "Error: Send amount exceeds balance." return None elif kbsize < getnkb(i): kbsize = getnkb(i) fee = kbsize * getnkb(i) else: fee = kbsize * getnkb(i) break unspent_list = unspent_list[0:i] if unspent_list: s = unspent_list[0] st = "[{\"txid\":\"" + s[0] + "\",\"vout\": " + str(s[2]) + "}" for s in unspent_list[1:]: st = st + ",{\"txid\":\"" + s[0] + "\",\"vout\":" + str(s[2]) + "}" st = st + "]" sr = "{\"" + recipient +"\":" + str(amount) + ",\"" + address_info.address + "\":" + str(my_sum - fee - amount) + "}" try: tx_hex = rpc_server.createrawtransaction(json.loads(st),json.loads(sr)) return rpc_server.createrawtransaction(json.loads(st),json.loads(sr)) except: #print "nud -unit=B createrawtransaction " + st + " " + sr return None else: return None def decode_raw_transaction(hexstring): try: s_json = rpc_server.decoderawtransaction(hexstring) except: return None
20502a4ee681137b4d585a9c10ac10ece23e70ef
[ "Python" ]
4
Python
Lamz0rNewb/git-multisig
d4507d551f2c83b54c469e0d7b58e3822ef358d6
088bbd562d3e99d14e0928bb65c5aa2ac17015a7
refs/heads/master
<file_sep>var events = require('events'); var myEmit = new events.EventEmitter(); myEmit.on('some_event', function(txt) { console.log(txt); }); myEmit.emit('some_event', 'Обработчик событий сработал'); <file_sep> console.log("SMTH");
c0f2ade5a9e7795a6a41f637f751c533ec76e7b7
[ "JavaScript" ]
2
JavaScript
fafnircheg/helloworld
f4037b1292c63dcc6e8f95666cc1b29eab03fc4f
5cc8124fbb29a6e5419c397366888896e9e3cda5
refs/heads/main
<repo_name>devneagu/Blog<file_sep>/src/blog/second-post.md --- title: Second author: Nikola date: 2020-07-15 --- ## Introduction to my blog post Great content of my first blog <file_sep>/src/pages/index.js import React from "react" import { graphql } from "gatsby" export default function Home({ data }) { const { title, description } = data.site.siteMetadata return ( <div> <h1>{title}</h1> <p>{description}</p> <img alt="Cute dog" src={data.image.publicURL} /> </div> ) } export const pageQuery = graphql` query MetadataQuery { site { siteMetadata { title description } } image: file(base: { eq: "cute-dog.png" }) { publicURL } } `
ee170aa472173e9b48606b051d973dcad9659672
[ "Markdown", "JavaScript" ]
2
Markdown
devneagu/Blog
d8f94e6c8ac2633d34ee90fe3ff22662e314915d
b443d61f468e4314a8331639bf02cf89c26c3330
refs/heads/master
<repo_name>Elektropepi/newsR<file_sep>/client/src/article/Content.ts export class Content { public readonly citationLevel: number; public readonly text: string; private static readonly citationRegex: RegExp[] = [ new RegExp(/am(.*?)schrieb.*/, "i"), new RegExp(/on(.*?)wrote.*/, "i") ]; constructor(text: string, citationLevel: number) { this.citationLevel = citationLevel; this.text = text; } public isCitationStart(): boolean { return this.citationLevel === 0 && Content.isCitationStart(this.text); } private static isCitationStart(text: string): boolean { return this.citationRegex.find((regexp: RegExp) => regexp.test(text)) !== undefined; } } <file_sep>/client/src/author/Author.ts export interface AuthorInterface { name: string, email: string } export class Author implements AuthorInterface { public readonly name: string; public readonly email: string; constructor(name: string, email: string) { this.name = name; this.email = email; } public static authorFromString(nameEmail: string) { const nameEmailRegexp = new RegExp('(.*?) <(.*?)>'); const nameEmailResult = nameEmailRegexp.exec(nameEmail); let name: string; let email: string; if (nameEmailResult === null) { name = nameEmail; email = "<EMAIL>"; } else { name = nameEmailResult[1]; email = nameEmailResult[2]; } return new Author(name, email); } public toString(): string { return `${this.name} <${this.email}>`; } } <file_sep>/client/src/emailjs-mime-codec.d.ts declare module 'emailjs-mime-codec'; <file_sep>/client/src/article/Attachment.ts export interface Attachment { contentType: string; dataUrl: string; name: string; } <file_sep>/client/src/template/Constants.ts export const SMALL_SCREEN_QUERY = "(max-width: 47rem)"; export const LARGE_SCREEN_QUERY = "(min-width: 47.1rem)"; <file_sep>/client/src/server/Server.ts import Newsie, {Command, Options as NewsieOptions} from 'newsie'; import {Group, GroupInterface} from "../group/Group"; interface ResponseHandler { callback: Function resolve: Function reject: Function } class WsConnection { private readonly _socket: WebSocket; private readonly _host: string; private readonly _port: number; private _queue: ResponseHandler[]; private onCloseCallback: any; // todo: type tlsOptions: TlsOptions constructor(host: string, port: number, tlsPort: boolean, tlsOptions: any) { // todo: not sure if this should be here or in .connect() if(!process.env.REACT_APP_WS_TO_NNTP_URL) { throw Error("WS_TO_NNTP_URL is not defined!"); } this._socket = new WebSocket(process.env.REACT_APP_WS_TO_NNTP_URL); this._host = host; this._port = port; this._queue = []; } public connect = async (): Promise<WebSocket> => { return new Promise((resolve) => { this._socket.addEventListener('open', () => { this.write(`NNTPCONNECT ${this._host} ${this._port}`); this._addSocketHandlers(); //return this._tlsPort ? this.upgradeTls() : Promise.resolve(this._socket); resolve(this._socket); }); }); }; public disconnect = () => { // Close connection this._socket.close(); //this._socket.removeAllListeners(); //this._socket.unref(); //if (this._tlsPromiseReject) { // this._tlsPromiseReject(); //} // Empty the queue this._queue.forEach(h => h.reject(new Error('Disconnected from server'))); this._queue = []; }; public write = (str: string): void => { this._socket.send(str); }; public addCallback = (callback: Function, resolve: Function, reject: Function) => { this._queue.push({callback, resolve, reject}) }; public setOnCloseCallback(callback: any) { this.onCloseCallback = callback; }; private _addSocketHandlers = (): void => { this._socket.onmessage = (event) => { const responseHandler = this._queue[0]; let response = responseHandler.callback(event.data); this._queue.shift(); responseHandler.resolve(response); }; this._socket.onerror = err => { this._queue.forEach(h => h.reject(err)); this.disconnect(); throw err; }; this._socket.onclose = () => { console.error('WS: Connection closed'); this._queue.forEach(h => h.reject(new Error('Connection closed'))); //this._socket.removeEventListener() this.onCloseCallback(); }; }; } class WsNewsie extends Newsie { public _wsConnection: WsConnection; constructor(options: NewsieOptions) { super(options); const { host, port = 119, tlsPort = false, tlsOptions = {} } = options; this._wsConnection = new WsConnection(host, port, tlsPort, tlsOptions); } public setOnCloseCallback(callback: any) { this._wsConnection.setOnCloseCallback(callback); } public connect = async (): Promise<any> => { const socket = await this._wsConnection.connect(); const response = await this.sendData(Command.GREETING); return { ...response, socket } }; public disconnect = () => this._wsConnection.disconnect(); public sendData = (command: Command, payload?: string): Promise<any> => new Promise((resolve, reject) => { this._wsConnection.addCallback((text: string) => JSON.parse(text), resolve, reject); if (payload) { this._wsConnection.write(payload) } }) //.then(this._interceptor) .then((response: any) => (response.code < 400 ? response : Promise.reject(response))) } export interface ServerInterface { readonly host: string; readonly port: number | undefined; getGroupByName(name: string): Promise<GroupInterface | null>; groups(): Promise<GroupInterface[]>; } export class Server implements ServerInterface { private static server: Server | null = null; private static keepaliveIntervalReference: NodeJS.Timeout | null = null; public readonly host: string; public readonly port: number | undefined; private newsieClient: WsNewsie; constructor(host: string, port?: number) { this.host = host; if (port) { this.port = port; } this.newsieClient = this.initWsNewsieClient(this.host, this.port); } public static async instance(): Promise<Server> { if (this.server === null) { const nntpUrl = process.env.REACT_APP_NNTP_URL; const nntpPortStr = process.env.REACT_APP_NNTP_PORT; if (!nntpUrl || !nntpPortStr) { throw new Error('Environment variable: REACT_APP_NNTP_URL or REACT_APP_NNTP_PORT not specified.'); } this.server = new Server(nntpUrl, parseInt(nntpPortStr)); await this.server.connectAndVerifyNewsieClient(); } return this.server; } private initWsNewsieClient(host: string, port?: number | undefined): WsNewsie { const newsieOptions: NewsieOptions = { host }; if (port && !isNaN(port)) { newsieOptions.port = port; } this.newsieClient = new WsNewsie(newsieOptions); this.newsieClient.setOnCloseCallback(() => { console.log('WS: Reconnect!'); this.initWsNewsieClient(host, port); this.connectAndVerifyNewsieClient(); }); return this.newsieClient; } private async connectAndVerifyNewsieClient(): Promise<WebSocket> { const connection = await this.newsieClient.connect(); if (connection.code !== 200) { throw Error('No connection to server.'); } const capabilities = await this.newsieClient.capabilities(); if (!capabilities.capabilities.LIST.includes('NEWSGROUPS')) { throw Error('Server does\'t have the required LIST NEWSGROUPS capability.'); } return connection.socket; } public async getGroupByName(name: string): Promise<Group | null> { const newsgroups = await this.newsieClient.listNewsgroups(name); if (newsgroups.newsgroups.length !== 1) { return null; } return newsgroups.newsgroups.map((ng) => { const description = typeof ng.description === 'undefined' ? '' : ng.description; return new Group(ng.name, description, this.host, this.newsieClient); })[0]; } public async groups(): Promise<Group[]> { // todo: remove 'tu-graz*' once https://gitlab.com/timrs2998/newsie/merge_requests/2 is merged const newsgroups = await this.newsieClient.listNewsgroups(process.env.REACT_APP_NNTP_GROUP_PREFIX); return newsgroups.newsgroups.map((ng) => { const description = typeof ng.description === 'undefined' ? '' : ng.description; return new Group(ng.name, description, this.host, this.newsieClient); }); } } <file_sep>/README.md # newsR This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Server The server communicates with the newsgroup server using NNTP. ### Available Scripts In the directory `server/`, you can run: #### `npm ci` Installs dependencies. #### `npm run start` Starts the NodeJS server. ## Client The client communicates with the NodeJS server in `server/` and displays newsgroup entries. ### Environment Variables - `REACT_APP_WS_TO_NNTP_URL`: url of the intermediate server with websocket protocol - `REACT_APP_NNTP_URL`: url of the news server (without protocol) - `REACT_APP_NNTP_PORT`: port of the news server - `REACT_APP_NNTP_GROUP_PREFIX`: the prefix of groups you want show ### IntelliJ specifics To get IntelliJ working with the TypeScript settings configured in `client/tsconfig.json`, one needs to configure the typescript scope: - Go to File -> Settings -> Languages & Frameworks - Click on "..." besides Compile scope - Then add a scope, call it e.g. "Client" - For the pattern enter `file[newsr]:client//*` ### Available Scripts In the directory `client/`, you can run: #### `npm ci` Installs dependencies. #### `npm run start` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. #### `npm run test` Launches the test runner in the interactive watch mode.<br /> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. #### `npm run build` Builds the app for production to the `build` folder.<br /> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br /> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. #### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). # Impressum “NewsR” is the newsreader Web App created under the MIT license bootsrapped by using Creat React App where the server communicates with the client via a NNTP. ## Publisher <NAME>, <NAME>, <NAME> Camarero, <NAME>. Created at Technical University Graz. ## Technical implementation and layout Github Link: https://github.com/Elektropepi/newsR Website: https://elektropepi.github.io/newsR Report: https://courses.isds.tugraz.at/iaweb/projects/ws2019/iaweb-ws2019-g3-project-newsr.pdf <file_sep>/client/src/cache/Cache.ts export interface Cache { groupNames: string[] } <file_sep>/server/README.md newsR-ws2nntp ============= deployment on heroku -------------------- run `git subtree push --prefix server heroku master` or ``git push heroku \`git subtree split --prefix server master\`:master --force`` to force deploy. <file_sep>/client/src/article/Article.test.ts import {Article} from "./Article"; import {Content} from "./Content"; test('Citation at beginning correctly removed', () => { const actual: Content[] = [ new Content("Am 25-Nov-19 um 17:01 schrieb blabla:", 0), new Content("lorem ipsum", 1), new Content("bla bla", 0), new Content("bla bla", 0), ]; const expected: Content[] = [ new Content("bla bla", 0), new Content("bla bla", 0), ]; Article.stripStartEndCitationsFromContents(actual); expect(actual).toEqual(expected); }); test('Citation at end correctly removed 1', () => { const actual: Content[] = [ new Content("Hello", 0), new Content("", 0), new Content("I cannot see any change on the upstream ", 0), new Content("Am 24.11.2019 um 11:39 schrieb re: ", 0), new Content("basdf", 1), new Content("as", 1), new Content("", 0) ]; const expected: Content[] = [ new Content("Hello", 0), new Content("", 0), new Content("I cannot see any change on the upstream ", 0), ]; Article.stripStartEndCitationsFromContents(actual); expect(actual).toEqual(expected); }); test('Nested citation at end correctly removed 1', () => { const actual: Content[] = [ new Content("Hello", 0), new Content("", 0), new Content("I cannot see any change on the upstream ", 0), new Content("Am 24.11.2019 um 11:39 schrieb re: ", 0), new Content("basdf", 1), new Content("as", 1), new Content("Am 25.11.2019 um 11:39 schrieb re: ", 1), new Content("lorem", 2), new Content("ipsum", 2), new Content("", 0) ]; const expected: Content[] = [ new Content("Hello", 0), new Content("", 0), new Content("I cannot see any change on the upstream ", 0), ]; Article.stripStartEndCitationsFromContents(actual); expect(actual).toEqual(expected); }); test('Citation at beginning removed 2', () => { const actual: Content[] = [new Content("Am 25-Nov-19 um 17:01 schrieb blabla:", 0), new Content(" Hello,", 1), new Content(" ", 1), new Content(" I cannot see any change on the upstream [1]. The latest commit I see is ", 1), new Content(" xxx..", 1), new Content(" ", 1), new Content(" Best regards,", 1), new Content(" blabla", 1), new Content(" ", 1), new Content(" [1] ", 1), new Content(" bla ", 1), new Content(" ", 1), new Content(" ", 1), new Content(" ", 1), new Content("", 0), new Content("Hi,", 0), new Content("", 0), new Content("it should be online now. Please" + " check and let me know in case it still ", 0), new Content("is not.", 0), new Content("", 0), new Content("Best wishes,", 0), new Content("BlaXX", 0)]; const expected: Content[] = [ new Content("", 0), new Content("Hi,", 0), new Content("", 0), new Content("it should be online now. Please check and let me know in case it still ", 0), new Content("is not.", 0), new Content("", 0), new Content("Best wishes,", 0), new Content("BlaXX", 0) ]; Article.stripStartEndCitationsFromContents(actual); expect(actual).toEqual(expected); }); <file_sep>/client/src/group/Group.ts import Newsie from 'newsie'; import {Article as NewsieArticle} from "newsie"; import {Author} from "../author/Author"; import {Article, ArticleInterface} from "../article/Article"; import {GroupCache} from "./GroupCache"; import packageJson from '../../package.json'; export interface GroupInterface { readonly name: string; readonly description: string; threads(): Promise<ArticleInterface[]>; } interface ArticleMap { [key: string]: Article; } export class Group implements GroupInterface { public readonly name: string; public readonly description: string; public readonly host: string; private readonly newsieClient: Newsie; constructor(name: string, description: string, host: string, newsieClient: Newsie) { this.name = name; this.description = description; this.newsieClient = newsieClient; this.host = host; } public async article(articleNumber: number): Promise<Article|null> { // todo: fix type const overview: any = await this.newsieClient.over(`${articleNumber}-${articleNumber}`); const groupCache = await GroupCache.instance(); await groupCache.persistOverArticles(this.host, this.name, overview.articles); const a: NewsieArticle = overview.articles[0]; return Article.ArticleFromNewsieArticle(a, this, this.newsieClient); } public async threads(): Promise<Article[]> { const group = (await this.newsieClient.group(this.name)).group; if (group.number === 0) { return []; } // todo: fix type const overview: any = await this.newsieClient.over(`${group.low}-${group.high}`); const groupCache = await GroupCache.instance(); await groupCache.persistOverArticles(this.host, this.name, overview.articles); const articles = await groupCache.retrieveOverArticles(this.host, this.name); const articlesByNumber: any[] = articles .sort((a: any, b: any) => a.articleNumber - b.articleNumber) .map((a: any) => { return Article.ArticleFromNewsieArticle(a, this, this.newsieClient); }); const articleIdMap: ArticleMap = {}; const threads: Article[] = []; articlesByNumber.forEach((article) => { articleIdMap[article.id] = article; if (article.references.length === 0) { threads.push(article); } else { if (articleIdMap[article.directReference]) { articleIdMap[article.directReference].followUps.push(article); } } }); threads.sort((a: Article, b: Article) => b.date.unix() - a.date.unix()); return threads; } public async post(author: Author, subject: string, body: string[], references?: string[]): Promise<void> { const initialResponse = await this.newsieClient.post(); if (initialResponse.code !== 340) { // todo: display error.. const errorMsg = "Cannot post: Posting not permitted"; console.error(errorMsg); throw new Error(errorMsg); } const article: NewsieArticle = { headers: { From: author.toString(), Newsgroups: this.name, Subject: subject, "User-Agent": `newsR/${packageJson.version}` }, body: body }; if (references && article.headers) { article.headers.References = references.join(' '); } const postResponse = await initialResponse.send(article); if (postResponse.code !== 240) { // todo: display error.. const errorMsg = "Posting failed: Posting failed"; console.error(errorMsg); throw new Error(errorMsg); } } } <file_sep>/client/src/emailjs-mime-parser.d.ts declare module 'emailjs-mime-parser'; <file_sep>/client/src/group/GroupCache.ts import {Article} from "newsie"; export class GroupCache { private static cache: GroupCache; private db: any; public static async instance(): Promise<GroupCache> { if (this.cache) { return GroupCache.cache; } return new Promise((resolve, reject) => { const openRequest = indexedDB.open("newsR"); openRequest.onerror = () => { reject(); }; openRequest.onsuccess = (event) => { this.cache = new GroupCache(openRequest.result); resolve(this.cache); }; openRequest.onupgradeneeded = GroupCache.upgrade; }) } // todo: event type private static upgrade(event: any) { const db = event.target.result; let overStore = db.createObjectStore("over", { keyPath: "id" }); overStore.createIndex("server-group", ["server", "group"], {unique:false}); overStore.createIndex("server", "server", { unique: false }); overStore.createIndex("group", "group", { unique: false }); overStore.createIndex("articleNumber", "articleNumber", { unique: false }); overStore.createIndex("headers", "headers", { unique: false }); overStore.createIndex("metadata", "metadata", { unique: false }); let bodyStore = db.createObjectStore("body", { keyPath: "id" }); bodyStore.createIndex("server-id", ["server", "id"], {unique:false}); bodyStore.createIndex("server", "server", { unique: false }); bodyStore.createIndex("body", "articleNumber", { unique: false }); } constructor(db: any) { this.db = db; } // todo: fix type // todo: only return once finished.. public async persistOverArticle(server: string, group: string, overArticle: any) { let transaction = this.db.transaction(["over"], "readwrite"); let objectStore = transaction.objectStore("over"); const storageObj = { id: overArticle.headers["MESSAGE-ID"], "server-group": [server, group], server: server, group: group, articleNumber: overArticle.articleNumber, headers: JSON.stringify(overArticle.headers), metadata: JSON.stringify(overArticle.metadata) }; objectStore.add(storageObj); } // todo: fix overview type public async persistOverArticles(server: string, group: string, overviewArticles: Article[]) { overviewArticles.forEach((overArticle: any) => this.persistOverArticle(server, group, overArticle)); } public async retrieveOverArticles(server: string, group: string): Promise<any[]> { return new Promise((resolve => { let transaction = this.db.transaction('over'); let objectStore = transaction.objectStore('over'); let index = objectStore.index("server-group"); const overArticles: any[] = []; index.openCursor(IDBKeyRange.only([server, group])).onsuccess = (event: any) => { let cursor = event.target.result; if(cursor) { const overArticle = { articleNumber: cursor.value.articleNumber, headers: JSON.parse(cursor.value.headers), metadata: JSON.parse(cursor.value.metadata), }; overArticles.push(overArticle); cursor.continue(); } else { resolve(overArticles); } }; })); } // todo: fix type // todo: only return once finished.. public async persistBody(server: string, article: any) { let transaction = this.db.transaction(["body"], "readwrite"); let objectStore = transaction.objectStore("body"); const storageObj = { id: article.messageId, server: server, body: JSON.stringify(article.body), }; objectStore.add(storageObj); } public async retrieveBody(server: string, id: string): Promise<Article> { return new Promise((resolve, reject) => { let transaction = this.db.transaction('body'); let objectStore = transaction.objectStore('body'); let index = objectStore.index("server-id"); index.openCursor(IDBKeyRange.only([server, id])).onsuccess = (event: any) => { let cursor = event.target.result; if (!cursor) { resolve(); return; } const body = { messageId: cursor.value.id, body: JSON.parse(cursor.value.body), }; resolve(body); } }); } } <file_sep>/client/src/localStorage/localStorage.ts export function subscribeGroup(group: string) { const subscribedGroups = getSubscribedGroups(); if (!!subscribedGroups.find(g => g === group)) return; localStorage.setItem("subscribedGroups", JSON.stringify(subscribedGroups.concat(group))) } export function unsubscribeGroup(group: string) { const subscribedGroups = getSubscribedGroups(); if (!subscribedGroups.find(g => g === group)) return; localStorage.setItem("subscribedGroups", JSON.stringify(subscribedGroups.filter(g => g !== group))) } export function getSubscribedGroups(): string[] { const subscribedGroups = localStorage.getItem("subscribedGroups"); if (!subscribedGroups) return []; return JSON.parse(subscribedGroups); } export function addReadArticle(group: string, article: string) { const readArticles = getReadArticles(group); if (!!readArticles.find(a => a === group)) return; localStorage.setItem(group, JSON.stringify(readArticles.concat(article))) } export function getReadArticles(group: string): string[] { const readArticles = localStorage.getItem(group); if (!readArticles) return []; return JSON.parse(readArticles); } <file_sep>/client/src/article/Article.ts import moment, {Moment} from "moment"; import Newsie from 'newsie'; import parse from "emailjs-mime-parser"; import {Author} from "../author/Author"; import {Content} from "./Content"; import {Group} from "../group/Group"; import {GroupCache} from "../group/GroupCache"; import {Attachment} from "./Attachment"; import {mimeWordsDecode} from "emailjs-mime-codec"; import {Article as NewsieArticle} from "newsie"; export type ArticleId = string; export interface ArticleInterface { id: ArticleId, subject: string, date: Moment, author: Author, followUps: ArticleInterface[], number: number, contents(): Promise<{text: Content[], attachments: Attachment[]}>, } export class Article implements ArticleInterface { private static readonly whitespaceRegex = new RegExp(/^$|\s+/); public readonly id: ArticleId; public readonly number: number; public readonly subject: string; public readonly date: Moment; public readonly author: Author; public references: ArticleId[] = []; public directReference: ArticleId = ''; public followUps: ArticleInterface[] = []; private group: Group; private readonly newsieClient: Newsie; constructor(id: string, number: number, subject: string, date: Moment, author: Author, group: Group, newsieClient: Newsie) { this.id = id; this.number = number; this.subject = subject; this.date = date; this.author = author; this.group = group; this.newsieClient = newsieClient; } public static ArticleFromNewsieArticle(a: NewsieArticle, group: Group, newsieClient: Newsie): Article | null { if (!a || !a.headers || !a.articleNumber) { return null; } const date = moment(a.headers.DATE); const author = Author.authorFromString(mimeWordsDecode(a.headers.FROM)); const article = new Article(a.headers['MESSAGE-ID'], a.articleNumber, mimeWordsDecode(a.headers.SUBJECT), date, author, group, newsieClient); article.setReferences(a.headers.REFERENCES); return article; } public static stripStartEndCitationsFromContents(contents: Content[]) { if (contents.length < 1) { return; } const firstContent = contents[0]; if (firstContent.isCitationStart()) { let nextRootIndex = 1; while ((nextRootIndex < contents.length && contents[nextRootIndex].citationLevel !== 0) || contents[nextRootIndex].text.length === 0) { nextRootIndex++; } contents.splice(0, nextRootIndex); } let citationIndex: number | null = null; for (let i = contents.length - 1; i >= 0; i--) { const content = contents[i]; if (content.citationLevel === 0 && !Article.isOnlyWhitespace(content.text)) { break; } if (content.isCitationStart()) { citationIndex = i; break; } } if (citationIndex !== null) { contents.splice(citationIndex, contents.length - citationIndex) } } private static isOnlyWhitespace(text: string): boolean { return Article.whitespaceRegex.test(text); } private static bodyToContents(body: string[]): {text: Content[], attachments: Attachment[]} { const contents: Content[] = []; let attachments: Attachment[] = []; if (body[0] === 'This is a multi-part message in MIME format.') { const missingMimeHeader = 'MIME-Version: 1.0\n' + `Content-Type: multipart/mixed; boundary=${body[1].substring(2)}\n` + '\n'; const mimeInfo = parse(missingMimeHeader + body.join('\n')); body = mimeInfo.childNodes .filter((node: any) => node.contentType.value === 'text/plain') .map((node: any) => new TextDecoder("utf-8").decode(node.content)) .join('\n') .split('\n'); attachments = mimeInfo.childNodes .filter((node: any) => node.contentType.value !== 'text/plain') .map((node: any) => { const base64 = node.raw.substring(node.raw.lastIndexOf('\n\n')).replace(/\s/g, ""); return { contentType: node.contentType.value, name: node.contentType.params.name, dataUrl: `data:${node.contentType.value};base64,${base64}` }; }); } if (!body) { return {text: contents, attachments}; } body.forEach((line: string) => { let citationLevel = 0; while (citationLevel < line.length && line[citationLevel] === ">") { citationLevel++; } line = line.substring(citationLevel, line.length); contents.push(new Content(line, citationLevel)); }); return {text: contents, attachments}; } public setReferences(references: string) { if (references.length <= 0) { return; } this.references = references.split(' '); this.directReference = this.references[this.references.length - 1]; } public async contents(): Promise<{text: Content[], attachments: Attachment[]}> { const groupCache = await GroupCache.instance(); let article = await groupCache.retrieveBody(this.group.host, this.id); if (!article || !article.body) { article = (await this.newsieClient.body(this.id)).article; if (article.body) { await groupCache.persistBody(this.group.host, article); } else { article.body = [ '[newsR: content not found and not cached]' ] } } const contents = Article.bodyToContents(article.body); Article.stripStartEndCitationsFromContents(contents.text); return {text: contents.text, attachments: contents.attachments}; } public async postFollowup(author: Author, subject: string, body: string[]): Promise<void> { await this.group.post(author, subject, body, this.references.concat(this.id)); } } <file_sep>/server/index.js const WebSocket = require('ws'); const Newsie = require('newsie').default; const {Command} = require('newsie'); // todo: typescript function findCommand(str) { return Object.values(Command).filter((command) => { return str.startsWith(command); }).sort((a, b) => b.length - a.length)[0]; } const port = process.env.PORT || 8080; console.log('Starting with port: ' + port); const keepAliveInterval = 1000; // 1 second const killConnectionInterval = 1000 * 30; // 30 seconds const server = new WebSocket.Server({ port: port }); function resetKillInterval(killInterval, ws) { clearInterval(killInterval); return setInterval(() => { ws.close(); }, killConnectionInterval); } server.on('connection', function connection(ws) { let newsie; const pingInterval = setInterval(() => { ws.ping(); }, keepAliveInterval); let killInterval = resetKillInterval(null, ws); ws.on('close', () => { clearInterval(pingInterval); clearInterval(killInterval); if (newsie) { newsie.disconnect(); } }); ws.on('pong', () => { killInterval = resetKillInterval(killInterval, ws); }); let previousCommand = ''; ws.on('message', async function incoming(message) { killInterval = resetKillInterval(killInterval, ws); if (message.startsWith('NNTPCONNECT')) { const messageSplit = message.split(" "); newsie = new Newsie({ host: messageSplit[1], port: messageSplit[2] }); newsie.connect().then(() => { ws.send(JSON.stringify({ code: 200 })); }); } const foundCommand = findCommand(message); if (foundCommand) { if (!newsie) { // todo: return error via websocket throw Error('No connection to NNTP server, call NNTPCONNECT with host and port first.'); } let arguments = []; if (foundCommand.length !== message.trim().length) { arguments = message.slice(foundCommand.length).trim().split(' '); } newsie.command(foundCommand, ...arguments).then((data) => { ws.send(JSON.stringify(data)); }); previousCommand = foundCommand; } else if (previousCommand === Command.POST) { newsie.sendData(Command.POST_SEND, message).then((data) => { ws.send(JSON.stringify(data)); }); } }); });
51875779553fe7a942c469ebed86da2e9ae93fa4
[ "Markdown", "TypeScript", "JavaScript" ]
16
TypeScript
Elektropepi/newsR
cec950eae92f28922cc8d400208ac4f1b05958db
924c70da931cf6dd6cd20885cc478f10f80fb53c
refs/heads/master
<file_sep>// Arquivo: php.c // Autor: <NAME> // Data: 28 ago. 2018 #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_RESOURCES 5 #define MAX_TASKS 26 #define MAX_STEPS 20 #define MAX_TIME 1000 #define RUN 0 #define LOCK 1 #define UNLOCK 2 typedef struct { int p; //prioridade int a; //tempo de chegada int ns; //numero de computaçoes int s[MAX_STEPS][2]; //steps [run, lock, unlock] char name; // ... } TASK; int main() { int num_resources, num_tasks, i, j, value; TASK tasks[MAX_TASKS], orderedTaks[MAX_TASKS]; char word[20]; char result[MAX_RESOURCES+1][MAX_TIME]; int sim_time = -1; char* provisorio; int runs; while (1) { // LEITURA //num_resources numero de coisas que podem ser usadas pelas taks //num_tasks é numero de tasks que vao ter de ser escalonadas scanf("%d %d", &num_resources, &num_tasks); if (num_tasks == 0) break; for (i=0; i<num_tasks; ++i) { //prioridade --- tempo de chegada --- numero de computações scanf("%d %d %d", &(tasks[i].p), &(tasks[i].a), &(tasks[i].ns) ); for (j=0; j<tasks[i].ns; ++j) { //word é pra scanf("%s %d", word, &value); if (strcmp(word,"run")==0 || strcmp(word,"RUN")==0) tasks[i].s[j][0] = RUN; else if (strcmp(word,"lock")==0 || strcmp(word,"LOCK")==0) tasks[i].s[j][0] = LOCK; else if (strcmp(word,"unlock")==0 || strcmp(word,"UNLOCK")==0) tasks[i].s[j][0] = UNLOCK; else exit(1); tasks[i].s[j][1] = value; } } //Ordena por tempo de chegada as tasks memcpy(orderedTaks, reorderTasks(tasks, num_tasks), sizeof(tasks)); //Nomeia de alfabeticamente as tasks for(i=0;i<sizeof(tasks); i++){ tasks[i].name = 'A' + i; } //Começa simulação sem os a atribuição de requisitos for(i=0;i<num_tasks; i++){ if(sim_time < orderedTaks[i].a){ for(j=0; j<orderedTaks[i].ns; j++){ if(orderedTaks[i].s[j][0] == "RUN"){ for(runs =0; runs<orderedTaks[i].s[j][1];runs++){ provisorio = orderedTaks[i].name; sim_time++; } } } } } // // provisorio: // sim_time = 20; // for (i=0; i<num_resources+1; ++i) { // for (j=0; j<sim_time; ++j) { // result[i][j] = '.'; // } // } // // fim do provisorio. // MOSTRAR RESULTADOS for (i=0; i<num_resources+1; ++i) { for (j=0; j<sim_time; ++j) { putchar(result[i][j]); } putchar('\n'); } putchar('\n'); } return 0; } TASK * setTasksName(TASK tasks[]){ int i; for(i=0;i<sizeof(tasks); i++){ tasks[i].name = 'A' + i; } return tasks; } TASK * reorderTasks(TASK tasks[], int numTasks){ int i =0; TASK orderedTasks[numTasks]; for(i=0; i<numTasks; i++){ if(sizeof(orderedTasks)==0){ orderedTasks[i] = tasks[i]; } if(tasks[i].a < orderedTasks[i].a){ orderedTasks[i+1] = orderedTasks[i]; orderedTasks[i] = tasks[i]; } else orderedTasks[i] = tasks[i]; } return orderedTasks; }
a0c4c78239af2e6ddbdc9f550361e4ae29e9ab88
[ "C" ]
1
C
pereiraguilherme/Trabalho_PHP_STR
650e3784f2257bafc7ad7d20a7c4202145090b8e
200ea2022525e6777de829a1078c25f0cd71f990
refs/heads/master
<repo_name>EllenPeng123/Gitlet<file_sep>/Gitlet.java package gitlet; import java.util.Map; import java.util.HashMap; import java.util.*; import java.io.*; public class Gitlet implements Serializable { public static final long serialVersionUID = 42L; // required for serializing private Map<String, Commit> listOfCommits; // maps commitHashID to Commit object private String currentBranch; // contains the branchName of the current branch private String currentCommit; // contains the HashID of the current HEAD commit ArrayList<File> filesAdded = new ArrayList<>(); ArrayList<String> filesRemoved = new ArrayList<>(); private HashMap<String, Commit> branch = new HashMap<>(); private HashMap<String, Commit> split = new HashMap<>(); public Gitlet(String stringy) { /** * This constructor is called in readObjectGitlet() * If no file is found, it initializes the object to null */ listOfCommits = new HashMap<String, Commit>(); currentBranch = null; currentCommit = null; filesAdded = null; filesRemoved = new ArrayList<String>(); branch = new HashMap<>(); } public Gitlet() { /** * This is the main constructor called in HandleArgs Class */ Gitlet g = readObjectGitlet(); try { this.listOfCommits = g.listOfCommits; } catch (NullPointerException e) { this.listOfCommits = new HashMap<String, Commit>(); } this.currentBranch = g.currentBranch; this.currentCommit = g.currentCommit; this.filesRemoved = g.filesRemoved; this.setFiles(); this.branch = g.branch; this.split = g.split; } public Gitlet readObjectGitlet() { /** * Reads a file named Commits.txt in directory .gitlet, serializes gitlet object * Reads gitlet objects and instances from this file */ if (new File(".gitlet/").exists()) { try { FileInputStream file = new FileInputStream(".gitlet/Commits.txt"); ObjectInputStream in = new ObjectInputStream(file); Gitlet g = (Gitlet) in.readObject(); in.close(); file.close(); return g; } catch (FileNotFoundException e) { return new Gitlet("new Constructor"); } catch (IOException e) { return null; } catch (ClassNotFoundException e) { return null; } } else { return new Gitlet("new Constructor"); } } /** * Writes a file named Commits.txt (Saves gitlet object and its instances in this file) */ public void writeObjectGitlet() { try { FileOutputStream fileOut = new FileOutputStream(".gitlet/Commits.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(this); out.close(); fileOut.close(); } catch (IOException e) { System.out.println("IO Exception"); } } /** * Makes a branch named master */ public void makeMasterBranch() { setCurrentBranch("master"); // make commit and get hashID Commit newCommit = new Commit(setToArray("master")); listOfCommits.put(newCommit.hashID, newCommit); currentCommit = newCommit.hashID; branch.put("master", listOfCommits.get(currentCommit)); } /** * Sets the list of filenames in the working directory edited by user * as filesAdded of the gitlet object */ public void setFiles() { TrackingFiles files = new TrackingFiles(); filesAdded = files.getFiles(); } public void setCurrentBranch(String s) { currentBranch = s; } public void init() { /** * Initializes a .gitlet directory * Initializes a master branch with a initial commit */ Init initial = new Init(); if (initial.makeDir()) { makeMasterBranch(); } } public void add(String filename) { /** * This method adds files to the StagingArea. * It checks if the file is already staged. * Then, it adds it to the instance variable - filesAdded. */ File ourFile = new File(filename); if (new File(filename).exists()) { StagingArea stage = new StagingArea(); Commit c = listOfCommits.get(currentCommit); boolean flag = false; try { flag = TrackingFiles.checkFile(ourFile, c.fileContents.get(filename)); } catch (NullPointerException e) { flag = false; } if (filesRemoved.contains(filename)) { filesRemoved.remove(filename); } else if (!flag) { if (stage.filesAdded.containsKey(filename)) { System.out.print("Is already staged"); } else { stage.addFiles(filename); } } stage.writeObject(); } else { System.out.println("File does not exist."); } } public ArrayList<String> setToArray(String strName) { /** * Sets a given string to an arrayList of type String. */ ArrayList<String> arrName = new ArrayList<String>(); arrName.add(strName); return arrName; } public void branch(String branchName) { /** * This method executes the command "branch". * It creates a new branch and before doing that, * it checks whether a branch of that name is already made. */ if (getAllbranches().contains(branchName)) { System.out.println("A branch with that name already exists."); } boolean setFlag = false; for (String bName : listOfCommits.get(currentCommit).branchName) { if (branchName == bName) { setFlag = true; } } if (!setFlag) { listOfCommits.get(currentCommit).branchName.add(branchName); } branch.put(branchName, listOfCommits.get(currentCommit)); split.put(branchName, listOfCommits.get(currentCommit)); } public void commit(String msg) { /** * This method initializes a commit everytime it is called. */ StagingArea stage = new StagingArea(); if (!stage.filesAdded.isEmpty() || !filesRemoved.isEmpty()) { HashMap<String, byte[]> files = new HashMap<String, byte[]>(); for (String key : stage.filesAdded.keySet()) { files.put(key, Utils.readContents(stage.filesAdded.get(key))); } Commit makeCommit = new Commit(setToArray(currentBranch), msg, currentCommit, files); listOfCommits.put(makeCommit.hashID, makeCommit); try { listOfCommits.get(currentCommit).nextHashID.add(makeCommit.hashID); } catch (NullPointerException e) { listOfCommits.get(currentCommit).nextHashID = new ArrayList<String>(); listOfCommits.get(currentCommit).nextHashID.add(makeCommit.hashID); } currentCommit = makeCommit.hashID; filesRemoved.clear(); stage.filesAdded.clear(); stage.writeObject(); branch.replace(currentBranch, listOfCommits.get(currentCommit)); } else { System.out.println("No changes added to the commit."); } } public void globLog() { /** * This method executes global-log command, * it works very closely with log method mentioned below. */ for (String key : listOfCommits.keySet()) { printCommit(key, listOfCommits.get(key).message, listOfCommits.get(key).timestamp); } } public void log() { /** * This method is called by handleArgs handle() method. * This calls recLog which is a recursive method in Commit class. * recLog recursively traverses through commits in the listOfCommits. * For each commit, it calls static method printCommit() in gitlet class. */ listOfCommits.get(currentCommit).recLog(listOfCommits); } public static void printCommit(String key, String messg, String timestamp) { /** * Prints commits in the following format */ System.out.println("==="); System.out.println("Commit " + key); System.out.println(timestamp); System.out.println(messg); System.out.println(); } public void remove(String fileName) { /** * This executes the remove command. Temporarily ignore it. */ File file = new File(fileName); StagingArea stage = new StagingArea(); if (Commit.checkFile(currentCommit, listOfCommits, fileName)) { // then remove filesRemoved.add(fileName); if (stage.checkFileName(fileName)) { stage.filesAdded.remove(fileName); } Utils.restrictedDelete(fileName); } else if (stage.checkFileName(fileName)) { stage.filesAdded.remove(fileName); } else { System.out.println("No reason to remove the file"); } stage.writeObject(); } public void removeBranch(String bName) { if (currentBranch.equals(bName)) { System.out.println("Cannot remove the current branch."); return; } if (!getAllbranches().contains(bName)) { System.out.println("A branch with that name does not exist."); } } public void find(String message) { /** * This method is called in handleArgs class by handle() method * It performs the find command. It finds the commit based on the commit message passed. */ boolean checker = false; for (Commit c : listOfCommits.values()) { if (c.message.equals(message)) { checker = true; System.out.println(c.hashID); } } if (!checker) { System.out.println("Found no commit with that message."); } } public void checkOutBranch(String bName) { /** * This is a partially implemented checkOutBranch() - bullet 3 in checkout spec sheet * Build up is required for proper functioning */ Commit currCommit = listOfCommits.get(currentCommit); if (isContainsBranch(bName) || currentBranch.equals(bName)) { if (currentBranch.equals(bName)) { System.out.println("No need to checkout the current branch."); return; } } else { System.out.println("No such branch exists."); return; } for (String filename : TrackingFiles.getFileNames()) { if (!checkIfFileIsInBranch(filename) && getLatestCommit(bName).fileContents.containsKey(filename)) { String messg = "There is an untracked file in the way; delete it or add it first."; System.out.println(messg); System.exit(0); } } Commit latest = getLatestCommit(bName); for (String filename : currCommit.fileContents.keySet()) { if (!latest.fileContents.keySet().contains(filename)) { Utils.restrictedDelete(filename); } } for (String filename : latest.fileContents.keySet()) { byte[] fileTodisk = latest.fileContents.get(filename); File overwrite = new File(filename); try { FileOutputStream out = new FileOutputStream(overwrite, false); out.write(fileTodisk); out.close(); } catch (IOException e) { System.out.println("IOException"); } catch (NullPointerException e) { System.out.println("File does not exist in that commit."); } } currentBranch = bName; currentCommit = getLatestCommit(bName).hashID; return; } public void checkOutFile(String filename) { /** * Takes the version of the file in the most recent commit * and adds it to the working directory * overrides if necessary */ Commit currCommit = listOfCommits.get(currentCommit); byte[] fileTodisk = currCommit.fileContents.get(filename); File overwrite = new File(filename); try { FileOutputStream out = new FileOutputStream(overwrite, false); out.write(fileTodisk); out.close(); } catch (IOException e) { System.out.println("IOException"); } } public void checkout(String filename, String commitID) { /** * Takes the version of the file in the commit specified and * adds it to the working directory * Overrides if necessary */ if (!listOfCommits.containsKey(commitID)) { if (!commitExist(commitID)) { System.out.println("No commit with that id exists."); return; } } if (commitID.length() != 8) { Commit currCommit = listOfCommits.get(commitID); byte[] fileTodisk = currCommit.fileContents.get(filename); File overwrite = new File(filename); try { FileOutputStream out = new FileOutputStream(overwrite, false); out.write(fileTodisk); out.close(); } catch (IOException e) { System.out.println("IOException"); } catch (NullPointerException e) { System.out.println("File does not exist in that commit."); } } else { Commit currCommit = returnCommit(commitID); byte[] fileTodisk = currCommit.fileContents.get(filename); File overwrite = new File(filename); try { FileOutputStream out = new FileOutputStream(overwrite, false); out.write(fileTodisk); out.close(); } catch (IOException e) { System.out.println("IOException"); } catch (NullPointerException e) { System.out.println("File does not exist in that commit."); } } } public void status() { /** * This is a functioning method that executes the status command. * Please contact Shruti for further assistance in comprehending the functionalities. */ System.out.println("=== Branches ==="); /** * Prints out all the branch names */ System.out.println("*" + currentBranch); for (String b : getAllbranches()) { System.out.println(b); } System.out.println(); System.out.println("=== Staged Files ==="); /** * prints out all the files in the staging area */ StagingArea stage = new StagingArea(); for (String file : stage.filesAdded.keySet()) { System.out.println(file); } System.out.println(); System.out.println("=== Removed Files ==="); try { for (String deletedFile : filesRemoved) { System.out.println(deletedFile); } } catch (NullPointerException e) { System.out.println(); } // get arraylist of removed files , print files System.out.println(); System.out.println("=== Modifications Not Staged For Commit ==="); //just keeping headers System.out.println(); System.out.println("=== Untracked Files ==="); //just keeping headers } public ArrayList<String> getAllbranches() { /** returns an array of all the branches * */ ArrayList<String> branches = new ArrayList<String>(); try { for (Commit c : listOfCommits.values()) { for (String b : c.branchName) { if (!b.equals(currentBranch) && !branches.contains(b)) { branches.add(b); } } } } catch (NullPointerException e) { return null; } return branches; } public boolean isContainsBranch(String brch) { /** checks if a branch name is a part of the branches * */ ArrayList<String> branches = getAllbranches(); if (branches.contains(brch)) { return true; } return false; } public boolean commitExist(String commitid) { for (String makeCommit : listOfCommits.keySet()) { String firstEight = commitid.substring(0, 7); String toCompare = makeCommit.substring(0, 7); if (firstEight.equals(toCompare)) { return true; } } return false; } public Commit returnCommit(String commitid) { if (commitExist(commitid)) { for (String makeCommit : listOfCommits.keySet()) { String firstEight = commitid.substring(0, 7); String toCompare = makeCommit.substring(0, 7); if (firstEight.equals(toCompare)) { return listOfCommits.get(makeCommit); } } } return null; } public void reset(String commitID) { String messg = "There is an untracked file in the way; delete it or add it first."; List<String> currFileNames = TrackingFiles.getFileNames(); if (!commitExist(commitID) && !listOfCommits.containsKey(commitID)) { System.out.println("No commit with that id exists."); return; } else { Commit getFile = listOfCommits.get(commitID); for (String filename : TrackingFiles.getFileNames()) { if (!checkIfFileIsInBranch(filename) && getFile.fileContents.containsKey(filename)) { byte[] fileInCommit = getFile.fileContents.get(filename); File fileInDir = new File(filename); byte [] fileinDir = Utils.readContents(fileInDir); if (!TrackingFiles.checkFile(fileinDir, fileInCommit)) { System.out.println(messg); System.exit(0); } } } for (String fileName : currFileNames) { File existingFile = new File(fileName); if (getFile.fileContents.get(fileName) == null) { if (checkIfFileIsInBranch(fileName)) { Utils.restrictedDelete(fileName); } } else { byte[] commitFile = getFile.fileContents.get(fileName); try { FileOutputStream out = new FileOutputStream(existingFile, false); out.write(commitFile); out.close(); } catch (IOException e) { System.out.println("Damn !!"); } } } currentCommit = commitID; StagingArea stage = new StagingArea(); stage.filesAdded.clear(); stage.writeObject(); branch.replace(currentBranch, listOfCommits.get(currentCommit)); } } public boolean checkIfFileIsInBranch(String fileName) { boolean msflaggy = false; File file = new File(fileName); for (Commit c : listOfCommits.values()) { try { if (c.fileContents.containsKey(fileName)) { byte[] toCompare = c.fileContents.get(fileName); if (TrackingFiles.checkFile(file, toCompare)) { msflaggy = true; } } } catch (NullPointerException e) { continue; } } return msflaggy; } public Commit getLatestCommit(String bName) { return branch.get(bName); } public void merge(String bName) { if (!isContainsBranch(bName) && !currentBranch.equals(bName)) { System.out.println("A branch with that name does not exist."); return; } if (bName.equals(currentBranch)) { System.out.println("Cannot merge a branch with itself."); return; } StagingArea stage = new StagingArea(); if (!stage.filesAdded.isEmpty()) { System.out.println("You have uncommitted changes."); stage.writeObject(); return; } for (String filename : TrackingFiles.getFileNames()) { if (!checkIfFileIsInBranch(filename)) { String messg = "There is an untracked file in the way; delete it or add it first."; System.out.println(messg); System.exit(0); } } if (isContainsBranch(bName)) { Commit c = getSplitPoint(bName, currentBranch); HashMap<String, byte[]> filesSplitPnt = c.fileContents; HashMap<String, byte[]> filesCurrBrch = listOfCommits.get(currentCommit).fileContents; HashMap<String, byte[]> filesGivBrch = listOfCommits.get(getLatestCommit(bName).hashID).fileContents; boolean conflict = false; if (filesSplitPnt.size() == filesGivBrch.size()) { if (filesSplitPnt.equals(filesGivBrch)) { String msg = "Given branch is an ancestor of the current branch."; stage.writeObject(); System.out.println(msg); } } if (filesSplitPnt.size() == filesCurrBrch.size()) { if (filesSplitPnt.equals(filesCurrBrch)) { stage.writeObject(); System.out.println("Current branch fast-forwarded."); } } for (String fileName : filesSplitPnt.keySet()) { if (filesGivBrch.get(fileName) == null && filesSplitPnt.get(fileName) == null) { continue; } else if (filesGivBrch.get(fileName) == null && filesCurrBrch.get(fileName) == null) { Utils.restrictedDelete(fileName); } else if (filesGivBrch.get(fileName) == null && TrackingFiles.checkFile(filesCurrBrch.get(fileName), filesSplitPnt.get(fileName))) { Utils.restrictedDelete(fileName); filesRemoved.add(fileName); } else if (filesGivBrch.get(fileName) == null && !TrackingFiles.checkFile(filesCurrBrch.get(fileName), filesSplitPnt.get(fileName))) { TrackingFiles.writeToFileConflict(fileName, filesCurrBrch.get(fileName), null); conflict = true; } else if (filesCurrBrch.get(fileName) == null && !TrackingFiles.checkFile(filesSplitPnt.get(fileName), filesGivBrch.get(fileName))) { TrackingFiles.writeToFile(fileName, filesGivBrch.get(fileName)); stage.addFiles(fileName); } else if (TrackingFiles.checkFile(filesSplitPnt.get(fileName), filesGivBrch.get(fileName))) { continue; } else if (TrackingFiles.checkFile(filesSplitPnt.get(fileName), filesCurrBrch.get(fileName))) { TrackingFiles.writeToFile((fileName), filesGivBrch.get(fileName)); stage.addFiles(fileName); } else if (!TrackingFiles.checkFile(filesSplitPnt.get(fileName), filesCurrBrch.get(fileName)) && !TrackingFiles.checkFile(filesSplitPnt.get(fileName), filesGivBrch.get(fileName))) { TrackingFiles.writeToFileConflict(fileName, filesCurrBrch.get(fileName), filesGivBrch.get(fileName)); conflict = true; } } for (String fileName : filesGivBrch.keySet()) { if (!filesSplitPnt.containsKey(fileName)) { TrackingFiles.writeToFile(fileName, filesGivBrch.get(fileName)); stage.addFiles(fileName); } } if (conflict) { System.out.println("Encountered a merge conflict."); } else { Commit merged = new Commit(setToArray(currentBranch), "Merged " + currentBranch + " with " + bName + ".", currentCommit, getLatestCommit(bName).fileContents); listOfCommits.get(currentCommit).nextHashID = setToArray(merged.hashID); currentCommit = merged.hashID; listOfCommits.put(merged.hashID, merged); stage.filesAdded.clear(); stage.writeObject(); branch.replace(currentBranch, listOfCommits.get(currentCommit)); filesRemoved.clear(); return; } } } public Commit getSplitPoint(String givenBranch, String currBranch) { if (givenBranch.equals("master")) { return split.get(currBranch); } return split.get(givenBranch); } } <file_sep>/StagingArea.java package gitlet; import java.io.*; import java.util.HashMap; import java.util.Map; public class StagingArea implements Serializable { public static final long serialVersionUID = 42L; Map<String, File> filesAdded; // filename to file public StagingArea() { if (new File(".gitlet/stagingArea").exists()) { StagingArea stage = this.readObject(); this.filesAdded = stage.filesAdded; } else { this.filesAdded = new HashMap<String, File>(); } } public boolean checkFile(File file) { /**checks if a file is a part of the staging area * */ return filesAdded.containsValue(file); } public void addFiles(String filename) { //We should be checking to see if the file has been modified first /** * This method adds file to the staging area */ if (!filesAdded.containsKey(filename)) { filesAdded.put(filename, new File(filename)); this.writeObject(); } } public static StagingArea readObject() { /** * This method reads and deserializes the object of Staging Area class. * The file where the following object is stores is - .gitlet/stagingArea */ try { FileInputStream file = new FileInputStream(".gitlet/stagingArea"); ObjectInputStream in = new ObjectInputStream(file); StagingArea stage = (StagingArea) in.readObject(); in.close(); file.close(); return stage; } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } catch (ClassNotFoundException e) { return null; } } public void writeObject() { /** * This method serializes and writes the object of Staging Area class. */ try { FileOutputStream fileOut = new FileOutputStream(".gitlet/stagingArea"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(this); out.close(); fileOut.close(); } catch (IOException e) { System.out.println("IO Exception"); } } public boolean checkFileName(String fileName) { try { return filesAdded.containsKey(fileName); } catch (NullPointerException e) { return false; } } } <file_sep>/README.md # Gitlet Summary This is a version control system that mimics the main functionality of the well-known Git, such as:<br /> - Committing: saving the contents of entire directories of files, which are called commits.<br /> - Checking out: restoring a version of one or more files or entire commits. <br> - Log: viewing the history of your backups. <br /> - Branches: maintaining related sequences of commits.<br/> - Merging changes made in one branch into another.<br /> Simple Visualization of Commit (snapshots of your files): ![img](1.png) Current Commit: ![img](3.png) Revert Last Commit: ![img](2.png) Multiple Commits(Commit Tree): ![img](4.png) Internal structures:<br /> - Blobs: Essentially the contents of files.<br /> - Trees: Directory structures mapping names to references to blobs and other trees (subdirectories).<br> - Commits: Combinations of log messages, other metadata (commit date, author, etc.), a reference to a tree, and references to parent commits. The repository also maintains a mapping from branch heads to references to commits, so that certain important commits have symbolic names.<br /> ![img](5.png) Collaborators: <NAME>, <NAME>, <NAME>.
b7eb468c979f55988e2912c2b9e66c239d634ae4
[ "Markdown", "Java" ]
3
Java
EllenPeng123/Gitlet
bdf7d3b9596bd0c4bd8bdc42dc2f396f055b9bfb
211c0a345ab5f24e5b8fa2aaaa335e8710ce2f95
refs/heads/master
<repo_name>alpcanaydin/devizmir-node<file_sep>/classes.js 'use strict'; class Example { constructor() { this.defaultOptions = { city: 'izmir', lang: 'node.js' }; } sayHi(name) { console.log(`Hello ${name} from ${this.options.city}`); } get options() { return this.defaultOptions; } set options(options) { Object.assign(this.defaultOptions, options); } } const example = new Example(); console.log(example.sayHi('alpcan')); console.log(example.options); console.log('----'); example.options = { city: 'ankara' }; console.log(example.sayHi('alpcan')); console.log(example.options); <file_sep>/nonBlocking.js 'use strict'; const fs = require('fs'); console.log(1); fs.readFile('file.7z', () => { console.log(2); console.log('File read.'); }); console.log(3); <file_sep>/chunkStream.js 'use strict'; const fs = require('fs'); const stream = fs.createReadStream('langs.txt'); stream .on('data', data => console.log(data)) .on('close', () => console.log('done!')) ; <file_sep>/existingPromise.js 'use strict'; const User = require('./model/user'); User .find({}) .then(docs => { if (docs === null) { return Promise.reject(); } return docs; }) .then(docs => docs.filter(doc => doc.age > 18)) .catch(err => console.log(err)) ; <file_sep>/creatingPromise.js 'use strict'; const fs = require('fs'); const readFile = filename => new Promise((resolve, reject) => { fs.readFile(filename, 'utf-8', (err, data) => { if (err) { return reject(err); } resolve(data); }); }); readFile('langs.txt') .then(data => data.split('\n')) .then(langs => langs.filter(lang => lang !== '')) .then(langs => console.log(langs)) .catch(err => console.log(err)) ; <file_sep>/classesExtends.js 'use strict'; class Animal { constructor() { this.kind = 'animal'; } setName(name) { this.name = name; } sayHi() { return `Hello my name is ${this.name}. I am an ${this.kind}`; } } class Dog extends Animal { constructor() { super(); this.something = 'somevalue'; } } const dog = new Dog(); console.log(dog.something); dog.setName('Karabaş'); console.log(dog.sayHi()); <file_sep>/promiseChain.js 'use strict'; const User = require('./model/user'); const Product = require('./model/product'); const Category = require('./model/category'); Promise .all([ User.count(), Product.count(), Category.count() ]) .then(values => { const userCount = values[0]; const productCount = values[1]; const categoryCount = values[2]; console.log(` userCount: ${userCount}\n productCount: ${productCount}\n categoryCount: ${categoryCount} `); }) .catch(err => console.log(err)) ; <file_sep>/eventEmitter.js 'use strict'; const EventEmitter = require('events'); // New instance of event emitter class ExampleEventEmitter extends EventEmitter {} const exampleEventEmitter = new ExampleEventEmitter(); setTimeout( // Push a message to say channel. () => exampleEventEmitter.emit('say', 'hello world!'), 3000 ); // Log message exampleEventEmitter.on('say', data => console.log(data)); <file_sep>/asyncEach.js 'use strict'; const async = require('async'); const User = require('./model/user'); const usernames = [ 'ali', 'veli', 'mehmet' ]; const response = []; async.each( usernames, (username, callback) => { User.findOne({ username }, (err, doc) => { if (err) { return callback(); } response.push(doc); callback(); }); }, () => { console.log('finished!'); }); <file_sep>/ws.js 'use strict'; const WebSocketServer = require('ws').Server; const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', ws => { console.log('New connection!'); ws.on('message', message => { const response = message.split('').reverse().join(''); ws.send(response); }); }); <file_sep>/customMiddleware.js 'use strict'; const express = require('express'); const app = express(); const responder = (req, res, next) => { res.success = vars => res.json({ meta: { status: 200 }, data: vars || null }); res.error = (status, error) => res.json({ meta: { status, error } }); next(); }; app.use(responder); app.get('/', (req, res) => res.success({ user: 'alpcan' })); app.get('/deneme', (req, res) => res.error(500, 'Server Error')); app.listen(3000, () => { console.log('API is running.'); }); <file_sep>/readme.md # Dev Izmir Node.js Sunumu için Örnek Kodlar <file_sep>/lineByLine.js 'use strict'; const fs = require('fs'); const readLine = require('readline'); const stream = readLine.createInterface({ input: fs.createReadStream('langs.txt'), terminal: false }); stream .on('line', line => console.log(line)) .on('close', () => console.log('done!')) ; <file_sep>/arrowFunction.js 'use strict'; // ES5 /* eslint-disable */ var es5Arr = [1, 2, 3, 4]; var newEs5Arr = es5Arr.filter(function (item) { return item > 2; }); /* eslint-enable */ // ES6 const arr = [1, 2, 3, 4]; const newArr = arr.filter(item => item > 2); console.log(newArr); const callback = (err, data) => { if (err) { throw new Error('Error occured'); } return data * 2; }; callback(null, 3); const cities = [ 'izmir', 'istanbul', 'ankara' ]; const citiesObj = cities.map(city => ({ name: city })); console.log(citiesObj); const responder = num => cb => cb(num * 3); responder(5)(result => console.log(result));
198bce65d792f722df5a682dec94e06e34508d46
[ "JavaScript", "Markdown" ]
14
JavaScript
alpcanaydin/devizmir-node
f3e9f87aae7a919af7e0e846d665114acd600d2b
bcfd61420c719f8793fd1bf0c8dfcf4de6293b1d
refs/heads/main
<repo_name>shaw1001/helper<file_sep>/jdresource/jx_sign.js const notify = $.isNode() ? require('./sendNotify') : ''; //Node.js用户请在jdCookie.js处填写京东ck; const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; let jdNotify = true;//是否关闭通知,false打开通知推送,true关闭通知推送 //IOS等用户直接用NobyDa的jd cookie let cookiesArr = [], cookie = '', message; let helpAuthor = false let task; if ($.isNode()) { Object.keys(jdCookieNode).forEach((item) => { cookiesArr.push(jdCookieNode[item]) }) if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') that.log = () => {}; } else { cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); } const JD_API_HOST = 'https://m.jingxi.com/'; !(async () => { if (!cookiesArr[0]) { $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', {"open-url": "https://bean.m.jd.com/bean/signIndex.action"}); return; } $.newShareCodes = [] // await getAuthorShareCode(); for (let i = 0; i < cookiesArr.length; i++) { if (cookiesArr[i]) { cookie = cookiesArr[i]; $.UserName = decodeURIComponent(cookie.match(/pt_pin=(.+?);/) && cookie.match(/pt_pin=(.+?);/)[1]) $.index = i + 1; $.isLogin = true; $.nickName = ''; message = ''; await TotalBean(); that.log(`\n******开始【京东账号${$.index}】${$.nickName || $.UserName}*********\n`); if (!$.isLogin) { $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, {"open-url": "https://bean.m.jd.com/bean/signIndex.action"}); if ($.isNode()) { await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); } continue } await jdCash() } } })() .catch((e) => { $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') }) .finally(() => { $.done(); }) async function jdCash() { $.coins = 0 $.money = 0 await sign() await getTaskList() await doubleSign() await showMsg() } function sign() { return new Promise((resolve) => { $.get(taskUrl("pgcenter/sign/UserSignOpr"), async (err, resp, data) => { try { if (err) { that.log(`${JSON.stringify(err)}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { if (safeGet(data)) { data = JSON.parse(data); if(data.retCode ===0){ if(data.data.signStatus===0){ that.log(`签到成功,获得${data.data.pingoujin}金币,已签到${data.data.signDays}天`) $.coins += parseInt(data.data.pingoujin) }else{ that.log(`今日已签到`) } }else{ that.log(`签到失败,错误信息${data.errMsg}`) } } } } catch (e) { $.logErr(e, resp) } finally { resolve(data); } }) }) } function getTaskList() { return new Promise((resolve) => { $.get(taskUrl("pgcenter/task/QueryPgTaskCfgByType","taskType=3"), async (err, resp, data) => { try { if (err) { that.log(`${JSON.stringify(err)}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { if (safeGet(data)) { data = JSON.parse(data); if(data.retCode ===0){ for (task of data.data.tasks) { if(task.taskState===1){ that.log(`去做${task.taskName}任务`) await doTask(task.taskId); await $.wait(1000) await finishTask(task.taskId); await $.wait(1000) } } }else{ that.log(`签到失败,错误信息${data.errMsg}`) } } } } catch (e) { $.logErr(e, resp) } finally { resolve(data); } }) }) } function doTask(id) { return new Promise((resolve) => { $.get(taskUrl("pgcenter/task/drawUserTask",`taskid=${id}`), async (err, resp, data) => { try { if (err) { that.log(`${JSON.stringify(err)}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { if (safeGet(data)) { data = JSON.parse(data); if(data.retCode ===0){ that.log(`任务领取成功`) }else{ that.log(`任务完成失败,错误信息${data.errMsg}`) } } } } catch (e) { $.logErr(e, resp) } finally { resolve(data); } }) }) } function finishTask(id) { return new Promise((resolve) => { $.get(taskUrl("pgcenter/task/UserTaskFinish",`taskid=${id}`), async (err, resp, data) => { try { if (err) { that.log(`${JSON.stringify(err)}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { if (safeGet(data)) { data = JSON.parse(data); if(data.retCode ===0){ that.log(`任务完成成功,获得金币${data.datas[0]['pingouJin']}`) $.coins += data.datas[0]['pingouJin'] }else{ that.log(`任务完成失败,错误信息${data.errMsg}`) } } } } catch (e) { $.logErr(e, resp) } finally { resolve(data); } }) }) } function doubleSign() { return new Promise((resolve) => { $.get(taskUrl("double_sign/IssueReward",), async (err, resp, data) => { try { if (err) { that.log(`${JSON.stringify(err)}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { if (safeGet(data)) { data = JSON.parse(data); if(data.retCode ===0){ that.log(`双签成功,获得金币${data.data.jd_amount / 100}元`) $.money += data.data.jd_amount / 100 }else{ that.log(`任务完成失败,错误信息${data.errMsg}`) } } } } catch (e) { $.logErr(e, resp) } finally { resolve(data); } }) }) } function showMsg() { message+=`本次运行获得金币${$.coins},现金${$.money}` return new Promise(resolve => { if (!jdNotify) { $.msg($.name, '', `${message}`); } else { $.log(`京东账号${$.index}${$.nickName}\n${message}`); } resolve() }) } function taskUrl(functionId, body = '') { return { url: `${JD_API_HOST}${functionId}?sceneval=2&g_login_type=1&g_ty=ls&${body}`, headers: { 'Cookie': cookie, 'Host': 'm.jingxi.com', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'https://jddx.jd.com/m/jddnew/money/index.html', 'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.2.2;14.2;%E4%BA%AC%E4%B8%9C/9.2.2 CFNetwork/1206 Darwin/20.1.0"), 'Accept-Language': 'zh-cn', 'Accept-Encoding': 'gzip, deflate, br', } } } function TotalBean() { return new Promise(async resolve => { const options = { "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, "headers": { "Accept": "application/json,text/plain, */*", "Content-Type": "application/x-www-form-urlencoded", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-cn", "Connection": "keep-alive", "Cookie": cookie, "Referer": "https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2", "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.2.2;14.2;%E4%BA%AC%E4%B8%9C/9.2.2 CFNetwork/1206 Darwin/20.1.0") } } $.post(options, (err, resp, data) => { try { if (err) { that.log(`${JSON.stringify(err)}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { if (data) { data = JSON.parse(data); if (data['retcode'] === 13) { $.isLogin = false; //cookie过期 return } if (data['retcode'] === 0) { $.nickName = data['base'].nickname; } else { $.nickName = $.UserName } } else { that.log(`京东服务器返回空数据`) } } } catch (e) { $.logErr(e, resp) } finally { resolve(); } }) }) } function safeGet(data) { try { if (typeof JSON.parse(data) == "object") { return true; } } catch (e) { that.log(e); that.log(`京东服务器访问数据为空,请检查自身设备网络情况`); return false; } } function jsonParse(str) { if (typeof str == "string") { try { return JSON.parse(str); } catch (e) { that.log(e); $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie') return []; } } }<file_sep>/script/jd_try.js let cookiesArr = [], cookie = '', jdNotify = false, jdDebug = false, notify const selfdomain = 'https://try.m.jd.com' let allGoodList = [] // default params $.pageSize = 12 let cidsList = ["家用电器", "手机数码", "电脑办公", "家居家装"] let typeList = ["普通试用", "闪电试用"] let goodFilters = "教程@软件@英语@辅导@培训@手机卡".split('@') let minPrice = 0 const cidsMap = { "全部商品": "0", "家用电器": "737", "手机数码": "652,9987", "电脑办公": "670", "家居家装": "1620,6728,9847,9855,6196,15248,14065", "美妆护肤": "1316", "服饰鞋包": "1315,1672,1318,11729", "母婴玩具": "1319,6233", "生鲜美食": "12218", "图书音像": "1713,4051,4052,4053,7191,7192,5272", "钟表奢品": "5025,6144", "个人护理": "16750", "家庭清洁": "15901", "食品饮料": "1320,12259", "更多惊喜": "4938,13314,6994,9192,12473,6196,5272,12379,13678,15083,15126,15980", } const typeMap = { "全部试用": "0", "普通试用": "1", "闪电试用": "2", "30天试用": "5", } !(async () => { await requireConfig() if (!cookiesArr[0]) { $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/', { "open-url": "https://bean.m.jd.com/" }) return } for (let i = 0; i < cookiesArr.length; i++) { if (cookiesArr[i]) { cookie = cookiesArr[i]; $.UserName = decodeURIComponent(cookie.match(/pt_pin=(.+?);/) && cookie.match(/pt_pin=(.+?);/)[1]) $.index = i + 1; $.isLogin = true; $.nickName = ''; await TotalBean(); that.log(`\n开始【京东账号${$.index}】${$.nickName || $.UserName}\n`); if (!$.isLogin) { $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { "open-url": "https://bean.m.jd.com/bean/signIndex.action" }); if ($.isNode()) { await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); } continue } $.goodList = [] $.successList = [] if(allGoodList.length == 0){ await getGoodList() } await filterGoodList() $.totalTry = 0 $.totalGoods = $.goodList.length await tryGoodList() await getSuccessList() await showMsg() } } })() .catch((e) => { that.log(`❗️ ${$.name} 运行错误!\n${e}`) if (eval(jdDebug)) $.msg($.name, ``, `${e}`) }).finally(() => $.done()) function requireConfig() { return new Promise(resolve => { that.log('开始获取配置文件\n') notify = $.isNode() ? require('./sendNotify') : ''; //Node.js用户请在jdCookie.js处填写京东ck; if ($.isNode()) { const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; Object.keys(jdCookieNode).forEach((item) => { if (jdCookieNode[item]) { cookiesArr.push(jdCookieNode[item]) } }) if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') that.log = () => {}; } else { //IOS等用户直接用NobyDa的jd cookie let cookiesData = $.getdata('CookiesJD') || "[]"; cookiesData = jsonParse(cookiesData); cookiesArr = cookiesData.map(item => item.cookie); cookiesArr.reverse(); cookiesArr.push(...[$.getdata('CookieJD2'), $.getdata('CookieJD')]); cookiesArr.reverse(); cookiesArr = cookiesArr.filter(item => item !== "" && item !== null && item !== undefined); } that.log(`共${cookiesArr.length}个京东账号\n`) if ($.isNode()) { if (process.env.JD_TRY_CIDS_KEYS) { cidsList = process.env.JD_TRY_CIDS_KEYS.split('@').filter(key=>{ return Object.keys(cidsMap).includes(key) }) } if (process.env.JD_TRY_TYPE_KEYS) { typeList = process.env.JD_TRY_CIDS_KEYS.split('@').filter(key=>{ return Object.keys(typeMap).includes(key) }) } if(process.env.JD_TRY_GOOD_FILTERS){ goodFilters = process.env.JD_TRY_GOOD_FILTERS.split('@') } if (process.env.JD_TRY_MIN_PRICE) { minPrice = process.env.JD_TRY_MIN_PRICE * 1 } if (process.env.JD_TRY_PAGE_SIZE) { $.pageSize = process.env.JD_TRY_PAGE_SIZE * 1 } } else { let qxCidsList = [] let qxTypeList = [] const cidsKeys = Object.keys(cidsMap) const typeKeys = Object.keys(typeMap) for (let key of cidsKeys) { const open = $.getdata(key) if (open == 'true') qxCidsList.push(key) } for (let key of typeKeys) { const open = $.getdata(key) if (open == 'true') qxTypeList.push(key) } if (qxCidsList.length != 0) cidsList = qxCidsList if (qxTypeList.length != 0) typeList = qxTypeList if ($.getdata('filter')) goodFilters = $.getdata('filter').split('&') if ($.getdata('min_price')) minPrice = Number($.getdata('min_price')) if ($.getdata('page_size')) $.pageSize = Number($.getdata('page_size')) if ($.pageSize == 0) $.pageSize = 12 } resolve() }) } function getGoodListByCond(cids, page, pageSize, type, state) { return new Promise((resolve, reject) => { let option = taskurl(`${selfdomain}/activity/list?pb=1&cids=${cids}&page=${page}&pageSize=${pageSize}&type=${type}&state=${state}`) delete option.headers['Cookie'] $.get(option, (err, resp, data) => { try { if (err) { that.log(`🚫 ${arguments.callee.name.toString()} API请求失败,请检查网路\n${JSON.stringify(err)}`) } else { data = JSON.parse(data) if (data.success) { $.totalPages = data.data.pages allGoodList = allGoodList.concat(data.data.data) } else { that.log(`💩 获得 ${cids} ${page} 列表失败: ${data.message}`) } } } catch (e) { reject(`⚠️ ${arguments.callee.name.toString()} API返回结果解析出错\n${e}\n${JSON.stringify(data)}`) } finally { resolve() } }) }) } async function getGoodList() { if (cidsList.length === 0) cidsList.push("全部商品") if (typeList.length === 0) typeList.push("全部试用") for (let cidsKey of cidsList) { for (let typeKey of typeList) { if (!cidsMap.hasOwnProperty(cidsKey) || !typeMap.hasOwnProperty(typeKey)) continue that.log(`⏰ 获取 ${cidsKey} ${typeKey} 商品列表`) $.totalPages = 1 for (let page = 1; page <= $.totalPages; page++) { await getGoodListByCond(cidsMap[cidsKey], page, $.pageSize, typeMap[typeKey], '0') } } } } async function filterGoodList() { that.log(`⏰ 过滤商品列表,当前共有${allGoodList.length}个商品`) const now = Date.now() const oneMoreDay = now + 24 * 60 * 60 * 1000 $.goodList = allGoodList.filter(good => { // 1. good 有问题 // 2. good 距离结束不到10min // 3. good 的结束时间大于一天 // 4. good 的价格小于最小的限制 if (!good || good.endTime < now + 10 * 60 * 1000 || good.endTime > oneMoreDay || good.jdPrice < minPrice) { return false } for (let item of goodFilters) { if (good.trialName.indexOf(item) != -1) return false } return true }) await getApplyStateByActivityIds() $.goodList = $.goodList.sort((a, b) => { return b.jdPrice - a.jdPrice }) } async function getApplyStateByActivityIds() { function opt(ids) { return new Promise((resolve, reject) => { $.get(taskurl(`${selfdomain}/getApplyStateByActivityIds?activityIds=${ids.join(',')}`), (err, resp, data) => { try { if (err) { that.log(`🚫 ${arguments.callee.name.toString()} API请求失败,请检查网路\n${JSON.stringify(err)}`) } else { data = JSON.parse(data) ids.length = 0 for (let apply of data) ids.push(apply.activityId) } } catch (e) { reject(`⚠️ ${arguments.callee.name.toString()} API返回结果解析出错\n${e}\n${JSON.stringify(data)}`) } finally { $.goodList = $.goodList.filter(good => { for (let id of ids) { if (id == good.id) { return false } } return true }) resolve() } }) }) } let list = [] for (let good of $.goodList) { list.push(good.id) if (list.length == $.pageSize) { await opt(list) list.length = 0 } } if (list.length) await opt(list) } function canTry(good) { return new Promise((resolve, reject) => { let ret = false $.get(taskurl(`${selfdomain}/activity?id=${good.id}`), (err, resp, data) => { try { if (err) { that.log(`🚫 ${arguments.callee.name.toString()} API请求失败,请检查网路\n${JSON.stringify(err)}`) } else { ret = data.indexOf('trySku') != -1 let result = data.match(/"shopId":(\d+)/) if (result) { good.shopId = eval(result[1]) } } } catch (e) { reject(`⚠️ ${arguments.callee.name.toString()} API返回结果解析出错\n${e}\n${JSON.stringify(data)}`) } finally { resolve(ret) } }) }) } function isFollowed(good) { return new Promise((resolve, reject) => { $.get(taskurl(`${selfdomain}/isFollowed?id=${good.shopId}`, good.id), (err, resp, data) => { try { if (err) { that.log(`🚫 ${arguments.callee.name.toString()} API请求失败,请检查网路\n${JSON.stringify(err)}`) } else { data = JSON.parse(data) resolve(data.success && data.data) } } catch (e) { reject(`⚠️ ${arguments.callee.name.toString()} API返回结果解析出错\n${e}\n${JSON.stringify(data)}`) } finally { resolve(false) } }) }) } function followShop(good) { return new Promise((resolve, reject) => { $.get(taskurl(`${selfdomain}/followShop?id=${good.shopId}`, good.id), (err, resp, data) => { try { if (err) { that.log(`🚫 ${arguments.callee.name.toString()} API请求失败,请检查网路\n${JSON.stringify(err)}`) } else { data = JSON.parse(data) if (data.code == 'F0410') { $.running = false $.stopMsg = data.msg || "关注数超过上限了哦~先清理下关注列表吧" } resolve(data.success && data.data) } } catch (e) { reject(`⚠️ ${arguments.callee.name.toString()} API返回结果解析出错\n${e}\n${JSON.stringify(data)}`) } finally { resolve(false) } }) }) } async function tryGoodList() { that.log(`⏰ 即将申请 ${$.goodList.length} 个商品`) $.running = true $.stopMsg = '申请完毕' for (let i = 0; i < $.goodList.length && $.running; i++) { let good = $.goodList[i] if (!await canTry(good)) continue // 如果没有关注且关注失败 if (good.shopId && !await isFollowed(good) && !await followShop(good)) continue // 两个申请间隔不能太短,放在下面有利于确保 follwShop 完成 await $.wait(5000) // 关注完毕,即将试用 await doTry(good) } } async function doTry(good) { return new Promise((resolve, reject) => { $.get(taskurl(`${selfdomain}/migrate/apply?activityId=${good.id}&source=1&_s=m`, good.id), (err, resp, data) => { try { if (err) { that.log(`🚫 ${arguments.callee.name.toString()} API请求失败,请检查网路\n${JSON.stringify(err)}`) } else { data = JSON.parse(data) if (data.success) { $.totalTry += 1 that.log(`🥳 ${good.id} 🛒${good.trialName.substr(0,15)}🛒 ${data.message}`) } else if (data.code == '-131') { // 每日300个商品 $.stopMsg = data.message $.running = false } else { that.log(`🤬 ${good.id} 🛒${good.trialName.substr(0,15)}🛒 ${JSON.stringify(data)}`) } } } catch (e) { reject(`⚠️ ${arguments.callee.name.toString()} API返回结果解析出错\n${e}\n${JSON.stringify(data)}`) } finally { resolve() } }) }) } async function getSuccessList() { // 一页12个商品,不会吧不会吧,不会有人一次性中奖12个商品吧?!🤔 return new Promise((resolve, reject) => { const option = { url: `https://try.jd.com/my/tryList?selected=2&page=1&tryVersion=2&_s=m`, headers: { 'Host': 'try.jd.com', 'Connection': 'keep-alive', 'UserAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1', 'Accept': '*/*', 'Referer': 'https://try.m.jd.com/', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh,zh-CN;q=0.9,en;q=0.8', 'Cookie': cookie } } $.get(option, (err, resp, data) => { try { if (err) { that.log(`🚫 ${arguments.callee.name.toString()} API请求失败,请检查网路\n${JSON.stringify(err)}`) } else { data = JSON.parse(data) if (data.success && data.data) { $.successList = data.data.data.filter(item => { return item.text.text.indexOf('请尽快领取') != -1 }) } else { that.log(`💩 获得成功列表失败: ${data.message}`) } } } catch (e) { reject(`⚠️ ${arguments.callee.name.toString()} API返回结果解析出错\n${e}\n${JSON.stringify(data)}`) } finally { resolve() } }) }) } async function showMsg() { let message = `京东账号${$.index} ${$.nickName || $.UserName}\n🎉 本次申请:${$.totalTry}/${$.totalGoods}个商品🛒\n🎉 ${$.successList.length}个商品待领取🤩\n🎉 结束原因:${$.stopMsg}` if (!jdNotify || jdNotify === 'false') { $.msg($.name, ``, message, { "open-url": 'https://try.m.jd.com/user' }) if($.isNode()){ await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName}`, message) } } else { that.log(message) } } function taskurl(url, goodId) { return { 'url': url, 'headers': { 'Host': 'try.m.jd.com', 'Accept-Encoding': 'gzip, deflate, br', 'Cookie': cookie, 'Connection': 'keep-alive', 'Accept': '*/*', 'UserAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1', 'Accept-Language': 'zh-cn', 'Referer': goodId ? `https://try.m.jd.com/activity/?id=${goodId}` : undefined }, } } function TotalBean() { return new Promise(async resolve => { const options = { "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, "headers": { "Accept": "application/json,text/plain, */*", "Content-Type": "application/x-www-form-urlencoded", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-cn", "Connection": "keep-alive", "Cookie": cookie, "Referer": "https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2", "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.2.2;14.2;%E4%BA%AC%E4%B8%9C/9.2.2 CFNetwork/1206 Darwin/20.1.0") }, "timeout": 10000, } $.post(options, (err, resp, data) => { try { if (err) { that.log(`${JSON.stringify(err)}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { if (data) { data = JSON.parse(data); if (data['retcode'] === 13) { $.isLogin = false; //cookie过期 return } //$.nickName = data['base'].nickname; if (data['retcode'] === 0) { $.nickName = (data['base'] && data['base'].nickname) || $.UserName; } else { $.nickName = $.UserName } } else { that.log(`京东服务器返回空数据`) } } } catch (e) { $.logErr(e, resp) } finally { resolve(); } }) }) } function jsonParse(str) { if (typeof str == "string") { try { return JSON.parse(str); } catch (e) { that.log(e); $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie') return []; } } } <file_sep>/jdresource/jd_nzmh.js const notify = $.isNode() ? require('./sendNotify') : ''; const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; //Node.js用户请在jdCookie.js处填写京东ck; //IOS等用户直接用NobyDa的jd cookie let cookiesArr = [], cookie = '', message; if ($.isNode()) { Object.keys(jdCookieNode).forEach((item) => { cookiesArr.push(jdCookieNode[item]) }) if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') that.log = () => { }; } else { cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); } !(async () => { if (!cookiesArr[0]) { $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/', {"open-url": "https://bean.m.jd.com/"}); return; } for (let i = 0; i < cookiesArr.length; i++) { if (cookiesArr[i]) { cookie = cookiesArr[i]; $.UserName = decodeURIComponent(cookie.match(/pt_pin=(.+?);/) && cookie.match(/pt_pin=(.+?);/)[1]) $.index = i + 1; $.isLogin = true; $.nickName = ''; $.beans = 0 message = ''; await TotalBean(); that.log(`\n******开始【京东账号${$.index}】${$.nickName || $.UserName}*********\n`); if (!$.isLogin) { $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/`, {"open-url": "https://bean.m.jd.com/"}); if ($.isNode()) { await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); } else { $.setdata('', `CookieJD${i ? i + 1 : ""}`);//cookie失效,故清空cookie。$.setdata('', `CookieJD${i ? i + 1 : "" }`);//cookie失效,故清空cookie。 } continue } try { await jdMh('https://h5.m.jd.com/babelDiy/Zeus/3eeruLXVbXge6CexVq8XkBbBvAfy/index.html') } catch (e) { $.logErr(e) } } } })() .catch((e) => { $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') }) .finally(() => { $.done(); }) async function jdMh(url) { try { await getInfo(url) await getUserInfo() await draw() while ($.userInfo.bless >= $.userInfo.cost_bless_one_time) { await draw() await getUserInfo() await $.wait(500) } await showMsg(); } catch (e) { $.logErr(e) } } function showMsg() { return new Promise(resolve => { message += `本次运行获得${$.beans}京豆` $.msg($.name, '', `京东账号${$.index}${$.nickName}\n${message}`); resolve() }) } function getInfo(url = 'https://anmp.jd.com/babelDiy/Zeus/3DSHPs2xC66RgcCEB8YVLsudqfh5/index.html?wxAppName=jd') { that.log(`url:${url}`) return new Promise(resolve => { $.get({ url, headers: { Cookie: cookie } }, (err, resp, data) => { try { $.info = JSON.parse(data.match(/var snsConfig = (.*)/)[1]) $.prize = JSON.parse($.info.prize) resolve() } catch (e) { that.log(e) } }) }) } function getUserInfo() { return new Promise(resolve => { $.get(taskUrl('query'), async (err, resp, data) => { try { if (err) { that.log(`${err},${jsonParse(resp.body)['message']}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { $.userInfo = JSON.parse(data.match(/query\((.*)\n/)[1]).data // that.log(`您的好友助力码为${$.userInfo.shareid}`) that.log(`当前幸运值:${$.userInfo.bless}`) for (let task of $.info.config.tasks) { if (!$.userInfo.complete_task_list.includes(task['_id'])) { that.log(`去做任务${task['_id']}`) await doTask(task['_id']) await $.wait(500) } } } } catch (e) { $.logErr(e, resp) } finally { resolve(data); } }) }) } function doTask(taskId) { let body = `task_bless=10&taskid=${taskId}` return new Promise(resolve => { $.get(taskUrl('completeTask', body), async (err, resp, data) => { try { if (err) { that.log(`${err},${jsonParse(resp.body)['message']}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { data = JSON.parse(data.match(/query\((.*)\n/)[1]) if (data.data.complete_task_list.includes(taskId)) { that.log(`任务完成成功,当前幸运值${data.data.curbless}`) $.userInfo.bless = data.data.curbless } } } catch (e) { $.logErr(e, resp) } finally { resolve(data); } }) }) } function draw() { return new Promise(resolve => { $.get(taskUrl('draw'), async (err, resp, data) => { try { if (err) { that.log(`${err},${jsonParse(resp.body)['message']}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { data = JSON.parse(data.match(/query\((.*)\n/)[1]) if (data.data && data.data.drawflag) { if ($.prize.filter(vo => vo.prizeLevel === data.data.level).length > 0) { that.log(`获得${$.prize.filter(vo => vo.prizeLevel === data.data.level)[0].prizename}`) $.beans += $.prize.filter(vo => vo.prizeLevel === data.data.level)[0].beansPerNum } } } } catch (e) { $.logErr(e, resp) } finally { resolve(data); } }) }) } function taskUrl(function_id, body = '') { body = `activeid=${$.info.activeId}&token=${$.info.actToken}&sceneval=2&shareid=&_=${new Date().getTime()}&callback=query&${body}` return { url: `https://wq.jd.com/activet2/piggybank/${function_id}?${body}`, headers: { 'Host': 'wq.jd.com', 'Accept': 'application/json', 'Accept-Language': 'zh-cn', 'Content-Type': 'application/json;charset=utf-8', 'Origin': 'wq.jd.com', 'User-Agent': 'JD4iPhone/167490 (iPhone; iOS 14.2; Scale/3.00)', 'Referer': `https://anmp.jd.com/babelDiy/Zeus/xKACpgVjVJM7zPKbd5AGCij5yV9/index.html?wxAppName=jd`, 'Cookie': cookie } } } function TotalBean() { return new Promise(async resolve => { const options = { "url": `https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2`, "headers": { "Accept": "application/json,text/plain, */*", "Content-Type": "application/x-www-form-urlencoded", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-cn", "Connection": "keep-alive", "Cookie": cookie, "Referer": "https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2", "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : "JD4iPhone/9.3.5 CFNetwork/1209 Darwin/20.2.0") : ($.getdata('JDUA') ? $.getdata('JDUA') : "JD4iPhone/9.3.5 CFNetwork/1209 Darwin/20.2.0") } } $.post(options, (err, resp, data) => { try { if (err) { that.log(`${JSON.stringify(err)}`) that.log(`${$.name} API请求失败,请检查网路重试`) } else { if (data) { data = JSON.parse(data); if (data['retcode'] === 13) { $.isLogin = false; //cookie过期 return } if (data['retcode'] === 0) { $.nickName = (data['base'] && data['base'].nickname) || $.UserName; } else { $.nickName = $.UserName } } else { that.log(`京东服务器返回空数据`) } } } catch (e) { $.logErr(e, resp) } finally { resolve(); } }) }) } function safeGet(data) { try { if (typeof JSON.parse(data) == "object") { return true; } } catch (e) { that.log(e); that.log(`京东服务器访问数据为空,请检查自身设备网络情况`); return false; } } function jsonParse(str) { if (typeof str == "string") { try { return JSON.parse(str); } catch (e) { that.log(e); $.msg($.name, '', '不要在BoxJS手动复制粘贴修改cookie') return []; } } } <file_sep>/jdresource/jx_mc.js /** * Name: 京喜牧场 Address: 京喜App -> 我的 -> 京喜牧场 Author: MoPoQAQ Created:2021/6/4 23:30 Updated: 2021/6/7 22:30 Thanks: https://github.com/whyour https://www.orzlee.com/web-development/2021/03/03/lxk0301-jingdong-signin-scriptjingxi-factory-solves-the-problem-of-unable-to-signin.html !!!先将新手任务做完,再执行本脚本,不然会出现未知错误 cron表达式 0 * * * * 或者 0 0 * * * * hostname = m.jingxi.com BoxJS订阅 https://raw.githubusercontent.com/whyour/hundun/master/quanx/whyour.boxjs.json * **/ const JD_API_HOST = "https://m.jingxi.com"; const notify = $.isNode() ? require('./sendNotify') : ''; const jdCookieNode = $.isNode() ? require("./jdCookie.js") : ""; $.showLog = $.getdata("mc_showLog") ? $.getdata("mc_showLog") === "true" : false; $.result = []; $.cookieArr = []; $.currentCookie = ''; $.petid = []; $.allTask = []; $.appId = 10028; !(async () => { if (!getCookies()) return; await requestAlgo(); for (let i = 0; i < $.cookieArr.length; i++) { $.currentCookie = $.cookieArr[i]; if ($.currentCookie) { $.userName = decodeURIComponent($.currentCookie.match(/pt_pin=(.+?);/) && $.currentCookie.match(/pt_pin=(.+?);/)[1]); $.index = i + 1; $.log(`\n开始【京东账号${i + 1}】${$.userName}`); const homepageinfo = await GetHomePageInfo(); // 领取金币 await $.wait(500); await GetCoin(homepageinfo); // 获取成就任务列表 await $.wait(500); await GetUserTaskStatusList(1); await $.wait(500); await Award(); // 获取每日任务列表(待完成) await $.wait(500); await GetUserTaskStatusList(3); await $.wait(500); await DoTask(); // 获取每日任务列表(待领取) await $.wait(500); await GetUserTaskStatusList(2); await $.wait(500); await Award(); // 购物 await $.wait(500); await UseCoin(homepageinfo) // 领金蛋 await $.wait(500); await GetSelfResult(homepageinfo); // 喂食 await $.wait(500); await Feed(homepageinfo); } } await $.wait(500); await showMsg(); })().catch((e) => $.logErr(e)) .finally(() => $.done()); // 获取主要信息 function GetHomePageInfo() { return new Promise(async (resolve) => { $.get(taskUrl(`queryservice/GetHomePageInfo`, ``), async (err, resp, _data) => { try { // 格式化JSON数据 // _data = _data.replace("jsonpCBKJJJ(", ""); // _data = _data.substring(0, _data.length - 1); //$.log(_data); const { data: { cockinfo = {}, // 孵化小鸡信息 coins, // 金币数量 cow = {}, // 牛牛信息 eggcnt, // 当前可用金蛋数量 hatchboxinfo, // 孵化箱信息 materialinfo = [], // 原材料信息,1: 白菜 nickname, // 用户昵称 petinfo = [], // 小鸡信息 }, message, ret } = JSON.parse(_data); $.log(`\n【获取用户信息📝】:${message}\n${$.showLog ? _data : ""}`); // 小鸡id编号列表 $.petid = petinfo.filter(x => x.status == 1).map(x => x.petid); //$.log($.petid); resolve({ cockinfo, coins, cow, eggcnt, hatchboxinfo, materialinfo, nickname, petinfo, }); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); }); } // 获取每日任务和成就任务列表 function GetUserTaskStatusList(taskType) { return new Promise(async (resolve) => { switch (taskType) { case 1: // 成就任务 $.get(taskListUrl(`GetUserTaskStatusList`, `&dateType=1`), async (err, resp, _data) => { try { //$.log(_data); const { data: { userTaskStatusList = [] } = {}, msg, ret } = JSON.parse(_data); $.allTask = userTaskStatusList.filter(x => x.awardStatus === 2 && x.completedTimes === x.targetTimes); $.log(`\n获取【🎖 成就任务】列表 ${msg},总共${$.allTask.length}个任务!\n${$.showLog ? data : ""}`); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); break; case 2: // 每日任务(领取奖励) $.get(taskListUrl(`GetUserTaskStatusList`, `&dateType=2`), async (err, resp, _data) => { try { //$.log(_data); const { data: { userTaskStatusList = [] } = {}, msg, ret } = JSON.parse(_data); $.allTask = userTaskStatusList.filter(x => x.awardStatus === 2 && x.completedTimes === x.targetTimes); $.log(`\n获取【📆 每日任务(待领取奖励)】列表 ${msg},总共${$.allTask.length}个任务!\n${$.showLog ? data : ""}`); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); break; case 3: // 每日任务(做任务) $.get(taskListUrl(`GetUserTaskStatusList`, `&dateType=2`), async (err, resp, _data) => { try { //$.log(_data); const { data: { userTaskStatusList = [] } = {}, msg, ret } = JSON.parse(_data); $.allTask = userTaskStatusList.filter(x => x.awardStatus === 2 && x.taskCaller === 1 && x.completedTimes != x.targetTimes); $.log(`\n获取【📆 每日任务(待完成)】列表 ${msg},总共${$.allTask.length}个任务!\n${$.showLog ? data : ""}`); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); break; default: break; } }); } // 完成每日任务 function DoTask() { return new Promise(async (resolve) => { if ($.allTask.length > 0) { for (let i = 0; i < $.allTask.length; i++) { const { description, taskId } = $.allTask[i]; $.get(taskListUrl(`DoTask`, `&taskId=${taskId}&configExtra=`, 'bizCode,configExtra,source,taskId'), async (err, resp, _data) => { try { const { data, msg, ret } = JSON.parse(_data); //$.log(_data); if (ret === 0) $.log(`\n【${description}🗒️】 任务 完成`); else $.log(`\n【${description}🗒️】 任务 未完成,${msg}`); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); } } else { resolve(); } }); } // 领取日常任务和成就任务奖励 function Award() { return new Promise(async (resolve) => { if ($.allTask.length > 0) { for (let i = 0; i < $.allTask.length; i++) { const { description, reward, taskId } = $.allTask[i]; $.get(taskListUrl(`Award`, `&taskId=${taskId}`), async (err, resp, _data) => { try { const { data, msg, ret } = JSON.parse(_data); if (ret === 0) $.log(`\n【${description}💰】 任务奖励领取成功, 获得 ¥ ${reward}`); else $.log(`\n【${description}💰】 任务奖励领取失败 ${msg}`); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); } } else { resolve(); } }); } // 收取金币 function GetCoin(homepageinfo) { return new Promise(async (resolve) => { try { const { cow: { lastgettime, // 上一次获取时间 } = {}, } = homepageinfo; //$.log(lastgettime); const token = new MD5().MD5.createMD5String(lastgettime); $.get(taskUrl(`operservice/GetCoin`, `&token=${token}`, 'channel,sceneid,token'), async (err, resp, _data) => { try { // 格式化JSON数据 const { data: { addcoin, // 收获金币数量 } = {}, message, ret } = JSON.parse(_data); //$.log(_data); $.log(`【收取金币💰】 ${ret == 0 ? message + `共 ${addcoin} 个` : message} \n ${$.showMsg ? _data : ""} `); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); } catch (e) { $.log(`您还没有领取过金币,快去手动点击牛牛🐮,领取一次金币吧~`); $.logErr(e); } finally { resolve(); } }); } // 喂食 function Feed(homepageinfo) { return new Promise(async (resolve) => { try { const { materialinfo } = homepageinfo; //$.log(materialinfo); const info = materialinfo.filter(x => x.type === 1); const { value } = info[0]; //$.log(value); if (value >= 10) { $.get(taskUrl(`operservice/Feed`, ``, `channel,sceneid`), async (err, resp, _data) => { try { const { data, message, ret } = JSON.parse(_data); //$.log(_data); $.log(`【投喂🥬】${message},请加大力度~ \n ${$.showMsg ? _data : ""} `); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); } else { $.log("白菜不足,满10颗可喂养哦"); resolve(); } } catch (e) { $.log(e); } finally { resolve(); } }); } // 金币 // 买白菜 > 孵化小鸡 function UseCoin(homepageinfo) { return new Promise(async (resolve) => { const { coins } = homepageinfo; const CurrCoin = coins / 5000; //$.log(CurrCoin); if (CurrCoin >= 2) { await Buy(); resolve(); } else if (CurrCoin >= 1) { await Buy(); resolve(); } else { $.log("您的金币太少了,什么也不能买,赶快去打工赚金币吧~"); resolve(); } }); } // 购买白菜🥬 function Buy() { return new Promise(async (resolve) => { $.get(taskUrl(`operservice/Buy`, `&type=1`, 'channel,sceneid,type'), async (err, resp, _data) => { try { const { data: { newnum, usecoins, } = {}, message, ret } = JSON.parse(_data); //$.log(_data); $.log(`【购物🛒】 ${ret === 0 ? `${message},您消费了 ¥${usecoins}金币,当前您有${newnum}颗白菜🥬 ,快去喂小鸡崽子~` : message} \n ${$.showMsg ? _data : ""} `); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); }); } // 领金蛋 function GetSelfResult(homepageinfo) { return new Promise(async (resolve) => { const { petinfo } = homepageinfo; const info = petinfo.filter(x => x.progress === "0" && x.experience == x.lastborn); if (info.length > 0) { const { petid } = info[0]; $.get(taskUrl(`operservice/GetSelfResult`, `&type=11&itemid=${petid}`, 'channel,itemid,sceneid,type'), async (err, resp, _data) => { try { const { data: { addnum, newnum, } = {}, message, ret, } = JSON.parse(_data); //$.log(_data); $.log(`【领取金蛋🥚】 ${ret === 0 ? `${message},收获${addnum}个金蛋🥚,当前您拥有${newnum}个金蛋🥚,请加大力度~` : message} \n ${$.showMsg ? _data : ""} `); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }); } else { resolve(); } }); } function getCookies() { if ($.isNode()) { $.cookieArr = Object.values(jdCookieNode); } else { const CookiesJd = JSON.parse($.getdata("CookiesJD") || "[]").filter(x => !!x).map(x => x.cookie); $.cookieArr = [$.getdata("CookieJD") || "", $.getdata("CookieJD2") || "", ...CookiesJd]; } if (!$.cookieArr[0]) { $.msg( $.name, "【⏰提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取", "https://bean.m.jd.com/", { "open-url": "https://bean.m.jd.com/", } ); return false; } return true; } function taskUrl(function_path, body, stk) { let url = `${JD_API_HOST}/jxmc/${function_path}?channel=7&sceneid=1001${body}&_ste=1&_=${Date.now()}&sceneval=2&g_login_type=1&g_ty=ls`; if (stk) { url += `&_stk=${stk}`; } url += `&h5st=${decrypt(Date.now(), stk, '', url)}`; return { url, headers: { Cookie: $.currentCookie, Accept: "*/*", Connection: "keep-alive", Referer: "https://st.jingxi.com/pingou/jxmc/index.html?nativeConfig=%7B%22immersion%22%3A1%2C%22toColor%22%3A%22%23e62e0f%22%7D&;__mcwvt=sjcp&ptag=7155.9.95", "Accept-Encoding": "gzip, deflate, br", Host: "m.jingxi.com", "User-Agent": `jdpingou;iPhone;3.15.2;14.2.1;ea00763447803eb0f32045dcba629c248ea53bb3;network/wifi;model/iPhone13,2;appBuild/100365;ADID/00000000-0000-0000-0000-000000000000;supportApplePay/1;hasUPPay/0;pushNoticeIsOpen/0;hasOCPay/0;supportBestPay/0;session/${Math.random * 98 + 1};pap/JA2015_311210;brand/apple;supportJDSHWK/1;Mozilla/5.0 (iPhone; CPU iPhone OS 14_2_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148`, "Accept-Language": "zh-cn", }, }; } function taskListUrl(function_path, body, stk) { let url = `${JD_API_HOST}/newtasksys/newtasksys_front/${function_path}?_=${Date.now()}&source=jxmc&bizCode=jxmc${body}&_ste=1&sceneval=2&g_login_type=1&g_ty=ajax`; if (stk) { url += `&_stk=${stk}`; } //传入url进行签名,加入位置不要错了,不然有些签名参数获取不到值 url += `&h5st=${decrypt(Date.now(), stk, '', url)}`; return { url, headers: { Cookie: $.currentCookie, Accept: "application/json", Connection: "keep-alive", Referer: "https://st.jingxi.com/pingou/jxmc/index.html?nativeConfig=%7B%22immersion%22%3A1%2C%22toColor%22%3A%22%23e62e0f%22%7D&;__mcwvt=sjcp&ptag=7155.9.95", "Accept-Encoding": "gzip, deflate, br", Host: "m.jingxi.com", "User-Agent": `jdpingou;iPhone;3.15.2;14.2.1;ea00763447803eb0f32045dcba629c248ea53bb3;network/wifi;model/iPhone13,2;appBuild/100365;ADID/00000000-0000-0000-0000-000000000000;supportApplePay/1;hasUPPay/0;pushNoticeIsOpen/0;hasOCPay/0;supportBestPay/0;session/${Math.random * 98 + 1};pap/JA2015_311210;brand/apple;supportJDSHWK/1;Mozilla/5.0 (iPhone; CPU iPhone OS 14_2_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148`, "Accept-Language": "zh-cn", }, }; } function format(a, time) { if (!a) a = 'yyyy-MM-dd'; var t; if (!time) { t = Date.now(); } else { t = new Date(time); } var e, n = new Date(t), d = a, l = { 'M+': n.getMonth() + 1, 'd+': n.getDate(), 'D+': n.getDate(), 'h+': n.getHours(), 'H+': n.getHours(), 'm+': n.getMinutes(), 's+': n.getSeconds(), 'w+': n.getDay(), 'q+': Math.floor((n.getMonth() + 3) / 3), 'S+': n.getMilliseconds(), }; /(y+)/i.test(d) && (d = d.replace(RegExp.$1, ''.concat(n.getFullYear()).substr(4 - RegExp.$1.length))); Object.keys(l).forEach(e => { if (new RegExp('('.concat(e, ')')).test(d)) { var t, a = 'S+' === e ? '000' : '00'; d = d.replace(RegExp.$1, 1 == RegExp.$1.length ? l[e] : ''.concat(a).concat(l[e]).substr(''.concat(l[e]).length)); } }); return d; } function decrypt(time, stk, type, url) { stk = stk || (url ? getUrlQueryParams(url, '_stk') : '') if (stk) { const timestamp = format("yyyyMMddhhmmssSSS", time); const hash1 = $.genKey($.token, $.fp.toString(), timestamp.toString(), $.appId.toString(), $.CryptoJS).toString($.CryptoJS.enc.Hex); let st = ''; stk.split(',').map((item, index) => { st += `${item}:${getUrlQueryParams(url, item)}${index === stk.split(',').length - 1 ? '' : '&'}`; }) const hash2 = $.CryptoJS.HmacSHA256(st, hash1.toString()).toString($.CryptoJS.enc.Hex); return encodeURIComponent(["".concat(timestamp.toString()), "".concat($.fp.toString()), "".concat($.appId.toString()), "".concat($.token), "".concat(hash2)].join(";")) } else { return '20210606002748531;4629136822268161;10028;tk01w7fa61b91a8nZXZ0UG1KNThmCDX8l17vfUjeNgy4+H2KeBO7PAJg5C3LOayqxMrGk7NiEMey8Qbqc4vJavW0PfsI;d68f6925e50d7464177f0971ca5964fae13bd65faee1fbfd5900858e59a3e0b4' } } function getUrlQueryParams(url_string, param) { let reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)", "i"); let r = url_string.split('?')[1].substr(0).match(reg); if (r != null) { return decodeURIComponent(r[2]); }; return ''; } function getRandomIDPro() { var e, t, a = void 0 === (n = (t = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}).size) ? 10 : n, n = void 0 === (n = t.dictType) ? 'number' : n, i = ''; if ((t = t.customDict) && 'string' == typeof t) e = t; else switch (n) { case 'alphabet': e = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'max': e = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-'; break; case 'number': default: e = '0123456789'; } for (; a--;) i += e[(Math.random() * e.length) | 0]; return i; } async function requestAlgo() { $.fp = (getRandomIDPro({ size: 13 }) + Date.now()).slice(0, 16); const options = { "url": `https://cactus.jd.com/request_algo?g_ty=ajax`, headers: { 'Authority': 'cactus.jd.com', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Accept': 'application/json', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1', 'Content-Type': 'application/json', 'Origin': 'https://st.jingxi.com', 'Sec-Fetch-Site': 'cross-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://st.jingxi.com/', 'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7' }, 'body': JSON.stringify({ "version": "1.0", "fp": $.fp, "appId": $.appId, "timestamp": Date.now(), "platform": "web", "expandParams": "" }) } return new Promise(async resolve => { $.post(options, (err, resp, data) => { try { const { ret, msg, data: { result } = {} } = JSON.parse(data); $.token = result.tk; // $.genKey = new Function(`return ${result.algo}`)(); eval(result.algo+";$.genKey=test"); } catch (e) { $.logErr(e, resp); } finally { resolve(); } }) }) } function showMsg() { return new Promise(async (resolve) => { if ($.notifyTime) { const notifyTimes = $.notifyTime.split(",").map((x) => x.split(":")); const now = $.time("HH:mm").split(":"); $.log(`\n${JSON.stringify(notifyTimes)}`); $.log(`\n${JSON.stringify(now)}`); if (notifyTimes.some((x) => x[0] === now[0] && (!x[1] || x[1] === now[1]))) { $.msg($.name, "", `\n${$.result.join("\n")}`); } } else { $.msg($.name, "", `\n${$.result.join("\n")}`); } if ($.isNode() && process.env.CFD_NOTIFY_CONTROL === 'true') await notify.sendNotify(`${$.name} - 账号${$.index} - ${$.nickName}`, `账号${$.index}:${$.nickName || $.userName}\n${$.result.join("\n")}`); resolve(); }); } function MD5() { //创建并实例化MD5对象并让他可以调用自身方法 function MD5(string) { this._this = this; return this; } this.MD5 = new MD5; MD5.prototype.createMD5String = function (string) { var x = Array(); var k, AA, BB, CC, DD, a, b, c, d; var S11 = 7, S12 = 12, S13 = 17, S14 = 22; var S21 = 5, S22 = 9, S23 = 14, S24 = 20; var S31 = 4, S32 = 11, S33 = 16, S34 = 23; var S41 = 6, S42 = 10, S43 = 15, S44 = 21; string = uTF8Encode(string); x = convertToWordArray(string); a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; for (k = 0; k < x.length; k += 16) { AA = a; BB = b; CC = c; DD = d; a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478); d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756); c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB); b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE); a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF); d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A); c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613); b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501); a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8); d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF); c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1); b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE); a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122); d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193); c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E); b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821); a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562); d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340); c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51); b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA); a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D); d = GG(d, a, b, c, x[k + 10], S22, 0x2441453); c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681); b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8); a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6); d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6); c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87); b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED); a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905); d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8); c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9); b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A); a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942); d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681); c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122); b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C); a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44); d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9); c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60); b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70); a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6); d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA); c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085); b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05); a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039); d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5); c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8); b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665); a = II(a, b, c, d, x[k + 0], S41, 0xF4292244); d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97); c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7); b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039); a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3); d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92); c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D); b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1); a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F); d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0); c = II(c, d, a, b, x[k + 6], S43, 0xA3014314); b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1); a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82); d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235); c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB); b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391); a = addUnsigned(a, AA); b = addUnsigned(b, BB); c = addUnsigned(c, CC); d = addUnsigned(d, DD); } var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d); return tempValue.toLowerCase(); } var rotateLeft = function (lValue, iShiftBits) { return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); } var addUnsigned = function (lX, lY) { var lX4, lY4, lX8, lY8, lResult; lX8 = (lX & 0x80000000); lY8 = (lY & 0x80000000); lX4 = (lX & 0x40000000); lY4 = (lY & 0x40000000); lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF); if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8); if (lX4 | lY4) { if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); else return (lResult ^ 0x40000000 ^ lX8 ^ lY8); } else { return (lResult ^ lX8 ^ lY8); } } var F = function (x, y, z) { return (x & y) | ((~x) & z); } var G = function (x, y, z) { return (x & z) | (y & (~z)); } var H = function (x, y, z) { return (x ^ y ^ z); } var I = function (x, y, z) { return (y ^ (x | (~z))); } var FF = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); }; var GG = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); }; var HH = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); }; var II = function (a, b, c, d, x, s, ac) { a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); }; var convertToWordArray = function (string) { var lWordCount; var lMessageLength = string.length; var lNumberOfWordsTempOne = lMessageLength + 8; var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64; var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16; var lWordArray = Array(lNumberOfWords - 1); var lBytePosition = 0; var lByteCount = 0; while (lByteCount < lMessageLength) { lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition)); lByteCount++; } lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); lWordArray[lNumberOfWords - 2] = lMessageLength << 3; lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; return lWordArray; }; var wordToHex = function (lValue) { var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount; for (lCount = 0; lCount <= 3; lCount++) { lByte = (lValue >>> (lCount * 8)) & 255; WordToHexValueTemp = "0" + lByte.toString(16); WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2); } return WordToHexValue; }; var uTF8Encode = function (string) { string = string.toString().replace(/\x0d\x0a/g, "\x0a"); var output = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { output += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { output += String.fromCharCode((c >> 6) | 192); output += String.fromCharCode((c & 63) | 128); } else { output += String.fromCharCode((c >> 12) | 224); output += String.fromCharCode(((c >> 6) & 63) | 128); output += String.fromCharCode((c & 63) | 128); } } return output; }; }
5cb033b44d15bb90afb1aa54cbdf706571577fa0
[ "JavaScript" ]
4
JavaScript
shaw1001/helper
d80466a92acf63c3ae37854a3daa2ed8e1f3495d
9c8cd505d8dfdf829a99de9cdec119d135c1dfc5
refs/heads/master
<file_sep>const navToggleShowBtn = document.getElementById('navbar-toggler-show'); const navToggleCloseBtn = document.getElementById('navbar-toggler-close'); const navbarCollapseDiv = document.getElementById('navbar-collapse'); const navbarDiv = document.querySelector('.navbar'); navToggleShowBtn.addEventListener('click', () => { navbarCollapseDiv.style.display = "flex"; }); navToggleCloseBtn.addEventListener('click', () => { navbarCollapseDiv.style.display = "none"; }); // hide navbar window.addEventListener('scroll', () => { if(document.body.scrollTop > 100 || document.documentElement.scrollTop > 100){ navbarDiv.style.display = "none"; } else { navbarDiv.style.display = ""; } });
b9ec7b1e2fe0e3d9075a3350466e0612a48acb6f
[ "JavaScript" ]
1
JavaScript
prabinmagar/design-website-html-css
d6fee940a4b9c7ab36a6615bb597cee6677a23d6
6bd6b8e0bbc42729e0a2fb5116014324e27f6c7c
refs/heads/master
<file_sep>// // OneViewController.swift // Navigator // // Created by <NAME> on 10/9/17. // Copyright © 2017 HuiJing. All rights reserved. // import UIKit class OneViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "ONE" } } <file_sep>// // TwoViewController.swift // Navigator // // Created by <NAME> on 10/9/17. // Copyright © 2017 HuiJing. All rights reserved. // import UIKit class TwoViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "Two" // Do any additional setup after loading the view. } }
d49ac05380d0f98663581045a85ba56edba6ff76
[ "Swift" ]
2
Swift
huijing0024/Navigator
aac15c505d0cb4114500958f04515530464eeb96
3d7a1e1509fb3c998fb8f7c61bb83e3ab2128331
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using Dapper; using System.Data.Common; using System.Linq; using MySql.Data.MySqlClient; namespace ShopMall.Common { /// <summary> /// 数据层访问类 /// </summary> public class DbProvider : IDisposable { /// <summary> /// 初始化 /// </summary> public DbProvider() { } /// <summary> /// 保存连接字符串 /// </summary> private string m_ConnectionString = string.Empty; /// <summary> /// 开始事物 /// </summary> public void BeginTran() { m_DbConnection = CreateOpenConnection(); m_DbTransaction = m_DbConnection.BeginTransaction(); } /// <summary> /// 提交事务 /// </summary> public void CommitTran() { m_DbTransaction.Commit(); Dispose(); } /// <summary> /// 回滚 /// </summary> public void Rollback() { m_DbTransaction.Rollback(); Dispose(); } /// <summary> /// 数据库连接 /// </summary> private DbConnection m_DbConnection { set; get; } /// <summary> /// 事物 /// </summary> private DbTransaction m_DbTransaction { set; get; } /// <summary> /// 创建数据连接 /// </summary> /// <returns></returns> private DbConnection CreateOpenConnection() { try { //如果事物存在则返回现有连接 if (IsTran) { return m_DbConnection; } if (string.IsNullOrWhiteSpace(m_ConnectionString)) { m_ConnectionString = ConfigManager.ReadMySqlConnection; } m_DbConnection = new MySqlConnection(m_ConnectionString); m_DbConnection.Open(); return m_DbConnection; } catch (Exception ex) { throw ex; } } /// <summary> /// 关闭连接 /// </summary> private void CloseDbConnection() { if (m_DbConnection == null) { return; } if (!IsTran) { try { m_DbConnection.Close(); } catch { } } } /// <summary> /// 是否是在事务处理环境下 /// </summary> private bool IsTran { get { if (m_DbTransaction == null) { return false; } else { return true; } } } /// <summary> /// 执行并返回List对象 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public List<T> GetList<T>(DbModel p_DbModel) { var m_Connection = CreateOpenConnection(); var m_Result = m_Connection.Query<T>(p_DbModel.Sql.ToString(), p_DbModel.Parameters, m_DbTransaction); CloseDbConnection(); if (m_Result != null && m_Result.Count() > 0) { return (List<T>)m_Result.ToList(); } return new List<T>(); } /// <summary> /// 执行并返回对象 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T Get<T>(DbModel p_DbModel) { var m_Connection = CreateOpenConnection(); var m_Result = m_Connection.Query<T>(p_DbModel.Sql.ToString(), p_DbModel.Parameters, m_DbTransaction); CloseDbConnection(); if (m_Result != null && m_Result.Count() > 0) { return (T)m_Result.First(); } return default(T); } /// <summary> /// 执行并返回对象 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public void Execute(DbModel p_DbModel) { var m_Connection = CreateOpenConnection(); m_Connection.Execute(p_DbModel.Sql.ToString(), p_DbModel.Parameters, m_DbTransaction); CloseDbConnection(); } /// <summary> /// 执行并返回对象 /// </summary> /// <returns></returns> public void ExecuteZeroRowEx(DbModel p_DbModel) { p_DbModel.Sql.Append(@" SELECT ROW_COUNT();"); var m_Connection = CreateOpenConnection(); int m_Count = m_Connection.Query<int>(p_DbModel.Sql.ToString(), p_DbModel.Parameters).FirstOrDefault(); CloseDbConnection(); if (m_Count == 0) { ExHelper.Throw_DataBase_ZeroRowEx(); } } /// <summary> /// 分页 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="p_DbModel"></param> /// <returns></returns> public List<T> PageQuery<T>(DbModel p_DbModel) { string p_SelectSql_Page = string.Empty; if (string.IsNullOrWhiteSpace(p_DbModel.PageInfo.SortValue)) { p_SelectSql_Page = string.Format(@" {0} LIMIT {1},{2}", p_DbModel.Sql.ToString(), p_DbModel.PageInfo.PageSize * (p_DbModel.PageInfo.PageIndex - 1), p_DbModel.PageInfo.PageSize); } else { p_SelectSql_Page = string.Format(@"{0} order by {1} {2} LIMIT {3},{4}", p_DbModel.Sql.ToString(), p_DbModel.PageInfo.SortValue, p_DbModel.PageInfo.Desc, p_DbModel.PageInfo.PageSize * (p_DbModel.PageInfo.PageIndex - 1), p_DbModel.PageInfo.PageSize); } try { var m_Connection = CreateOpenConnection(); p_DbModel.PageInfo.TotalCount = m_Connection.Query<int>(GetCountSql(p_DbModel.Sql.ToString()), p_DbModel.Parameters).FirstOrDefault(); List<T> m_List = m_Connection.Query<T>(p_SelectSql_Page, p_DbModel.Parameters).ToList(); CloseDbConnection(); return m_List; } catch (Exception ex) { throw ex; } } /// <summary> /// 获取SelectCount语句 /// </summary> /// <param name="p_Sql">Sql语句</param> /// <returns></returns> private static string GetCountSql(string p_Sql) { //获取FirstTableName开始的位置 int m_FirstTableName_Index = p_Sql.ToLower().IndexOf("from") + 4; string m_PartString = p_Sql.Substring(m_FirstTableName_Index, p_Sql.Length - m_FirstTableName_Index); return "SELECT COUNT(*) FROM " + m_PartString; } /// <summary> /// 销毁方法 /// </summary> public void Dispose() { try { m_DbConnection.Close(); m_DbConnection.Dispose(); m_DbTransaction.Dispose(); } catch { } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShopMall.Common { public class ExHelper { /// <summary> /// 附加异常处理执行 /// </summary> /// <param name="p_CommonResultBase"></param> /// <param name="p_Action"></param> public static void TryExec(CommonResultBase p_CommonResultBase, Action p_Action) { try { //执行代码 p_Action(); //不抛异常默认为成功 p_CommonResultBase.Success = true; if (string.IsNullOrWhiteSpace(p_CommonResultBase.Message)) { p_CommonResultBase.Message = "执行成功!"; } } catch (SysEx ex) { LogHelper.WriteLog("SysEx", ex); p_CommonResultBase.Success = false; p_CommonResultBase.Message = ex.ExMessage; p_CommonResultBase.ExCode = ex.ExCode; p_CommonResultBase.ExMessage = ex.ExMessage; Console.WriteLine(ex.Message); } catch (Exception ex) { LogHelper.WriteLog("Exception", ex); p_CommonResultBase.Success = false; p_CommonResultBase.Message = "系统错误!" + ex.Message; p_CommonResultBase.ExCode = "ExCode000000"; p_CommonResultBase.ExMessage = "系统错误!" + ex.Message; Console.WriteLine("【" + p_CommonResultBase.ExCode + "】" + ex.Message); } finally { } } /// <summary> /// 操作数据库时影响行数为零 /// </summary> public static void Throw_DataBase_ZeroRowEx() { throw new SysEx("ExCode000001", "操作数据库时影响行数为零!"); } /// <summary> /// 数据库连接失败 /// </summary> public static void Throw_DbOpenEX() { throw new SysEx("ExCode000002", "数据库连接失败!"); } /// <summary> /// 登出 /// </summary> public static void Throw_LogOut() { throw new SysEx("ExCode000003", "登出!"); } /// <summary> /// 用户ID为空 /// </summary> public static void Throw_UserID_Empty() { throw new SysEx("ExCode000004", "用户ID为空!"); } /// <summary> /// 登录名为空 /// </summary> public static void Throw_LoginName_Empty() { throw new SysEx("ExCode000005", "登录名为空!"); } /// <summary> /// 密码为空 /// </summary> public static void Throw_Password_Empty() { throw new SysEx("ExCode000006", "密码为空!"); } /// <summary> /// 密码不正确 /// </summary> public static void Throw_Password_Does_Not_Match() { throw new SysEx("ExCode000007", "密码不正确!"); } /// <summary> /// 用户已经删除 /// </summary> public static void Throw_User_Deleted() { throw new SysEx("ExCode000008", "用户已经删除!"); } /// <summary> /// 用户没有找到 /// </summary> public static void Throw_User_NoFind() { throw new SysEx("ExCode000009", "用户没有找到!"); } /// <summary> /// 一次性查询数量太多,请勿超过{0}条! /// </summary> /// <param name="p_RowCount"></param> public static void Throw_RowCount_TooMuch(int p_RowCount) { throw new SysEx("ExCode00010", string.Format("一次性查询数量太多,请勿超过{0}条!", p_RowCount)); } /// <summary> /// 创建流程时没有找到起草环节 /// </summary> public static void Throw_BuildingWF_NoDraft() { throw new SysEx("ExCode00011", string.Format("创建流程时没有找到起草环节!")); } /// <summary> /// 创建流程时没有找到分支线 /// </summary> public static void Throw_BuildingWF_NoTransition() { throw new SysEx("ExCode00012", string.Format("创建流程时没有找到分支线!")); } /// <summary> /// 创建流程时没有找到下一个环节 /// </summary> public static void Throw_BuildingWF_NoActivityModel() { throw new SysEx("ExCode00013", string.Format("创建流程时没有找到下一个环节!")); } /// <summary> /// 创建流程时发现{0}环节出现多次 /// </summary> public static void Throw_BuildingWF_MultipleActive(string p_WF_ActiveModelName) { throw new SysEx("ExCode00014", string.Format("创建流程时发现{0}环节出现多次!", p_WF_ActiveModelName)); } /// <summary> /// 该任务与用户不符! /// </summary> public static void Throw_TaskAndUserNoMatch() { throw new SysEx("ExCode00015", string.Format("该任务与用户不符!")); } /// <summary> /// 没有表单权限 /// </summary> public static void Throw_NoAcl() { throw new SysEx("ExCode00016", string.Format("没有表单权限!")); } /// <summary> /// 没有初始化布尔变量 /// </summary> public static void Throw_NoInitBooleanValue(string p_Message) { throw new SysEx("ExCode00017", string.Format("字段{0}没有初始化布尔变量!", p_Message)); } /// <summary> /// 任务没有找到 /// </summary> public static void Throw_TaskNotFind() { throw new SysEx("ExCode00018", string.Format("任务没有找到!")); } /// <summary> /// 任务已经办理完成 /// </summary> public static void Throw_TaskIsDid() { throw new SysEx("ExCode00019", string.Format("任务已经办理完成!")); } /// <summary> /// 汇签任务不能进行加签、转签等操作 /// </summary> public static void Throw_IsGroupActivity() { throw new SysEx("ExCode00020", string.Format("汇签任务不能进行加签、转签等操作!")); } /// <summary> /// 同步任务到老系统失败! /// </summary> /// <param name="p_ExMessage"></param> public static void Throw_SyncOldSystemEx(string p_ExMessage) { throw new SysEx("ExCode00021", string.Format("同步任务到老系统失败!异常信息:{0}", p_ExMessage)); } /// <summary> /// 同步老系统任务需要传WF_FormID参数 /// </summary> public static void Throw_No_WF_FormID() { throw new SysEx("ExCode00022", "同步老系统任务需要传WF_FormID参数!"); } /// <summary> /// 同步老系统任务需要传FormDataID参数 /// </summary> public static void Throw_No_FormDataID() { throw new SysEx("ExCode00023", "同步老系统任务需要传FormDataID参数!"); } /// <summary> /// 同步老系统任务需要传FormTaskID参数 /// </summary> public static void Throw_No_FormTaskID() { throw new SysEx("ExCode00024", "同步老系统任务需要传FormTaskID参数!"); } /// <summary> /// 登录认证票时间超时 /// </summary> public static void Throw_LoginTicksout() { throw new SysEx("ExCode00025", "录认证票时间超时!"); } /// <summary> /// 登录认证票时间超时 /// </summary> public static void Throw_OutSideInterfaceEx(string p_ExMessage) { throw new SysEx("ExCode00026", string.Format("调用{0}接口异常!", p_ExMessage)); } /// <summary> /// 任务未激活 /// </summary> public static void Throw_TaskNotActivited() { throw new SysEx("ExCode00027", string.Format("该任务未激活!")); } /// <summary> /// 文件未找到 /// </summary> public static void Throw_FileNotFound() { throw new SysEx("ExCode00028", string.Format("文件未找到!")); } /// <summary> /// 文件不属于自己 /// </summary> public static void Throw_FileBelongOneself() { throw new SysEx("ExCode00029", string.Format("文件不属于自己!")); } /// <summary> /// 意见不能为空 /// </summary> public static void Throw_OpinionIsEmpty() { throw new SysEx("ExCode00030", string.Format("意见不能为空!")); } /// <summary> /// 已经有完成的任务,不能撤回 /// </summary> public static void Throw_HaveDidTask_NoBack() { throw new SysEx("ExCode00031", string.Format("已经有完成的任务,不能撤回!")); } /// <summary> /// 没有找到要退回的环节,不能撤回 /// </summary> public static void Throw_NotFindActivity_NoBack() { throw new SysEx("ExCode00032", string.Format("没有找到要退回的环节,不能撤回!")); } /// <summary> /// 没有找到要退回的环节,不能撤回 /// </summary> public static void Throw_NotFindTask_NoBack() { throw new SysEx("ExCode00033", string.Format("没有找到要退回的任务,不能撤回!")); } /// <summary> /// 表单不是送签中 /// </summary> public static void Throw_FormDataStateIsError_NoBack() { throw new SysEx("ExCode00034", string.Format("表单不是送签中,不能撤回!")); } /// <summary> /// 起草时检查流程未通过 /// </summary> public static void Throw_ChckDraft(string p_ExMessage) { throw new SysEx("ExCode00035", string.Format("起草时检查流程未通过,原因是:{0}", p_ExMessage)); } /// <summary> /// 创建流程时发现{0}环节出现多次 /// </summary> public static void Throw_CookieLengthMax(string p_ExMessage) { throw new SysEx("ExCode00036", string.Format("Cookie:【{0}】超出了最大长度!", p_ExMessage)); } /// <summary> /// 用户账户不是有效状态 /// </summary> public static void Throw_User_StateNoValid() { throw new SysEx("ExCode00037", "用户账户不是有效状态!"); } /// <summary> /// 用户不是在职状态 /// </summary> public static void Throw_User_NoWork() { throw new SysEx("ExCode00038", "用户不是在职状态!"); } /// <summary> /// 表单是起草状态 不能撤回 /// </summary> public static void Throw_FormIsDraft_NotBak() { throw new SysEx("ExCode00039", "表单是起草状态 不能撤回!"); } /// <summary> /// 撤回错误 /// </summary> public static void Throw_BackError(string p_ExMessage) { throw new SysEx("ExCode00040", p_ExMessage); } /// <summary> /// 抛出一般错误 /// </summary> public static void Throw_Ex(string p_ExMessage) { throw new SysEx("ExCode99999", p_ExMessage); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using ShopMall.Entity; using ShopMall.DAL; using ShopMall.Common; namespace ShopMall.BLL { public class UserBll { /// <summary> /// 获取全部用户 /// </summary> /// <returns></returns> public static List<UserEntity> GetAllUser() { DbModel m_DbModel = UserDal.GetAllUser(); DbProvider m_DbProviderRead = new DbProvider(); return m_DbProviderRead.GetList<UserEntity>(m_DbModel); } public static UserEntity GetByLoginName(string p_LoginName) { DbModel m_DbModel = UserDal.GetByLoginName(p_LoginName); DbProvider m_DbProviderRead = new DbProvider(); return m_DbProviderRead.Get<UserEntity>(m_DbModel); } public static void Add(UserEntity p_UsersEntity) { DbModel m_DbModel = UserDal.Add(p_UsersEntity); DbProvider m_DbProvider = new DbProvider(); m_DbProvider.Execute(m_DbModel); } public static void Update(UserEntity p_UsersEntity) { DbModel m_DbModel = UserDal.Update(p_UsersEntity); DbProvider m_DbProvider = new DbProvider(); m_DbProvider.Execute(m_DbModel); } public static void Del(UserEntity p_UserModel) { DbModel m_DbModel = UserDal.Del(p_UserModel); DbProvider m_DbProvider = new DbProvider(); m_DbProvider.Execute(m_DbModel); } /// <summary> /// 用户明和密码 /// </summary> /// <param name="username">组织编号</param> /// <returns></returns> public static UserEntity GetUserByUsernameAndPassword(string username,string password) { DbModel m_DbModel = UserDal.GetUserByUsernameAndPassword(username, password); DbProvider m_DbProviderRead = new DbProvider(); return m_DbProviderRead.Get<UserEntity>(m_DbModel); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShopMall.Common { public class MD5Util { } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShopMall.Common { /// <summary> /// 数据Model /// </summary> public class DbModel { /// <summary> /// 初始化 /// </summary> public DbModel() { m_Sql = new StringBuilder(); m_Parameters = null; } private StringBuilder m_Sql; /// <summary> /// SQL语句 /// </summary> public StringBuilder Sql { get { return m_Sql; } } private object m_Parameters; /// <summary> /// 参数 /// </summary> public object Parameters { set { m_Parameters = value; } get { return m_Parameters; } } private PageInfoDom m_PageInfo; /// <summary> /// 分页 /// </summary> public PageInfoDom PageInfo { set { m_PageInfo = value; } get { return m_PageInfo; } } /// <summary> /// 执行行数为零时的异常提示 /// </summary> public string ZeroExMessage { set; get; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShopMall.Common { /// <summary> /// 系统自定义异常类 /// </summary> public class SysEx : Exception { private string m_ExCode; /// <summary> /// 错误编码 /// </summary> public string ExCode { get { return m_ExCode; } } private string m_ExMessage; /// <summary> /// 错误信息 /// </summary> public string ExMessage { get { return m_ExMessage; } } /// <summary> /// /// </summary> /// <param name="p_PurchaseExCode">错误编码</param> /// <param name="p_ExMessage">错误信息</param> internal SysEx(string p_ExCode, string p_ExMessage) { m_ExCode = p_ExCode; m_ExMessage = p_ExMessage; } } } <file_sep>using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; namespace ShopMall.Common { public class CommonResultBase { /// <summary> /// 将是否成功和发生异常标志初始化为false /// </summary> public CommonResultBase() { Success = false; LogOut = false; ResultObjList = new List<object>(); PageInfo = new PageInfoDom(); } /// <summary> /// 操作是否成功 /// </summary> [DataMember] public bool Success { set; get; } /// <summary> /// 登出 /// </summary> [DataMember] public bool LogOut { set; get; } /// <summary> /// 异常编码 /// </summary> [DataMember] public string ExCode { set; get; } /// <summary> /// 异常信息 /// </summary> [DataMember] public string ExMessage { set; get; } /// <summary> /// 返回信息 /// </summary> [DataMember] public string Message { set; get; } /// <summary> /// 操作影响行数 /// </summary> [DataMember] public int EffectRows { set; get; } /// <summary> /// 返回值(object数组) /// </summary> [DataMember] public List<object> ResultObjList { set; get; } //////////////////////////////////////////////////////////////////////// [DataMember] public PageInfoDom PageInfo { set; get; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShopMall.Common { public class PageInfoDom { public PageInfoDom() { } public PageInfoDom(int p_PageIndex, int p_PageSize) { PageIndex = p_PageIndex; PageSize = p_PageSize; } public int PageIndex { get; set; } public int PageSize { get; set; } public int TotalCount { get; set; } public string SortValue { get; set; } public string Desc { get; set; } //页数 private int m_PageCount; public Int32 PageCount { get { if (PageSize == 0) { return 0; } if (m_PageCount == 0) { m_PageCount = TotalCount / PageSize; if (TotalCount % PageSize > 0) { m_PageCount++; } } return m_PageCount; } } //当前页开始编号 private int m_RowStart = 0; public Int32 RowStart { get { return m_RowStart == 0 ? (PageIndex - 1) * PageSize + 1 : m_RowStart; } } //当前页结束编号 private int m_RowEnd = 0; public Int32 RowEnd { get { return m_RowEnd == 0 ? PageIndex * PageSize : m_RowEnd; } } /// <summary> /// 显示多少个页 /// </summary> private const int ShowPagerCount = 10; public Int32 PageStart { get { //计算开始值 int m_Start = PageIndex - ShowPagerCount / 2; if (m_Start < 1) { return 1;//如果小于1则返回1 } else { return m_Start;//否则返回计算值 } } } public Int32 PageEnd { get { //用开始页计算最后页面 int m_End = PageStart + ShowPagerCount - 1; if (m_End > m_PageCount) { return m_PageCount;//如果最后页面超过了总也是返回总页数 } else { return m_End;//否则返回计算值 } } } public List<int> PageList { get { List<int> m_PageList = new List<int>(); if (PageStart == 0) { return m_PageList; } if (PageStart == PageEnd) { m_PageList.Add(PageStart); return m_PageList; } for (int t_Index = PageStart; t_Index <= PageEnd; t_Index++) { m_PageList.Add(t_Index); } return m_PageList; } } } } <file_sep>/** * Created by walker on 2017/4/21. */ $(function(){ var $my_nav = $('#my-nav'); // 导航事件 $my_nav.on('click', '.navbar-nav>li>a', function(e){ e.preventDefault(); if( $(this).attr('href') === '#shoppingCar' ){ location.href = 'shoppingCar.html'; return ; } if( $(this).parent().hasClass('active') ) return ; // 如果点击的锚点已经是激活状态,不再响应点击事件 $(this).parent().addClass('active').siblings('.active').removeClass('active'); var id = $(this).attr('href'); $(id).addClass('active').siblings('.active').removeClass('active'); }).on('click', '.search-input', function(){ $('.navbar-nav>li').removeClass('active'); $('section>div.active').removeClass('active'); $('#search').addClass('active'); }); // 用户注册/登录事件 $('.btns').on('click', '#loginBtn', function(){ toggleRole('login'); }).on('click', '#registerBtn', function(){ toggleRole('register'); }); // 登录/注册框中的事件 $('#myModal').on('focus', 'input', function(){ $('#error-info').html(''); }).on('click', '#actionBtn1', function(){ var actionType = $('#myModal').attr('data-role'); var userName = $('#userName').val(), password = $('#password').val(); var data = { userName: userName, password: <PASSWORD> }; switch( actionType ){ case 'login': // 登录接口 $.get('../src/data/userTable.json', function( data ){ var canLogin = false; for( var k1 in data ){ if( data[k1].userName === userName && data[k1].password ){ // 登录成功 loginSuccess(data[k1]); canLogin = true; break; } } if( !canLogin ){ // 用户名或密码错误 $('#error-info').html('用户名或密码错误!'); } }); break; case 'register': // 注册接口 break; } }).on('click', '#actionBtn2', function(){ // 按钮2的目的是转换角色 var actionType = $('#myModal').attr('data-role'); switch( actionType ){ case 'login': // 切换为注册 toggleRole('register'); break; case 'register': // 切换为登录 toggleRole('login'); break; } }); function loginSuccess( userInfo ){ $('.action>.btns').html( userInfo.nickName ); $('#myModal').modal('hide'); } function toggleRole( actionType ){ var roleType1 = actionType === 'login' ? '登录' : '注册'; var roleType2 = actionType === 'login' ? '注册' : '登录'; var $myModal = $('#myModal'); var $myModalLabel = $('#myModalLabel'); $myModal.attr('data-role', actionType); // 修改模态框的角色 $myModalLabel.html(roleType1); // 修改模态框标题 $('#actionBtn1').html(roleType1); // 修改action1按钮动作 $('#actionBtn2').html(roleType2); // 修改action2按钮动作 if( actionType === 'register' ){ $myModal.find('.my-help-block').show(); $myModal.find('.quickAction>span').html('已有账号?'); }else{ $myModal.find('.my-help-block').hide(); $myModal.find('.quickAction>span').html('还没有账号?'); } } // 商品点击事件 $('#p-list').on('click', '.productItem, .p-name', function(){ // 点击商品,携带商品信息,跳转至详情页 location.href = 'detail.html?pid=*'; }); $('.p-list').on('click', '.productItem, .p-name', function(){ // 点击商品,携带商品信息,跳转至详情页 location.href = 'detail.html?pid=*'; }); var param = $.getRequest(); if( param.route === 'search'){ $my_nav.find('.search-input').trigger('click'); }else{ $my_nav.find('[href="#' + param.route + '"]').trigger('click'); } });<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace ShopMall.Common { /// <summary> /// 异常编码 /// </summary> public static class ExCode { /// <summary> /// 操作数据库时影响行数为零! /// </summary> [Description("操作数据库时影响行数为零!")] public const string DataBase_ZeroRowEx = "ExCode000001"; /// <summary> /// 数据库连接失败! /// </summary> [Description("数据库连接失败!")] public static string DbOpenEX = "ExCode000002"; /// <summary> /// 用户ID为空! /// </summary> [Description("用户ID为空!")] public static string UserID_Empty = "ExCode000003"; /// <summary> /// 登录名为空! /// </summary> [Description("登录名为空!")] public static string LoginName_Empty = "ExCode000004"; /// <summary> /// 密码为空! /// </summary> [Description("密码为空!")] public static string Password_Empty = "<PASSWORD>"; /// <summary> /// 密码不正确! /// </summary> [Description("密码不正确!")] public static string Password_Does_Not_Match = "ExCode0<PASSWORD>"; /// <summary> /// 用户已经删除! /// </summary> [Description("用户已经删除!")] public static string User_Deleted = "ExCode000007"; /// <summary> /// 用户没有找到! /// </summary> [Description("用户没有找到!")] public static string User_NoFind = "ExCode000008"; } } <file_sep>/** * Created by walker on 2017/4/24. */ $(function(){ $('.goBack').bind('click', function(){ location.href = 'index.html?route=home'; }); $('#cashier').bind('click', function(){ location.href = 'index.html?route=mine'; }); });<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ShopMall.Common { /// <summary> /// 写文件日志类 /// </summary> public class LogHelper { /// <summary> /// 写入日志 /// </summary> /// <param name="p_LogTxt"></param> public static void WriteLog(string p_Title, object p_LogObject) { try { string m_LogText = JsonTools.GetJson(p_LogObject); WriteLog(p_Title, m_LogText); } catch (Exception ex) { //如果 JsonTools.GetJson 转换失败则记录失败原因 WriteLog(p_Title, ex.ToString()); } } /// <summary> /// 写入日志 /// </summary> /// <param name="p_LogTxt"></param> public static void WriteLog(string p_Title, string p_Context) { StreamWriter m_StreamWriter = null; try { //日志路径 string m_LogPath = System.IO.Directory.GetCurrentDirectory() + "/Log/" + p_Title; //如果文件夹不存在则创建 DirectoryInfo m_LogDirectoryInfo = new DirectoryInfo(m_LogPath); if (!m_LogDirectoryInfo.Exists) { m_LogDirectoryInfo.Create(); } //Log全路径 string LogFilePath = m_LogPath + "/" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; //创建流 m_StreamWriter = File.AppendText(LogFilePath); //写入 m_StreamWriter.WriteLine("--------------------------------------------------------------------------------------------------------"); m_StreamWriter.WriteLine(DateTime.Now.ToString() + " " + p_Title); m_StreamWriter.WriteLine(p_Context); m_StreamWriter.WriteLine("========================================================================================================"); m_StreamWriter.WriteLine(); m_StreamWriter.Flush(); m_StreamWriter.Dispose(); } catch (Exception ex) { try { if (m_StreamWriter != null) { m_StreamWriter.Flush(); m_StreamWriter.Dispose(); } } catch (Exception ex2) { //不做任何处理 } } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShopMall.Common { public class JsonTools { public static string GetJson<T>(T p_Obj) { return Newtonsoft.Json.JsonConvert.SerializeObject(p_Obj); } // 从一个Json串生成对象信息 public static object JsonToObject(string jsonString, object obj) { return Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString, obj.GetType()); } } } <file_sep>using Microsoft.Extensions.Configuration; using System.IO; namespace ShopMall.Common { public static class ConfigManager { private static IConfigurationBuilder m_ConfigurationBuilder = null; private static IConfiguration m_Configuration = null; static ConfigManager() { m_ConfigurationBuilder = new ConfigurationBuilder(); m_ConfigurationBuilder.AddJsonFile(Directory.GetCurrentDirectory() + "/appsettings.json"); m_Configuration = m_ConfigurationBuilder.Build(); } private static string GetConfigValue(string p_Key) { return m_Configuration[p_Key]; } /// <summary> /// 读写字符串 /// </summary> /// <returns></returns> public static string ReadMySqlConnection { get { return GetConfigValue("ConnectionStrings:ReadMySqlConnection"); } } /// <summary> /// 只读字符串 /// </summary> /// <returns></returns> public static string WriteMySqlConnection { get { return GetConfigValue("ConnectionStrings:WriteMySqlConnection"); } } } } <file_sep>using ShopMall.Common; using System; using System.Collections.Generic; using System.Text; using ShopMall.Entity; namespace ShopMall.DAL { public class UserDal { public static DbModel Get(string p_UserID) { DbModel m_DbModel = new DbModel(); m_DbModel.Sql.Append(@"SELECT id username password createtime updatetime createAccount updateAccount status rid nickname email FROM t_user WHERE status = @status AND id = @id"); m_DbModel.Parameters = new { status = "1", id = p_UserID }; return m_DbModel; } public static DbModel GetAllUser() { DbModel m_DbModel = new DbModel(); m_DbModel.Sql.Append(@"SELECT id, username, password, createtime, updatetime, createAccount, updateAccount, status, rid, nickname, email FROM t_user WHERE status = @status "); m_DbModel.Parameters = new { status = "y" }; return m_DbModel; } public static DbModel GetList(List<string> p_UserIDs) { DbModel m_DbModel = new DbModel(); m_DbModel.Sql.Append(@"SELECT id, username, password, createtime, updatetime, createAccount, updateAccount, status, rid, nickname, email FROM t_user WHERE status = @status AND id in @id"); m_DbModel.Parameters = new { status = 1, id = p_UserIDs }; return m_DbModel; } public static DbModel GetByLoginName(string p_LoginName) { DbModel m_DbModel = new DbModel(); m_DbModel.Sql.Append(@"SELECT id, username, password, createtime, updatetime, createAccount, updateAccount, status, rid, nickname, email FROM t_user WHERE status=@Status AND LoginName = @LoginName"); m_DbModel.Parameters = new { Status = 1, LoginName = p_LoginName }; return m_DbModel; } public static DbModel Add(UserEntity p_UsersEntity) { DbModel m_DbModel = new DbModel(); m_DbModel.Sql.Append(@"INSERT INTO t_user (id, username, password, createtime, updatetime, createAccount, updateAccount, status, rid, nickname, email) VALUES (@id, @username, @password, @createtime, @updatetime, @createAccount, @updateAccount, @status, @rid, @nickname, @email);"); m_DbModel.Parameters = p_UsersEntity; return m_DbModel; } public static DbModel Update(UserEntity p_UsersEntity) { DbModel m_DbModel = new DbModel(); m_DbModel.Sql.Append(@" UPDATE t_user SET username=@username, password=@<PASSWORD>, createtime=@createtime, createAccount=@createAccount, updatetime=@updatetime, updateAccount=@updateAccount, status=@status, rid=@rid, nickname=@nickname, email=email WHERE status = @status AND id = @id;"); p_UsersEntity.UpdateTime = DateTime.Now; m_DbModel.Parameters = p_UsersEntity; return m_DbModel; } public static DbModel Del(UserEntity p_UserModel) { DbModel m_DbModel = new DbModel(); m_DbModel.Sql.Append(@"UPDATE t_user SET Status = @Status, UpdateTime = @UpdateTime, UpdateAccount = @UpdateAccount WHERE id = @id "); m_DbModel.Parameters = new { id = p_UserModel.ID, Status = p_UserModel.Status, UpdateTime = p_UserModel.UpdateTime, UpdateAccount = p_UserModel.UpdateAccount }; return m_DbModel; } public static DbModel GetUserByUsernameAndPassword(string username, string password) { DbModel m_DbModel = new DbModel(); m_DbModel.Sql.Append(@"SELECT * FROM t_user WHERE status = @status AND username = @username AND password = <PASSWORD>"); m_DbModel.Parameters = new { status = 1, username = username, password = <PASSWORD> }; return m_DbModel; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ShopMall.Entity; using ShopMall.BLL; using Microsoft.Extensions.Logging; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace ShopMall.API.Controllers { [Route("api/[controller]")] public class UsersController : Controller { private readonly ILogger<UsersController> _logger; List<UserEntity> U_UsersList = UserBll.GetAllUser(); // GET: api/values [HttpGet] public IEnumerable<UserEntity> Get() { return U_UsersList.AsEnumerable(); } // GET api/values/5 [HttpGet("{id}")] public UserEntity Get(int id) { return U_UsersList.Find(m => m.ID == id); } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ShopMall.Entity { public class UserEntity:BaseEntity { #region 构造函数 public UserEntity() { } #endregion #region 属性访问器 /// <summary> /// 用户ID /// </summary> public long ID { set; get; } /// <summary> /// 登录名 /// </summary> public string UserName { set; get; } /// <summary> /// 密码 /// </summary> public string Password { set; get; } /// <summary> /// 用户状态 /// </summary> public string Status { set; get; } /// <summary> /// 角色id /// </summary> public int Rid { set; get; } /// <summary> /// 展示名称 /// </summary> public string NickName { set; get; } /// <summary> /// 邮箱 /// </summary> public string Email { set; get; } #endregion } } <file_sep>using System; namespace ShopMall.Entity { public class BaseEntity { /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; set; } /// <summary> /// 创建账号 /// </summary> public string CreateAccount { get; set; } /// <summary> /// 更新时间 /// </summary> public DateTime UpdateTime { get; set; } /// <summary> /// 更新账号 /// </summary> public string UpdateAccount { get; set; } } }
ed0d943aa6fcb0424cad1f0ceada56daf7292f46
[ "JavaScript", "C#" ]
18
C#
nightsWatcher/PistolShopMall
60bc785e9a8c5678f36482e8698e9aa1078f8cdc
c5b329a599d800a2dde1bdb103339afa108c50bd
refs/heads/master
<file_sep># Trabalho Final da disciplina de Tópicos Especiais III ## Projeto Smart Lamp ### Introdução O sistema como um todo gira em torno de uma lâmpada inteligente (e ai você pode imaginar várias situações onde está lâmpada possa estar, um quarto, uma sala, whatever). Está lâmpada representada como um LED deve ficar apagada durante o dia e caso seja noite esta lâmpada só deve ser acesa caso haja alguém dentro do ambiente. Para isso foram utilizadas tecnologias como o Arduino, NodeJS e MQTT. #### Dispositivos embarcados - **Hardware necessário** - Arduino UNO - Shield Ethernet - Sensor de Luminosidade - LED'S - Resistores - Jumpers - **Circuito** ![Arduino](arduinoproto.jpeg) - **Funcionamento** Basicamente, precisa definir variáveis com ip que o arduino vai usar, ip do servidor (máquina que vai estar rodando o serviço consumido pelo arduino), uma variável para guardar o pino que o LED está ligado, uma variável para ficar armazenando o valor gerado pelo sensor de luminosidade, e as referências para o Shield Ethernet e o cliente do MQTT. No código você vai iniciar uma nova conexão com a internet, se conectar ao servidor, subscrever em um tópico/serviço do servidor e setar um método que deverá ser chamado sempre que alguma alteração for feita no tópico ou serviço subscrito. **Método Callback** - Principal método da aplicação, pois é ele que contém a lógica de negócio do sistema. Este método recebe como parâmetro um tópico e uma mensagem. No caso deste sistema eu verifico se a mensagem é exatamente "ligar" ou "desligar", caso passem no teste ele liga ou desliga a lâmpada, neste caso representado como LED. **Método Reconect** - Método auxiliar, responsável por reconectar o arduino ao servidor, caso por algum motivo se desconecte. Caso consiga se conectar ele subscreve nos tópicos novamente. Caso não consiga ele fica tentando reconectar novamente a cada 5 segundos. **Método Loop** - Responsável por verificar se o arduino está conectado, caso não esteja chama o método Reconect indefinidamente até conseguir conexão. Este método também é responsável por ficar lendo o valor na porta analógica do sensor de luminosidade, este valor é publicado em um topico ou serviço no servidor. Esta operação de ler e publicar valor lido do sensor é realizado a cada 1 segundo(Pode variam conforme a sua vontade). #### Protocolo de comunicação e controle No meu computador eu instalei um broker para receber mensagens MQTT (Mosquitto). A partir foi habilitado a possibilidade de utilizar mensagens MQTT e criação de tópicos. O fluxo da aplicação basicamente se baseia pela troca de mensagens. O **arduino** subscreve no tópico *"casa/lampada"* e portanto fica escutando as alterações e publicações feitas neste tópico. Além de subscrever nesse tópico ele publica em um outro tópico, denominado *"casa/lampada/estado"* onde informa para o servidor o estado do sensor de luminosidade. E o servidor feito em NodeJS faz o contrário do arduino, ele subscreve no tópico *"casa/lampada/estado"* e publica mensagens somente no tópico *"casa/lampada"*. **Tópico "casa/lampada"** - recebe mensagens do tipo {"ligar", "desligar"} **Tópico "casa/lampada/estado"** - recebe números gerados dinamicamente conforme lidos do sensor de luminosidade, dentro da faixa {0 - 1023} #### Serviços na internet - **Controlador** O controlador foi desenvolvido utilizando NodeJS. Ele é capaz de mandar e receber dados do browser. Basicamente como já explicado o módulo controlador abre uma conexão com a internet, após isso se conecta ao broker que neste caso funciona localmente e após isso o controlador subscreve nos tópicos que lhe interessam do broker, neste caso no tópico *"casa/lampada/estado"*, onde ele fica "escutando" todas as modificações naquele tópico e reage conforme lhe for programado. Neste caso quando o valor recebido neste tópico for maior do que 600 e possuir alguém dentro da sala (manipulado pela interface web) o controlador entende que está de noite e que portanto deve acender a luz/LED, neste caso ele publica no tópico *"casa/lampada"* a menssagem "acender" e o arduino acende o LED. Caso o sensor envie um valor maior do que 600 (o que significa que está de noite) e não tenha ninguém na sala ele não acende a lâmpada. Caso o valor enviado pelo sensor no arduino seja menor do que 600 ele publica a seguinte mensagem no mesmo tópico "desligar", e portanto o arduino mantém a lâmpada desligada. Basicamente este é toda a lógica desta aplicação contida no código NodeJS, exceto a comunicação com a página web feita através dos verbos HTTP, GET e POST, acionados ao carregar a página e ao clicar em algum botão na tela respectivamente. - **Interface Web** Eu criei na interface um título, que leva o título do projeto, dois botões um para entrar na sala e outro para sair, e um paragrafo onde apresento a quantidade de pessoas conectadas/dentro da sala. <file_sep>#include <Ethernet.h> #include <SPI.h> #include <PubSubClient.h> #include "RestClient.h" int ledPin = 7; //Led no pino 7 int ldrPin = 0; //LDR no pino analígico 8 int ldrValor = 0; //Valor lido do LDR byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; IPAddress ip(192, 168, 0, 110); IPAddress server(192, 168, 0, 102); EthernetClient ethClient; PubSubClient client(ethClient); //Setup void setup() { Serial.begin(9600); pinMode(ledPin,OUTPUT); //define a porta 7 como saída // Connect via DHCP Serial.println("connect to network"); Ethernet.begin(mac, ip); client.setServer(server, 1883); Serial.println("Setup!"); client.setCallback(callback); //subscreve no tópico client.subscribe("casa/lampada"); } void callback(char* topic, byte* payload, unsigned int length) { //armazena msg recebida em uma sring payload[length] = '\0'; String strMSG = String((char*)payload); Serial.print("Mensagem chegou do tópico: "); Serial.println(topic); Serial.print("Mensagem:"); Serial.print(strMSG); Serial.println(); Serial.println("-----------------------"); //aciona saída conforme msg recebida if (strMSG == "ligar"){ //se msg "ligar" digitalWrite(ledPin, HIGH); //coloca saída em LOW para ligar a Lampada }else if (strMSG == "desligar"){ //se msg "desligar" digitalWrite(ledPin, LOW); //coloca saída em HIGH para desligar a Lampada } } //função pra reconectar ao servido MQTT void reconect() { //Enquanto estiver desconectado while (!client.connected()) { Serial.println("Tentando conectar ao servidor MQTT"); if(client.connect("arduinoClient")) { Serial.println("Conectado!"); //subscreve no tópico client.subscribe("casa/lampada"); } else { Serial.println("Falha durante a conexão.Code: "); Serial.println( String(client.state()).c_str()); Serial.println("Tentando novamente em 5 s"); //Aguarda 5 segundos delay(5000); } } } void loop() { if (!client.connected()) { reconect(); } //ler o valor do LDR ldrValor = analogRead(ldrPin); //O valor lido será entre 0 e 1023 char msg[55]; sprintf(msg, "%d", ldrValor); Serial.println("Publicar no topico casa/lampada/estado o estado da lampada"); client.publish("casa/lampada/estado", msg); //imprime o valor lido do LDR no monitor serial Serial.println(ldrValor); delay(1000); client.loop(); }
ed13aa85462bbb4d495434d5b9e12134a68e0053
[ "Markdown", "C++" ]
2
Markdown
Eudalio/smart_lamp
24e1965cd5d301fde1c14f99a26f6fc8c10e9266
fa307a1da2162ae99d647d260e42594b1b9b01b8
refs/heads/master
<repo_name>nirlo/EyeNeuro2<file_sep>/app/src/main/java/com/example/lock0134/eyeneuro/MainActivity.java package com.example.lock0134.eyeneuro; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.Toast; import com.example.lock0134.eyeneuro.ExpandableListAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity { View view_Group; private DrawerLayout mDrawerLayout; ExpandableListAdapter mMenuAdapter; ExpandableListView expandableList; List<String> listDataHeader; HashMap<String, List<String>> listDataChild; FragmentManager fragmentManager; //Icons, use as you want @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { expandableList.setIndicatorBounds(expandableList.getRight()- 80, expandableList.getWidth()); } else { expandableList.setIndicatorBoundsRelative(expandableList.getRight()- 80, expandableList.getWidth()); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); //requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); expandableList = (ExpandableListView) findViewById(R.id.navigationmenu); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setItemIconTintList(null); if (navigationView != null) { setupDrawerContent(navigationView); } prepareListData(); mMenuAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild); // setting list adapter expandableList.setAdapter(mMenuAdapter); expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long id) { //Log.d("DEBUG", "submenu item clicked"); selectDrawerItem(listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition)); view.setSelected(true); if (view_Group != null) { view_Group.setBackgroundColor(Color.parseColor("#ffffff")); } view_Group = view; view_Group.setBackgroundColor(Color.parseColor("#DDDDDD")); mDrawerLayout.closeDrawers(); return false; } }); expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) { //Log.d("DEBUG", "heading clicked"); return false; } }); Fragment fragment = new MainFragment(); fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); } private void prepareListData() { listDataHeader = new ArrayList<String>(); listDataChild = new HashMap<String, List<String>>(); // Adding data header listDataHeader.add("Physical Examination"); listDataHeader.add("Algorithm"); listDataHeader.add("About"); // Adding child data List<String> heading1 = new ArrayList<String>(); heading1.add("Afferent System"); heading1.add("Pupils"); heading1.add("Efferent System"); heading1.add("Intra Ocular Pressure"); heading1.add("Anterior Segment"); heading1.add("Posterior Segment"); heading1.add("Cranial Nerves"); heading1.add("Orbits"); heading1.add("Neuro Examination"); List<String> heading2 = new ArrayList<String>(); heading2.add("Unilateral Vision Loss"); List<String> heading3 = new ArrayList<String>(); heading3.add("Submenu"); heading3.add("Submenu"); listDataChild.put(listDataHeader.get(0), heading1);// Header, Child data listDataChild.put(listDataHeader.get(1), heading2); listDataChild.put(listDataHeader.get(2), heading3); } private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { menuItem.setChecked(true); mDrawerLayout.closeDrawers(); return true; } }); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public boolean selectDrawerItem(String item) { // Handle navigation view item clicks here. Fragment fragment = null; Class fragmentClass; switch(item) { case "Afferent System": fragmentClass = AfferentFrag.class; break; case "Pupils": fragmentClass = PupilsFrag.class; break; case "Efferent System": fragmentClass = EfferentFrag.class; break; case "Intra Ocular Pressure": fragmentClass = EfferentFrag.class; break; case "Anterior Segment": fragmentClass = EfferentFrag.class; break; case "Posterior Segment": fragmentClass = EfferentFrag.class; break; case "Cranial Nerves": fragmentClass = EfferentFrag.class; break; case "Orbits": fragmentClass = EfferentFrag.class; break; case "Neuro Examination": fragmentClass = EfferentFrag.class; break; case "Unilateral Vision Loss": fragmentClass = UnilateralFrag.class; break; default: fragmentClass = MainFragment.class; } try { fragment = (Fragment) fragmentClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } // Insert the fragment by replacing any existing fragment fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); // Set action bar title //setTitle(item.getTitle()); // Close the navigation drawer DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
2e3d83b7c87fb6e3906c9ba7f45854a3f092204e
[ "Java" ]
1
Java
nirlo/EyeNeuro2
60f73ff79c819bd6201960b562cc49e1b59115c8
8fe75a57c49e674d03ca9a20732ad1ffc35ea97c
refs/heads/master
<file_sep>module.exports = { uv: { code: null, fullname: null, description: null, branche: null, saison: null, type: null } } <file_sep>var https = require("https"); var _ = require("lodash") function getUserUvs(user, callback) { // https://webapplis.utc.fr/Edt_ent_rest/myedt/result?login={userid} https.get("https://webapplis.utc.fr/Edt_ent_rest/myedt/result?login=" + user, (res) => { var body = ''; res.on('data', function(chunk){ body += chunk; }); res.on('end', function(){ var uvs = JSON.parse(body); callback(Object.keys(_.groupBy(uvs, 'uv')), null); }); }) } exports.getUserUvs = getUserUvs; <file_sep>const config = require("../config/config") const neo4j = require('neo4j-driver').v1; var _ = require("lodash"); const Uv = require("../models/uv"); const driver = neo4j.driver("bolt://neo4j:" + config.neo4j.port, neo4j.auth.basic( config.neo4j.user, config.neo4j.password)); function getUvs() { var session = driver.session(); return session .run( "MATCH (uv: UV) RETURN uv") .then(result => { session.close(); return res = result.records.map(record => { return new Uv(record.get('uv').properties).data; }) }) .catch(error => { session.close(); throw error; }); } function getUserUvs(userid) { var session = driver.session(); console.log(userid) return session .run("MATCH (p:Person {id:'" + userid +"'})-[r:SUIT]->(uv:UV) RETURN r.GX,r.codeSemestre,uv.code") .then(result => { session.close(); return res = result.records.map(record => { return {uv :record.get('uv.code'), gx: record.get('r.GX'), semestre: record.get('r.codeSemestre')} ; }) }) .catch(error => { session.close(); console.log(error) throw error; }); } function getUv(code) { var session = driver.session(); return session .run( "MATCH (uv: UV {code:\"" + code + "\" }) RETURN uv") .then(result => { session.close(); return res = new Uv(result.records[0].get('uv').properties).data; }) .catch(error => { session.close(); throw error; }); } function getUvAttendance(code) { var session = driver.session(); return session .run( "MATCH ()-[r:SUIT]->(uv:UV {code : {code}}) WHERE left(r.GX,2) in ['TC','GI','IM','GU','GB','GP'] WITH r as r, LEFT(r.GX, 2) as GX, uv AS uv WITH [GX,toFloat(count(GX)) / uv.degree] as cnt return collect(cnt) as attendance", {code: code}) .then(result => { session.close(); res = {} result.records[0].get("attendance").map( attendance => { res[attendance[0]] = attendance[1]; }); return res; }) .catch(error => { session.close(); throw error; }); } function getSemestresAttendance(semestre, uv_type, limit, saison) { var session = driver.session(); return session .run( "MATCH ()-[r:SUIT {GX: {semestre} }]->(uv:UV) WHERE uv.type in {uv_type} AND LEFT(r.codeSemestre,1) in {saison} WITH uv.code as code, count(r) as cnt ORDER BY cnt DESC LIMIT {limit} WITH collect([code, toFloat(cnt)]) as collection RETURN collection as attendance", { semestre: semestre, uv_type: uv_type, limit: limit, saison: saison }) .then(result => { session.close(); res = {} result.records[0].get("attendance").map( attendance => { res[attendance[0]] = attendance[1]; }); return res; }) .catch(error => { session.close(); throw error; }); } function getGraphBranches(filter) { var session = driver.session(); return session .run( "MATCH ()-[r]->(uv) WHERE uv.degree > 5 AND uv.type IN {types} AND left(r.GX,2) IN {branches} RETURN count(r), r.GX,uv", filter) .then(result => { session.close(); var nodes = []; var edges = []; var genie = {}; var uv = {}; var groupe = {'TC': 1, 'IM': 2, 'GU': 3, 'GB': 4, 'GI': 5, 'GP': 6, 'GX': 0} config.branches.forEach( GX => { groupe[GX] = {}; groupe[GX].color = {background: config.branches_color[GX]} }) var length = 0; result.records.map(record => { var gx = record.get('r.GX'); if ( genie[gx] === undefined ){ genie[gx] = length; var n = _.indexOf(config.branches, gx.substring(0,2) ) var k = parseInt(gx.substring(gx.length-2,gx.length)) var x_coord = 0 var y_coord = 0 if ( gx.substring(0,2) == "TC" ){ x_coord = 0 y_coord = (7-k) * 300 } else { size = k * 300 + 300 x_coord = -Math.cos((n-1)/(4) * 3.14) * size y_coord = -Math.sin((n-1)/(4) * 3.14) * size } nodes.push( {id: length, "label": gx, "group": gx.substring(0,2), x:x_coord, y:y_coord, fixed: true, size: 50, "shape": "box", "font": {"size":50} } ) length = nodes.length; } }) result.records.map(record => { var gx = record.get('r.GX'); if ( gx.substring(0,3) == 'GSU' ){ gx = "GU" + gx.substring(3,5) } if ( gx.substring(0,3) == 'GSM' ){ gx = "IM" + gx.substring(3,5) } if ( gx.substring(0,2) == 'GM' ){ gx = "IM" + gx.substring(2,4) } if ( uv[record.get('uv').properties.code] === undefined){ nodes.push( {id: length, "label": record.get('uv').properties.code, size: 50, "value": record.get('uv').properties.degree.low , "group": record.get('uv').properties.branche} ) edges.push( {"from": length, "to": genie[gx],"color": {"color": "#dddddd", "highlight": config.branches_color[gx.substring(0,2)]} , value: record.get("count(r)").low} ) uv[record.get('uv').properties.code] = length; } else { edges.push( {"from": uv[record.get('uv').properties.code],"color": {"color": "#dddddd", "highlight": config.branches_color[gx.substring(0,2)]} , "to": genie[gx], value: record.get("count(r)").low} ) } length = nodes.length; }) return {nodes: nodes, edges: edges, genie: genie, groupes: groupe} }) .catch(error => { session.close(); throw error; }); } function getGraphBranches2(filter) { var session = driver.session(); return session .run( "MATCH ()-[r]->(uv) WHERE uv.degree > 5 AND uv.type IN {types} AND left(r.GX,2) IN {branches} AND LEFT(r.codeSemestre,1) in {saison} WITH count(r) as cnt, r.GX as GX, uv as uv RETURN collect([cnt, uv]) as attendances, GX as gx", filter) .then(result => { session.close(); var nodes = []; var edges = []; var genie = {}; var uv = {}; var groupe = {'TC': 1, 'IM': 2, 'GU': 3, 'GB': 4, 'GI': 5, 'GP': 6, 'GX': 0} config.branches.forEach( GX => { groupe[GX] = {}; groupe[GX].color = {background: config.branches_color[GX]} }) var length = 0; // ajout des branches result.records.map(record => { var gx = record.get('gx'); if ( genie[gx] === undefined ){ genie[gx] = length; // node id for the gx node // Calcul de la position var n = _.indexOf(config.branches, gx.substring(0,2) ) var k = parseInt(gx.substring(gx.length-2,gx.length)) var x_coord = 0 var y_coord = 0 if ( gx.substring(0,2) == "TC" ){ x_coord = 0 y_coord = (7-k) * 300 } else { size = k * 300 + 300 x_coord = -Math.cos((n-1)/(4) * 3.14) * size y_coord = -Math.sin((n-1)/(4) * 3.14) * size } // ajout du noeud de branche nodes.push( {id: length, type:"GX", "label": gx, "group": gx.substring(0,2), x:x_coord, y:y_coord, fixed: true, size: 50, "shape": "box", "font": {"size":50} } ) length = nodes.length; } }) // ajout des uvs result.records.map(record => { var gx = record.get('gx'); attendances = record.get('attendances'); attendances.map( data => { // [cnt, uv] uv_node = data[1].properties; cnt = data[1].low; if ( uv[uv_node.code] === undefined){ // si le noeud n'a pas encore été ajouté nodes.push( {id: length,type:"UV", "label": uv_node.code, size: 50, "value": uv_node.degree.low , "group": uv_node.branche} ) uv[uv_node.code] = length; // set node id } edges.push( {"from": uv[uv_node.code], "to": genie[gx], "value": data[0].low ,"color": {"color": "#dddddd", "highlight": config.branches_color[gx.substring(0,2)]}} ) length = nodes.length; }) }) return {nodes: nodes, edges: edges, genie: genie, groupes: groupe} }) .catch(error => { session.close(); throw error; }); } exports.getUv = getUv; exports.getUvAttendance = getUvAttendance; exports.getSemestresAttendance = getSemestresAttendance; exports.getUvs = getUvs; exports.getGraphBranches = getGraphBranches2; exports.getUserUvs = getUserUvs; <file_sep>module.exports = { query: { limit: 10, max_limit: 50 }, neo4j: { user: "neo4j", password: "<PASSWORD>", port: "7687" }, branches: ["TC","GU","GI","IM","GB","GP", "GX"], branches_color: { TC: "#3498db", GU: "#e<PASSWORD>", GI: "#1abc9c", IM: "#f1c40f", GB: "#<PASSWORD>", GP: "#e74c3c", GX: "#888888" }, saison: ["A", "P"], types: ["CS", "TM", "TSH"] }; <file_sep># UVector A project aiming to make students' course selection easier. ## Deployment You just need **docker** to deploy UVector. On the root directory run make Or to run it on dev mode (you also need node and [nodemon](https://github.com/remy/nodemon)) make dev Once the server is deployed you need to add the data to neo4j. Go to the endpoint ```/setup/db``` once the server is done you also have to go to ```/setup/calc```. ## Screenshot ![Home](screenshots/home.png) <file_sep>-- phpMyAdmin SQL Dump -- version 3.3.7deb7 -- http://www.phpmyadmin.net -- -- Serveur: localhost -- Généré le : Lun 13 Juin 2016 à 15:55 -- Version du serveur: 5.1.73 -- Version de PHP: 5.3.3-7+squeeze19 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Base de données: `dbtest` -- -- -------------------------------------------------------- -- -- Structure de la table `Cursus` -- CREATE TABLE IF NOT EXISTS `Cursus` ( `loginEtudiant` varchar(8) NOT NULL, `codeUV` varchar(6) NOT NULL, `codeSemestre` char(5) NOT NULL, `GX` char(8) NOT NULL, `GX_DD` char(8) DEFAULT NULL, PRIMARY KEY (`loginEtudiant`,`codeUV`,`codeSemestre`), KEY `codeUV` (`codeUV`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `Cursus` -- INSERT INTO `Cursus` (`loginEtudiant`, `codeUV`, `codeSemestre`, `GX`, `GX_DD`) VALUES -- -------------------------------------------------------- -- -- Structure de la table `Etudiant` -- CREATE TABLE IF NOT EXISTS `Etudiant` ( `loginEtudiant` varchar(8) NOT NULL, PRIMARY KEY (`loginEtudiant`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `Etudiant` -- INSERT INTO `Etudiant` (`loginEtudiant`) VALUES -- -------------------------------------------------------- -- -- Structure de la table `UV` -- CREATE TABLE IF NOT EXISTS `UV` ( `codeUV` varchar(6) NOT NULL, `categorieUV` varchar(6) DEFAULT NULL, `nomUV` varchar(100) DEFAULT NULL, `nbCreditsUV` int(2) DEFAULT NULL, `descriptionUV` varchar(4000) DEFAULT NULL, PRIMARY KEY (`codeUV`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `UV` -- INSERT INTO `UV` (`codeUV`, `categorieUV`, `nomUV`, `nbCreditsUV`, `descriptionUV`) VALUES -- -- Contraintes pour les tables exportées -- -- -- Contraintes pour la table `Cursus` -- ALTER TABLE `Cursus` ADD CONSTRAINT `Cursus_ibfk_1` FOREIGN KEY (`loginEtudiant`) REFERENCES `Etudiant` (`loginEtudiant`), ADD CONSTRAINT `Cursus_ibfk_2` FOREIGN KEY (`codeUV`) REFERENCES `UV` (`codeUV`); <file_sep>import json import sys from ast import literal_eval as make_tuple filename = sys.argv[1] f = open(filename, 'r') names = ('id_etu', 'uv', 'semestre', 'gx', 'gxdd') #names = ['id_etu'] #names = ['codeUV', 'categorie', 'nom', 'credits', 'descriptionUV'] print(names) data = [] data_line = [] for line in f: line = line.replace('NULL', 'None') line = '[' + line[1:line.__len__()-2] + ']' line_dict = {} line_tuple = make_tuple(line) #print(line) #print(line_tuple) for x in range(names.__len__()): #print(x) line_dict[names[x]] = line_tuple[x] data_line.append(line_dict) if data_line.__len__() == 100: data.append(data_line) data_line = [] if ( data_line.__len__() != 0 ): data.append(data_line) with open(filename + '.json', 'w') as outfile: json.dump(data, outfile) f.close() <file_sep>var https = require('https'); var url = require('url'); var session = require('express-session'); /** * Initialize CAS with the given `options`. * * @param {Object} options * @api public */ var CAS = module.exports = function CAS(options) { options = options || {}; if (!options.base_url) { throw new Error('Required CAS option `base_url` missing.'); } if (!options.service) { throw new Error('Required CAS option `service` missing.'); } var cas_url = url.parse(options.base_url); if (cas_url.protocol != 'https:') { throw new Error('Only https CAS servers are supported.'); } else if (!cas_url.hostname) { throw new Error('Option `base_url` must be a valid url like: https://example.com/cas'); } else { this.hostname = cas_url.host; this.port = cas_url.port || 443; this.base_path = cas_url.pathname; } this.service = options.service; }; /** * Attempt to validate a given ticket with the CAS server. * `callback` is called with (err, auth_status, username) * * @param {String} ticket * @param {Function} callback * @api public */ CAS.prototype.validate = function(ticket, callback) { var cas = this var req = https.get({ host: this.hostname, port: this.port, path: url.format({ pathname: this.base_path+'serviceValidate', query: {ticket: ticket, service: this.service} }) }, function(res) { // Handle server errors res.on('error', function(e) { callback(e); }); // Read result res.setEncoding('utf8'); var response = ''; res.on('data', function(chunk) { response += chunk; }); res.on('end', function() { var regExp = /<cas:user>(.+)</; var matches = regExp.exec(response); var login = matches[1]; if (login.length == 8) { callback(undefined, true, login); return; } // Format was not correct, error callback({message: 'Bad response format.'}); }); }); }; <file_sep>// Button variables var network; var nodes = [] var edges = [] // update the network var filterBranch = []; var filterType = []; let saison = []; function updateGraph() { $("#graph-preloader").show(); filterBranch = []; filterType = []; saison = []; if (!$("#node_branch_TC").hasClass("btn-flat")) { filterBranch.push("TC"); } if (!$("#node_category_CS").hasClass("btn-flat")) { filterType.push("CS"); } if (!$("#node_category_TM").hasClass("btn-flat")) { filterType.push("TM"); } if (!$("#node_branch_GI").hasClass("btn-flat")) { filterBranch.push("GI"); } if (!$("#node_branch_GU").hasClass("btn-flat")) { filterBranch.push("GU"); } if (!$("#node_branch_IM").hasClass("btn-flat")) { filterBranch.push("IM"); } if (!$("#node_branch_GP").hasClass("btn-flat")) { filterBranch.push("GP"); } if (!$("#node_branch_GB").hasClass("btn-flat")) { filterBranch.push("GB"); } if (!$("#saison_A").hasClass("btn-flat")) { saison.push("A"); } if (!$("#saison_P").hasClass("btn-flat")) { saison.push("P"); } var JSONadress = "/api/v1/graphs/branches/?branches="+filterBranch+"&types="+filterType+"&saison="+saison; console.log(JSONadress) //JSONadress = "/api/v1/graphs/branches/?types=TSH" $.getJSON( JSONadress, function( data ) { var container = document.getElementById('vis-network'); console.log(data.groupes) var options = { layout: { improvedLayout: false, }, nodes: { shape: 'dot', size: 25 }, edges: { smooth: {type: 'continuous'}, selectionWidth: function (width) {return width*2;} }, groups: data.groupes, physics: { forceAtlas2Based: { gravitationalConstant: -100, centralGravity: 0.005, springLength: 230, springConstant: 0.18 }, maxVelocity: 150, solver: 'forceAtlas2Based', timestep: 0.35, stabilization: {iterations: 5} }, layout:{ improvedLayout: false }, interaction: { hideEdgesOnDrag: true, // tooltipDelay: 200, // dragNodes: false,// do not allow dragging nodes // zoomView: true, // do not allow zooming // dragView: true // do not allow dragging } }; var dataNodes = { "nodes": data['nodes'], "edges": data['edges'] }; $("#graph-preloader").fadeOut(100); network = new vis.Network(container, dataNodes, options); network.on("selectNode", function (params) { if (dataNodes.nodes[params.nodes[0]].type == "GX"){ // GX showGxCard(dataNodes.nodes[params.nodes[0]].label) } else { // UV showUvCard(dataNodes.nodes[params.nodes[0]].label) } } ); network.on("dragEnd", function (params) { if (dataNodes.nodes[params.nodes[0]] != undefined){ if (dataNodes.nodes[params.nodes[0]].type == "GX"){ // GX showGxCard(dataNodes.nodes[params.nodes[0]].label) } else { // UV showUvCard(dataNodes.nodes[params.nodes[0]].label) } } } ); network.on( 'click', function(properties) { if (properties.edges.length == 0){ $('#right-menu-gx').hide(); $('#right-menu-uv').hide(); } }); // Autocomplete $('#node-to-search').on('keyup', function(){ console.log('input') const search = data['nodes'].filter(node => node.label.startsWith($('#node-to-search').val().toUpperCase())).slice(0, 5); $('#dropdown').empty(); if(search){ for (var i = 0; i < search.length; i++) { name = '<span style="color: #9E9E9C;" class="truncate">' + search[i].label + '</span>'; $('#dropdown').append('<li><a href="#"><span class="node">' + name + '</span></a></li>'); } } }); // On autocomplete element click $('#dropdown').on('click', 'li', function(e){ let node = data['nodes'].find(node => node.label == $(this).find('a span.node').text()); network.selectNodes([node.id]) if ( node.type == "GX" ){ showGxCard(node.label) } else { showUvCard(node.label) } // network.zoomExtent(); // var nodePosition= {x: network.nodes[data['nodes'].find(node => node.label == $(this).find('a span.node').text()).id].x, y: network.nodes[data['nodes'].find(node => node.label == $(this).find('a span.node').text()).id].y}; // var canvasCenter = network.DOMtoCanvas({x:0.5 * network.frame.canvas.width,y:0.5 * network.frame.canvas.height}); // var translation = network._getTranslation(); // var requiredScale = 0.75; // var distanceFromCenter = {x:canvasCenter.x - nodePosition.x, // y:canvasCenter.y - nodePosition.y}; // network._setScale(requiredScale); // network._setTranslation(translation.x + requiredScale * distanceFromCenter.x,translation.y + requiredScale * distanceFromCenter.y); // network.redraw(); $('#node-to-search').val('') $('#dropdown').empty(); }); var dataBranches = data['genie']; }); //console.log("Types=",filterType,"Branches=",filterBranch); }; <file_sep>const config = require("../config/config"); const neo4j = require('neo4j-driver').v1; var _ = require("lodash"); const driver = neo4j.driver("bolt://neo4j:" + config.neo4j.port, neo4j.auth.basic( config.neo4j.user, config.neo4j.password)); const uvs = require('./uvs.txt.json') const etus = require('./etu.txt.json') const suit = require('./suit.txt.json') function insererUV(){ var session = driver.session(); return session .run( "MATCH (uv: UV) RETURN uv") .then(result => { session.close(); return res = result.records.map(record => { return new Uv(record.get('uv').properties); }) }) .catch(error => { session.close(); throw error; }); } function insererUv(uv){ var session = driver.session(); return session .run( "CREATE (:UV {code: {codeUV} , fullname: {nom} , type: {categorie}})", uv) .then(result => { session.close(); return result; }) .catch(error => { session.close(); throw error; }); } function changeGXNames(from , to){ var session = driver.session(); return session .run( "MATCH ()-[r:SUIT]->() WHERE r.GX =~ '" + from + ".*' SET r.GX = replace(r.GX, '" + from + "', '" + to + "') return null") .then(result => { session.close(); return result; }) .catch(error => { session.close(); throw error; }); } function calc(){ calcGX(); calcSaison(); } function calcGX(){ var session = driver.session(); return session .run( "MATCH ()-[r]->(uv) WHERE uv.type <> 'TSH' AND left(r.GX, 2) IN ['TC','GI','IM','GU','GB','GP'] WITH LEFT(r.GX, 2) as branche, uv as uv WITH [count(branche), branche] as branche, uv as uv ORDER BY branche[0] DESC WITH collect(branche) as branches, uv as uv SET uv.branche = branches[0][1]") .then(result => { session.close(); calcGX2() return result; }) .catch(error => { session.close(); throw error; }); } function calcGX2(){ var session = driver.session(); return session .run( "MATCH ()-[r]->(uv) WHERE uv.type <> 'TSH' AND left(r.GX, 2) IN ['TC','GI','IM','GU','GB','GP'] AND uv.degree > 100 WITH LEFT(r.GX, 2) as branche, uv as uv WITH toFloat(count(branche))/toFloat(uv.degree) as prop, branche as branche, uv as uv WITH stDev(prop) as dev,collect([prop, branche]) as prop, count(prop) as cnt, uv as uv WHERE cnt > 2 and dev < 0.2 SET uv.branche = 'GX'") .then(result => { session.close(); return result; }) .catch(error => { session.close(); throw error; }); } function calcSaison(){ var session = driver.session(); return session // WITH uv as uv, saison as saison, CASE WHEN prop < 0.05 THEN 0 WHEN prop > 0.95 THEN 1 END as prop .run( "MATCH ()-[r]->(uv) WHERE left(r.GX, 2) IN ['TC','GI','IM','GU','GB','GP'] WITH uv as uv, left(r.codeSemestre,1) as saison WITH uv as uv, count(saison) as cnt, saison as saison WITH uv as uv, toFloat(cnt)/toFloat(uv.degree) as prop, saison as saison WITH uv as uv, collect(saison + ':' + toString(prop) ) as prop SET uv.saison = prop") .then(result => { session.close(); return result; }) .catch(error => { session.close(); throw error; }); } function calcDeg(){ var session = driver.session(); return session .run( "MATCH (p:Person)-[r:SUIT]->(uv:UV) WHERE left(r.GX, 2) IN ['TC','GI','IM','GU','GB','GP'] WITH count(r) as cnt, uv.code as code MATCH (uv:UV {code: code}) SET uv.degree = cnt ") .then(result => { session.close(); return result; }) .catch(error => { session.close(); throw error; }); } function insererSuit(suit){ var session = driver.session(); return session .run( "MATCH (a:Person {id: {id_etu} }),(b:UV {code: {uv} }) CREATE (a)-[r:SUIT {codeSemestre: {semestre} , GX: {gx} }]->(b)", suit) .then(result => { session.close(); return result; }) .catch(error => { session.close(); throw error; }); } function insererRec(tab, i, query, callback, pas = 1 ){ var session = driver.session(); if ( i < tab.length ){ var promises = []; tab[i].forEach( (element) => { promises.push( session.run(query, element) ) }) Promise.all(promises) .then( (results) => { session.close(); console.log('"' + query + '"' + (i+1) + "/" + tab.length) insererRec(tab, i+pas, query, callback, pas); }) .catch( (error) => { session.close(); }) } else if (i == tab.length) { console.log(query + " : Done !") console.log(callback) if ( callback !== undefined ){ callback(); } } } function dropDB(){ var session = driver.session(); return session .run( "match (n) detach delete n") .then(result => { session.close(); return result; }) .catch(error => { session.close(); throw error; }); } function inserMulti(tab, n, query, callback){ for ( var i = 0; i < n; i ++){ insererRec(tab, i, query, callback, n); } } function setupDB(){ dropDB().then( () => { inserMulti(uvs, 5,"CREATE (:UV {code: {codeUV} , fullname: {nom} , type: {categorie}})"); inserMulti(etus, 5, "CREATE (:Person {id: {id_etu} })", function() { inserMulti(suit, 20, "MATCH (a:Person {id: {id_etu} }),(b:UV {code: {uv} }) CREATE (a)-[r:SUIT {codeSemestre: {semestre} , GX: {gx} }]->(b)", function(){ changeGXNames("GSU", "GU") changeGXNames("GSM", "IM") changeGXNames("GM", "IM") calcDeg() }) }) //insererListeSuit(); }); } exports.setupDB = setupDB; exports.calc = calc; <file_sep>var schemas = require("../schemas/schemas.js"); var _ = require("lodash"); var Uv = function (data) { this.data = this.sanitize(data); } Uv.prototype.sanitize = function (data) { data = data || {}; schema = schemas.uv; let saison = {}; data.saison.forEach( (prop) => { let tab = prop.split(":"); saison[tab[0]] = parseFloat(tab[1]); }) data.saison = _.pick(_.defaults(saison, {A:0, P:0}), ["A", "P"]); return _.pick(_.defaults(data, schema), _.keys(schema)); } Uv.prototype.data = {} module.exports = Uv;
d780a3096cebc524dff469dc69b0c0eeff7dc270
[ "JavaScript", "SQL", "Python", "Markdown" ]
11
JavaScript
bloriot97/UVector
06a88b49de53855f6df6084f8cac063db286d6f5
eebb13766c54e29e28428d9655b6c3e98f9dee19
refs/heads/master
<repo_name>KristianWB/ItJP_Exercise_3_31<file_sep>/src/CurrencyExchange.java import java.util.Scanner; public class CurrencyExchange { public static void main(String[] args) { Scanner input = new Scanner(System.in); double exchangeRateTemp; System.out.print( "Enter the exchange rate from US dollars to Chinese RMB: " ); double exchangeRate = input.nextDouble(); System.out.print( "Press 0 if you are exchanging dollars to Chinese RMB and press 1 if you are exchanging fra Chinese RMB to US dollars: " ); int choice = input.nextInt(); if (choice == 0) System.out.println( "You chose US dollars to Chinese RMB" ); else System.out.println( "You choose to exchange from Chinese RMB to US dollars" ); System.out.print( "Enter the amount you want to exchange: " ); double amount = input.nextDouble(); if (choice == 1) { exchangeRateTemp = exchangeRate; exchangeRate = 1 / exchangeRateTemp; } if (choice == 0) System.out.print( "You have changed " + amount + " US Dollars to " + (amount * exchangeRate) + " Chinese RMB" ); else System.out.print( "You have changed " + amount + " Chinese RMB to " + (amount * exchangeRate) + " US Dollars" ); } }
6f98a77c1a41dd3eaba1bd43dd02386349882562
[ "Java" ]
1
Java
KristianWB/ItJP_Exercise_3_31
b7370122a9b25cd9df13ffaafc8b853ba401a3f3
9517668d40ba35f064243c93a0f28a0a89e1ef0a
refs/heads/master
<file_sep># Yet Another Pig Latin Converter ### Converts strings into pig latin Exposes a single function, `changePhrase`, that accepts a string argument, and returns a pig-latinised string. Examples: var pigLatin = reqiure('yapiglatin').changePhrase; console.log(pigLatin('test')) // esttay console.log(pitLatin('Hello World')) // ellohay orldway ### Todo: - non-english characters - hyphenated words and other punctuation - are there any situations where 'y' counts as a vowel? - how to handle silent consonents at the beginnings of words - capitalised characters <file_sep>'use strict'; // Standard test. Originally cribbed from: // http://stackoverflow.com/questions/4059147/check-if-a-variable-is-a-string var isString = function (text) { return typeof text === 'string' || text instanceof String; }; // Probably more efficient to compare chars rather than regex, but it's likely // the words we're testing will be relatively short. // @todo: non-english characters? // @todo: hyphenated words and other punctuation? var isAllLetters = function (word) { return word.match(/^[a-z]+$/i); }; // Again, could do this with a regex, but there are only five vowels, so it // seems like overkill. // @todo: any situations in which 'y' starts a word with a vowel sound? var isVowel = function (letter) { return ['a', 'e', 'i', 'o', 'u'].indexOf(letter) >= 0; }; // Find the index of the first vowel // Recursive for fun. var firstVowel = function (index, word) { if (index < 0 || index > word.length) { return -1; } if (isVowel(word[index]) || index === word.length) { return index; } return firstVowel(++index, word); }; var changeWord = function (word) { if (!word || !isString(word)) { return ''; } // @todo: preserve case? var lcWord = word.toLowerCase(); if (!isAllLetters(word)) { return lcWord; } // @todo: how to detect silent consonents? var splitPoint = firstVowel(0, lcWord); // Debating whether separate if-statements is more legible. // It's unlikely that we'll ever need to add more cases. switch (splitPoint) { // If firstVowel returned an error. case -1: return lcWord; // If the first letter is a vowel case 0: return lcWord + 'way'; // If the word contains no vowels, return the word. case word.length: return lcWord; // Return the pig latin default: var beforeFirstVowel = lcWord.slice(0, splitPoint); var afterFirstVowel = lcWord.slice(splitPoint); return afterFirstVowel + beforeFirstVowel + 'ay'; } }; // @todo: Do things with capitalisation of first letter // @todo: Do things with punctuation at the end of the sentence. var changePhrase = function (sentence) { if (!sentence || !isString(sentence)) { return ''; } return sentence.split(' ').map(changeWord).join(' '); }; if(typeof require === 'function'){ exports.changePhrase = changePhrase; } <file_sep>/*global describe, it, after, before, afterEach, beforeEach*/ /*jshint expr:true*/ /*jshint unused:false*/ 'use strict'; var pigLatin = require('../index.js').changePhrase; var should = require('should'); describe('Pig Latin', function () { it('should not fail when incorrect values are sent', function (done) { pigLatin('').should.eql(''); pigLatin(123).should.eql(''); pigLatin(false).should.eql(''); pigLatin(true).should.eql(''); pigLatin('123').should.eql('123'); pigLatin('test123').should.eql('test123'); pigLatin({}).should.eql(''); pigLatin({fail: '123'}).should.eql(''); return done(); }); it('converts consonent-starting words', function (done) { pigLatin('pig').should.eql('igpay'); pigLatin('banana').should.eql('ananabay'); pigLatin('trash').should.eql('ashtray'); pigLatin('happy').should.eql('appyhay'); pigLatin('duck').should.eql('uckday'); pigLatin('glove').should.eql('oveglay'); return done(); }); it('converts vowel-starting words', function (done) { pigLatin('egg').should.eql('eggway'); pigLatin('inbox').should.eql('inboxway'); pigLatin('eight').should.eql('eightway'); return done(); }); it('converts potential-gotcha words', function (done) { pigLatin('TEST').should.eql('esttay'); pigLatin('false').should.eql('alsefay'); pigLatin('true').should.eql('uetray'); pigLatin('rhythm').should.eql('rhythm'); pigLatin('the').should.eql('ethay'); return done(); }); it('converts sentences', function (done) { pigLatin('Hello World').should.eql('ellohay orldway'); return done(); }) });
74313cf002e80b27194d8fa2f56bfabf379713c2
[ "Markdown", "JavaScript" ]
3
Markdown
tomruttle/node-yapiglatin
df7183cf633c66c7918db8148a3414adf14cbcd9
6cc19928887745d49b294124d8ec8cee219bd186
refs/heads/master
<repo_name>Palamax/ecoleg<file_sep>/ecoleg/modele/m_session.php <?php class m_session{ private $base_de_donnee; public function __construct($base_de_donnee){ $this->base_de_donnee = $base_de_donnee; } /* Vérifie les cookies de session */ public function vérification_cookie() { $vérification_cookie = $this->base_de_donnee->prepare('SELECT id FROM utilisateurs WHERE id = ? AND password = ?'); $vérification_cookie->bindValue(1, $_COOKIE['u'], PDO::PARAM_INT); $vérification_cookie->bindValue(2, $_COOKIE['p'], PDO::PARAM_STR); $vérification_cookie->execute(); $retour_vérif = $vérification_cookie->fetch(PDO::FETCH_OBJ); return $retour_vérif->id; } /* ############################## # statistiques ############################## */ // Verifie si l'utilisateur connectés est présent ou non dans la table cpt_connectes public function is_utilisateurs_connectes_existe($ip){ $is_utilisateurs_connectes_existe = $this->base_de_donnee->prepare('SELECT COUNT(ip) as nb FROM cpt_connectes where ip = ?'); $is_utilisateurs_connectes_existe->bindValue(1, $ip, PDO::PARAM_STR); $is_utilisateurs_connectes_existe->execute(); $retour = $is_utilisateurs_connectes_existe->fetch(PDO::FETCH_ASSOC); $is_utilisateurs_connectes_existe->closeCursor(); return $retour; } // Retourne le nombre d'utilisateurs connectés public function get_nombre_utilisateurs_connectes(){ $get_nb_utilisateurs = $this->base_de_donnee->prepare('SELECT COUNT(ip) as nb FROM cpt_connectes'); $get_nb_utilisateurs->execute(); $retour = $get_nb_utilisateurs->fetch(PDO::FETCH_ASSOC); $get_nb_utilisateurs->closeCursor(); return $retour; } // Met à jour le nombre d'utilisateurs connectés public function update_nombre_utilisateurs_connectes($ip){ $update_nb_utilisateurs = $this->base_de_donnee->prepare('UPDATE cpt_connectes SET timestamp = ? WHERE ip = ?'); $update_nb_utilisateurs->bindValue(1, time(), PDO::PARAM_STR); $update_nb_utilisateurs->bindValue(2, $ip, PDO::PARAM_STR); $update_nb_utilisateurs->execute(); } // Ajout un utilisateur connecté public function add_utilisateur_connecte($ip){ $add_utilisateur_connecte = $this->base_de_donnee->prepare('INSERT INTO cpt_connectes (ip, timestamp) VALUES (?, ?) '); $add_utilisateur_connecte->bindValue(1, $ip, PDO::PARAM_STR); $add_utilisateur_connecte->bindValue(2, time(), PDO::PARAM_STR); $add_utilisateur_connecte->execute(); } // Supprime un utilisateur connecté public function delete_utilisateur_connecte($time){ $delete_utilisateur_connecte = $this->base_de_donnee->prepare('DELETE FROM cpt_connectes WHERE timestamp < ?'); $delete_utilisateur_connecte->bindValue(1, $time, PDO::PARAM_STR); $delete_utilisateur_connecte->execute(); } /* Tiens à jour le nombre de visite Information : - INSERT s'il n'existe - UPDATE s'il existe Le tout en une requête grâce : si le tuple existe déjà (clé primaire ip + date), grâce à la clause ON DUPLICATE KEY on incrément le champ page_vue de 1 pour le tuple en question (ip + date) */ public function compter_visite($ip, $date){ $compter_visite = $this->base_de_donnee->prepare('INSERT INTO cpt_visites (ip , date_visite , pages_vues) VALUES (?, ?, 1) ON DUPLICATE KEY UPDATE pages_vues = pages_vues + 1'); $compter_visite->bindValue(1, $ip, PDO::PARAM_STR); $compter_visite->bindValue(2, $date, PDO::PARAM_STR); $compter_visite->execute(); } /* Compte le nombre de visites total et le nombre de pages vues */ public function get_nbr_visite(){ $get_nbr_visite = $this->base_de_donnee->prepare('SELECT COUNT(ip) as nbVisite, SUM(pages_vues) as nbPageVues FROM cpt_visites'); $get_nbr_visite->execute(); $retour = $get_nbr_visite->fetch(PDO::FETCH_ASSOC); $get_nbr_visite->closeCursor(); return $retour; } /* retourne toutes les informations de la table visites */ public function liste_table_visite($numPage){ // Calcul num page - 1 * nbr element par page $calcul = ($numPage - 1) * NB_ELEMENT_PAGE_LISTE_STATISTIQUES; $liste_table_visite = $this->base_de_donnee->prepare('SELECT * FROM cpt_visites LIMIT ?,' . NB_ELEMENT_PAGE_LISTE_STATISTIQUES); $liste_table_visite->bindValue(1, $calcul, PDO::PARAM_INT); $liste_table_visite->execute(); $retour = $liste_table_visite->fetchAll(PDO::FETCH_OBJ); $liste_table_visite->closeCursor(); return $retour; } /* retourne toutes les informations de la table visites ordonné par le param */ public function liste_table_visite_order_by($numPage, $order){ // Calcul num page - 1 * nbr element par page $calcul = ($numPage - 1) * NB_ELEMENT_PAGE_LISTE_STATISTIQUES; $liste_table_visite = $this->base_de_donnee->prepare('SELECT * FROM cpt_visites ORDER BY ? DESC LIMIT ?,' . NB_ELEMENT_PAGE_LISTE_STATISTIQUES); $liste_table_visite->bindValue(1, $order, PDO::PARAM_STR); $liste_table_visite->bindValue(2, $calcul, PDO::PARAM_INT); $liste_table_visite->execute(); $retour = $liste_table_visite->fetchAll(PDO::FETCH_OBJ); $liste_table_visite->closeCursor(); return $retour; } } ?><file_sep>/ecoleg/modele/m_groupe.php <?php class m_groupe{ private $base_de_donnee; public function __construct($base_de_donnee){ $this->base_de_donnee = $base_de_donnee; } public function getAllGroupe(){ $connexion = $this->base_de_donnee->prepare('SELECT * FROM groupe'); $connexion->execute(); $retour = $connexion->fetchAll(PDO::FETCH_OBJ); $connexion->closeCursor(); return $retour; } public function getGroupe($id){ $requete = $this->base_de_donnee->prepare('SELECT * FROM groupe where ID = ?'); $requete->bindValue(1, $id, PDO::PARAM_INT); $requete->execute(); $retour = $requete->fetch(PDO::FETCH_OBJ); $requete->closeCursor(); return $retour; } /* PERMET D'AJOUTER UN Groupe */ public function modifierGroupe($libelle, $destination, $id){ $modifierGroupe = $this->base_de_donnee->prepare('UPDATE groupe SET LIBELLE = ?, DESTINATION = ? where ID = ?'); $modifierGroupe->bindValue(1, $libelle, PDO::PARAM_STR); $modifierGroupe->bindValue(2, $destination, PDO::PARAM_STR); $modifierGroupe->bindValue(3, $id, PDO::PARAM_INT); $modifierGroupe->execute(); } /* PERMET DE CREER UN Groupe */ public function creerGroupe($libelle, $destination){ $creerGroupe = $this->base_de_donnee->prepare('INSERT INTO groupe (LIBELLE, DESTINATION) values (?, ?) '); $creerGroupe->bindValue(1, $libelle, PDO::PARAM_STR); $creerGroupe->bindValue(2, $destination, PDO::PARAM_STR); $creerGroupe->execute(); $lastId = $this->base_de_donnee->lastInsertId(); return $lastId; } /* PERMET DE SUPPRESSION D'UN Groupe */ public function deleteGroupe($id){ $deleteGroupe = $this->base_de_donnee->prepare('DELETE FROM groupe where ID = ?'); $deleteGroupe->bindValue(1, $id, PDO::PARAM_INT); $deleteGroupe->execute(); } public function getDerniereDateCovoiturage($idGroupe){ $connexion = $this->base_de_donnee->prepare('SELECT MAX(gp.DATE_CONDUCTEUR) as MAX FROM groupe as g INNER JOIN groupePassager as gp on gp.ID_GROUPE = g.ID where g.ID = ?'); $connexion->bindValue(1, $idGroupe, PDO::PARAM_INT); $connexion->execute(); $retour = $connexion->fetch(PDO::FETCH_OBJ); $connexion->closeCursor(); return $retour; } } ?><file_sep>/ecoleg/SQL/init.sql -- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Hôte : 127.0.0.1:3306 -- Généré le : ven. 16 mars 2018 à 10:15 -- Version du serveur : 5.7.19 -- Version de PHP : 5.6.31 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `covoiturage` -- -- -------------------------------------------------------- -- -- Structure de la table `covoiturage` -- DROP TABLE IF EXISTS `covoiturage`; CREATE TABLE IF NOT EXISTS `covoiturage` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ADRESSE` varchar(255) NOT NULL, `ID_GROUPE` int(11) NOT NULL, PRIMARY KEY (`ID`), KEY `FK_covoiturage_groupe` (`ID_GROUPE`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `covoiturage` -- INSERT INTO `covoiturage` (`ID`, `ADRESSE`, `ID_GROUPE`) VALUES (1, '81570 Fréjeville, France', 1), (2, 'Route de Lautrec, 81100 Castres, France', 1); -- -------------------------------------------------------- -- -- Structure de la table `groupe` -- DROP TABLE IF EXISTS `groupe`; CREATE TABLE IF NOT EXISTS `groupe` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `LIBELLE` varchar(255) NOT NULL, `DESTINATION` varchar(255) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `groupe` -- INSERT INTO `groupe` (`ID`, `LIBELLE`, `DESTINATION`) VALUES (1, 'Groupe a  3', '5 Rue Jean Borotra, 81000 Albi, France'); -- -------------------------------------------------------- -- -- Structure de la table `groupepassager` -- DROP TABLE IF EXISTS `groupepassager`; CREATE TABLE IF NOT EXISTS `groupepassager` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ID_PASSAGER` int(11) NOT NULL, `ID_GROUPE` int(11) NOT NULL, `COMPTEUR` int(11) DEFAULT '0', `KMS` int(11) DEFAULT '0', `DATE_CONDUCTEUR` date DEFAULT NULL, `ECONOMIE` int(11) DEFAULT '0' PRIMARY KEY (`ID`), UNIQUE KEY `indexGroupePassager` (`ID_GROUPE`,`ID_PASSAGER`), KEY `FK_groupePassager_passager` (`ID_PASSAGER`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `groupepassager` -- INSERT INTO `groupepassager` (`ID`, `ID_PASSAGER`, `ID_GROUPE`, `COMPTEUR`, `KMS`, `DATE_CONDUCTEUR`) VALUES (1, 1, 1, 0, 0, NULL), (2, 2, 1, 0, 0, NULL), (3, 3, 1, 0, 0, NULL); -- -------------------------------------------------------- -- -- Structure de la table `passager` -- DROP TABLE IF EXISTS `passager`; CREATE TABLE IF NOT EXISTS `passager` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NOM` varchar(100) NOT NULL, `PRENOM` varchar(100) NOT NULL, `ADRESSE` varchar(255) NOT NULL, `EMAIL` varchar(100) NOT NULL, `TELEPHONE` varchar(20) DEFAULT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `EMAIL` (`EMAIL`) ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `passager` -- INSERT INTO `passager` (`ID`, `NOM`, `PRENOM`, `ADRESSE`, `EMAIL`, `TELEPHONE`) VALUES (1, 'VALERY', 'Stephane', '<NAME>, 81710 Saix, France', '<EMAIL>', '06.87.80.58.35'), (2, 'GAIGNARD', 'Rene-Louis', '81700 Puylaurens, France', '<EMAIL>', '06.87.80.58.35'), (3, 'FAURE', 'Thierry', 'En Priou, 81580 Cambounet-sur-le-Sor, France', '<EMAIL>', '06.87.80.58.35'); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/ecoleg/controleur/covoiturages.php <?php /**** SESSION ****/ session_start(); /**** CLASS CONTROLEUR ****/ require_once('class/c_session.php'); require_once('class/t_texte.php'); /**** MODELE ****/ require_once('modele/m_session.php'); require_once('modele/m_groupe.php'); /**** OBJETS ****/ $t_texte = new t_texte(); $m_session = new m_session($base_de_donnee); $m_groupe = new m_groupe($base_de_donnee); $c_session = new c_session($m_session, $t_texte); /**** VERIF SESSION ****/ $c_session->session(); $liste_groupe = $m_groupe->getAllGroupe(); $idGroupe = null; if(!empty($url_param[0])) { if(preg_match('#^[0-9]{1,}$#', $url_param[0])) { $idGroupe = $url_param[0]; if($idGroupe != null){ $m_groupe->deleteGroupe($idGroupe); $liste_groupe = $m_groupe->getAllGroupe(); } } } ?><file_sep>/ecoleg/vue/covoiturages.php <div class="jumbotron"> <h1> Covoiturage</h1> <p class="lead"><i>Sélectionner le groupe de covoiturage concerné</i></p> </div> <div class="col-md-12"> <table class="table table-striped custab"> <thead> <tr> <th>ID</th> <th>LIBELLE</th> <th>Destination</th> <th class="text-center">Action</th> </tr> </thead> <?php foreach($liste_groupe as $groupe){ ?> <tr> <td><?php echo $groupe->ID; ?></td> <td><?php echo $groupe->LIBELLE; ?></td> <td><?php echo $groupe->DESTINATION; ?></td> <td class="text-center"> <a class='btn btn-info btn-xs' href="<?php echo ADRESSE_ABSOLUE_URL . 'covoiturage/' . $groupe->ID; ?>"><span class="glyphicon glyphicon-edit"></span> GO !!</a> </tr> <?php } ?> </table> </div><file_sep>/ecoleg/vue/groupes.php <div class="jumbotron"> <h1>Liste des groupes</h1> <p class="lead"></p> </div> <div class="col-md-12"> <table class="table table-striped custab"> <thead> <a href="<?php echo ADRESSE_ABSOLUE_URL . 'groupe'; ?>" class="btn btn-primary btn-xs pull-right"><b>+</b> Nouveau groupe</a> <tr> <th>Id</th> <th>Libellé</th> <th>Destination</th> <th class="text-center">Action</th> </tr> </thead> <?php foreach($liste_groupe as $groupe){ ?> <tr> <td><?php echo $groupe->ID; ?></td> <td><?php echo $groupe->LIBELLE; ?></td> <td><?php echo $groupe->DESTINATION; ?></td> <td class="text-center"> <a class='btn btn-info btn-xs' href="<?php echo ADRESSE_ABSOLUE_URL . 'groupe/' . $groupe->ID; ?>"><span class="glyphicon glyphicon-edit"></span></a> <a href="<?php echo ADRESSE_ABSOLUE_URL . 'groupes/' . $groupe->ID; ?>" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span></a></td> </tr> <?php } ?> </table> </div> <file_sep>/ecoleg/controleur/class/f_formulaire.php <?php class f_formulaire { public function verify_name($name){ if (!preg_match("/^[a-zA-Z ]*$/",$name)) { return 8; } return 0; } public function verify_email($email){ if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return 9; } return 0; } public function verify_url($website){ if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { return 10; } return 0; } /* NEVER TRUST USER INPUT MY FRIEND */ public function testInputData($data) { $data = trim($data);// Supprime espace en début et fin de chaine $data = stripslashes($data); // Déspécialise les anti slash $data = htmlspecialchars($data); // Evite l'exécution de code return $data; } /* FILE UPLOADER md5(uniqid()) */ public function uploadPicture($p_FILES, $target, $nomFichier){ $message = -1; if(!is_dir($target)){ return $message = 16; } if(!empty($p_FILES['fichier']['name'])){ //1. strrchr renvoie l'extension avec le point (« . »). //2. substr(chaine,1) ignore le premier caractère de chaine. //3. strtolower met l'extension en minuscules. $extension_upload = strtolower(substr(strrchr($p_FILES['icone']['name'], '.'),1)); if (in_array($extension_upload, $extensions_valides)){ // Si extension ok if($p_FILES['fichier']['size'] <= UPLOAD_MAX_SIZE){ // On vérifier la taille // Parcours du tableau d'erreurs if(isset($_FILES['fichier']['error']) && UPLOAD_ERR_OK === $_FILES['fichier']['error']){ $nom = $target . $nomFichier . '.' . $extension_upload; // On forme le nom $resultat = move_uploaded_file($p_FILES['icone']['tmp_name'], $nom); if ($resultat){ return $message = 17; } }else{ return $message = 18; } }else{ return $message = 19; } }else{ return $message = 20; } }else{ return $message = 21; } } } ?><file_sep>/ecoleg/vue/accueil.php <div class="jumbotron"> <h1>Accueil</h1> <p class="lead"><i>Le TOP des covoitureurs</i></p> </div> <div class="col-md-12"> <table class="table table-striped custab"> <thead> <tr> <th>Nom</th> <th>Prenom</th> <th>Compteur</th> <th>Kms</th> <th>Economie</th> </tr> </thead> <?php foreach($statistique as $stat){ ?> <tr> <td><?php echo $stat->NOM; ?></td> <td><?php echo $stat->PRENOM; ?></td> <td><?php echo $stat->CPT; ?></td> <td><?php echo $stat->KMS; ?></td> <td><?php echo $stat->ECO; ?></td> </tr> <?php } ?> </table> </div><file_sep>/ecoleg/vue/passager.php <?php if($idPassager != null){ ?> <!-- modifier un passager --> <div class="jumbotron"> <h1>Modification du passager</h1> <p class="lead"><i>Le passager est defini par un nom, un prenom et une adresse</i></p> </div> <div class="container"> <form class="form-horizontal" method="post" action=""> <div class="col-md-10"> <div class="form-group"> <div class="col-sm-offset-2"> <span style="clear:both"></span> <p> Nom : <input type="text" class="form-control" id="nom" name="nom" value="<?php echo $passager->NOM; ?>" placeholder="Nom" required> </p> <p> Prénom : <input type="text" class="form-control" id="prenom" name="prenom" value="<?php echo $passager->PRENOM; ?>" placeholder="Prenom" required> </p> <p> <span clas="form-control"> Adresse : </span> </p> <p> <input type="text" id="adresse" name="adresse" value="<?php echo $passager->ADRESSE; ?>" class="form-control form-control-inline" onfocus="javascript:$('#myModal').modal('show');" readonly /> </p> <p> Téléphone : <input type="text" class="form-control" id="telephone" name="telephone" placeholder="Téléphone" value="<?php echo $passager->TELEPHONE; ?>"> </p> <p> Email : <input type="text" class="form-control" id="email" name="email" placeholder="email" value="<?php echo $passager->EMAIL; ?>"> </p> </div> </div> <div class="form-group"> <div class="col-sm-offset-6"> <input type="submit" class="btn btn btn-success" value="Enregistrer"/> </div> </div> </div> </form> </div> <?php }else{ ?> <!-- ajouter un passager --> <div class="jumbotron"> <h1>Création du passager</h1> <p><i>Le passager est defini par un nom, un prenom et une adresse</i></p> </div> <div class="container"> <form class="form-horizontal" method="post" action=""> <div class="col-md-10"> <div class="form-group"> <div class="col-sm-offset-2"> <span style="clear:both"></span> <p> Nom : <input type="text" class="form-control" id="nom" name="nom" placeholder="Nom" required> </p> <p> Prénom : <input type="text" class="form-control" id="prenom" name="prenom" placeholder="Prenom" required> </p> <p> <span clas="form-control"> Adresse : </span> </p> <p> <input type="text" id="adresse" name="adresse" class="form-control form-control-inline" onfocus="javascript:$('#myModal').modal('show');" readonly /> </p> <p> Téléphone : <input type="text" class="form-control" id="telephone" name="telephone" placeholder="Téléphone"> </p> <p> Email : <input type="text" class="form-control" id="email" name="email" placeholder="email"> </p> </div> </div> <div class="form-group"> <div class="col-sm-offset-6"> <input type="submit" class="btn btn btn-success" value="Enregistrer"/> </div> </div> </div> </form> </div> <?php } ?> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title" id="myModalLabel">Rechercher votre adresse</h4> </div> <div class="modal-body"> <input type="text" id="adresseRecherchee" placeholder="Recherchez votre adresse" class="form-control form-control-inline"/> <a href="#" onclick="showLocation('adresseRecherchee', 'adresse');javascript:$('#myModal').modal('hide');"><span class="glyphicon glyphicon-map-marker form-control-inline"></a> </div> </div> </div> </div><file_sep>/ecoleg/modele/m_groupePassager.php <?php class m_groupePassager{ private $base_de_donnee; public function __construct($base_de_donnee){ $this->base_de_donnee = $base_de_donnee; } public function getPassagerByGroupe($idGroupe){ $connexion = $this->base_de_donnee->prepare('SELECT gp.ID, p.NOM, p.PRENOM, p.ADRESSE, gp.KMS, gp.COMPTEUR, gp.ECONOMIE FROM groupepassager as gp INNER JOIN passager as p on gp.ID_PASSAGER = p.ID where ID_GROUPE = ? order by gp.COMPTEUR, gp.DATE_CONDUCTEUR'); $connexion->bindValue(1, $idGroupe, PDO::PARAM_INT); $connexion->execute(); $retour = $connexion->fetchAll(PDO::FETCH_OBJ); $connexion->closeCursor(); return $retour; } public function getStatistique(){ $connexion = $this->base_de_donnee->prepare('SELECT p.ID, p.NOM, p.PRENOM, SUM(gp.COMPTEUR) as CPT, SUM(gp.KMS) as KMS, SUM(gp.ECONOMIE) as ECO FROM groupepassager as gp INNER JOIN passager as p on gp.ID_PASSAGER = p.ID group by p.ID, p.NOM, p.PRENOM order by ECO desc'); $connexion->execute(); $retour = $connexion->fetchAll(PDO::FETCH_OBJ); $connexion->closeCursor(); return $retour; } /* PERMET D'AJOUTER UN Groupe */ public function ajouterGroupePassager($idGroupe, $idPassager){ $lastId = null; try { $ajouterGroupePassager = $this->base_de_donnee->prepare('INSERT groupePassager SET ID_GROUPE = ?, ID_PASSAGER = ?, COMPTEUR=0, KMS=0, ECONOMIE=0'); $ajouterGroupePassager->bindValue(1, $idGroupe, PDO::PARAM_INT); $ajouterGroupePassager->bindValue(2, $idPassager, PDO::PARAM_INT); $ajouterGroupePassager->execute(); } catch (Exception $e) { if(strstr($e->getMessage(), 'SQLSTATE[23000]')) { throw new Exception('Ce passager appartient déjà à ce groupe.'); }else{ throw new Exception('Erreur technique !!'); } } finally { $lastId = $this->base_de_donnee->lastInsertId(); } return $lastId; } /* PERMET DE SUPPRESSION D'UN GroupePassager */ public function deleteGroupePassager($id){ $deletePassager = $this->base_de_donnee->prepare('DELETE FROM groupePassager where ID = ?'); $deletePassager->bindValue(1, $id, PDO::PARAM_INT); $deletePassager->execute(); } /* PERMET D'AJOUTER les kms */ public function ajouterKmsConducteur($idGroupePassager, $kms){ $ajouterKms = $this->base_de_donnee->prepare('UPDATE groupePassager SET COMPTEUR = COMPTEUR + 1, DATE_CONDUCTEUR = CURRENT_TIMESTAMP, KMS = KMS + ? where ID = ?'); $ajouterKms->bindValue(1, $kms, PDO::PARAM_INT); $ajouterKms->bindValue(2, $idGroupePassager, PDO::PARAM_INT); $ajouterKms->execute(); } public function ajouterKmsPassager($idGroupePassager, $kms, $economie){ $ajouterKms = $this->base_de_donnee->prepare('UPDATE groupePassager SET KMS = KMS + ?, ECONOMIE = ECONOMIE + ? where ID = ?'); $ajouterKms->bindValue(1, $kms, PDO::PARAM_INT); $ajouterKms->bindValue(2, $economie, PDO::PARAM_INT); $ajouterKms->bindValue(3, $idGroupePassager, PDO::PARAM_INT); $ajouterKms->execute(); } } ?><file_sep>/ecoleg/vue/footer.php <!-- Footer --> <footer class="container" style="margin:auto; text-align:center;"> <div class="col-md-11"> <p style="font-size: 12px;"> Site web fait par <NAME> - PHP - CSS Bootstrap </p> </div> <div class="col-md-1"> <a class="up-arrow" href="#top" data-toggle="tooltip" title="" data-original-title="TO TOP" style="color:black;"> <span class="glyphicon glyphicon-chevron-up"></span> </a> </div> </footer> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="<?php echo ADRESSE_ABSOLUE_URL . 'js/bootstrap.min.js'; ?>"></script> </body> </html><file_sep>/ecoleg/vue/covoiturage.php <div class="jumbotron"> <h1>Covoiturage &#8239;<span class="badge"><?php echo $groupe->LIBELLE; ?></span> <span> &#8239;<span title="Destination" class="badge"><span class="glyphicon glyphicon-flag">&#8239;<?php echo $groupe->DESTINATION; ?></span> </span> </h1> <p class="lead"><i>Veuillez sélectionner le point de covoiturage et le conducteur</i></p> </div> <div class="container"> <div class="row col-md-12"> <form class="form-horizontal" method="post" action=""> <div class="form-group"> <span style="clear:both"></span> <?php if (!$isConsultation){ ?> <p> Point de covoiturage : <select id="adresseCovoiturage" name="adresseCovoiturage" class="form-control"> <option value="" selected="selected"></option> <?php foreach($liste_covoiturage as $covoiturage){ ?> <option value="<?php echo $covoiturage->ADRESSE; ?>"><?php echo $covoiturage->ADRESSE; ?></option> <?php } ?> </select> </p> <p> Conducteur : <select id="idGroupePassager" name="idGroupePassager" class="form-control"> <option value="" selected="selected"></option> <?php foreach($liste_groupePassager as $groupePassager){ ?> <option value="<?php echo $groupePassager->ID; ?>"><?php echo $groupePassager->NOM . ' ' . $groupePassager->PRENOM;?></option> <?php } ?> </select> </p> <?php } ?> </div> <div class="panel panel-default"> <div class="panel-heading">Liste des passagers</div> <div class="panel-body"> <table class="table table-striped custab"> <thead> <tr> <th>NOM</th> <th>PRENOM</th> <th>COMPTEUR</th> <th>KMS</th> <th>ECONOMIE</th> <th></th> </tr> </thead> <?php $i = 0; foreach($liste_groupePassager as $groupePassager){ ?> <tr <?php if ($i == 0){ echo 'style=background-color:#f2dede;font-weight:bold'; } ?>> <td <?php if ($i == 0){ echo 'style=font-weight:bold'; } ?>><?php echo $groupePassager->NOM; ?></td> <td><?php echo $groupePassager->PRENOM; ?></td> <td><?php echo $groupePassager->COMPTEUR; ?></td> <td><?php echo $groupePassager->KMS; ?></td> <td><?php echo $groupePassager->ECONOMIE; ?></td> <td> <?php if ($i == 0){ echo '<span class="glyphicon glyphicon-star-empty">'; } ?></td> </tr> <?php $i = $i + 1;} ?> </table> </div> </div> <?php if (!$isConsultation){ ?> <div class="form-group"> <div class="col-sm-offset-5"> <input type="submit" class="btn btn btn-success" value="Enregistrer"/> </div> </div> <?php } ?> </form> </div> </div><file_sep>/ecoleg/modele/m_covoiturage.php <?php class m_covoiturage{ private $base_de_donnee; public function __construct($base_de_donnee){ $this->base_de_donnee = $base_de_donnee; } public function getCovoiturageByGroupe($idGroupe){ $connexion = $this->base_de_donnee->prepare('SELECT ID, ADRESSE FROM covoiturage where ID_GROUPE = ?' ); $connexion->bindValue(1, $idGroupe, PDO::PARAM_INT); $connexion->execute(); $retour = $connexion->fetchAll(PDO::FETCH_OBJ); $connexion->closeCursor(); return $retour; } /* PERMET D'AJOUTER UN POINT DE COVOITURAGE */ public function ajouterCovoiturage($idGroupe, $adresse){ $ajouterCovoiturage = $this->base_de_donnee->prepare('INSERT covoiturage SET ID_GROUPE = ?, ADRESSE = ?'); $ajouterCovoiturage->bindValue(1, $idGroupe, PDO::PARAM_INT); $ajouterCovoiturage->bindValue(2, $adresse, PDO::PARAM_STR); $ajouterCovoiturage->execute(); $lastId = $this->base_de_donnee->lastInsertId(); return $lastId; } /* PERMET DE SUPPRESSION D'UN POINT DE COVOITURAGE */ public function deleteCovoiturage($id){ $deleteCovoiturage = $this->base_de_donnee->prepare('DELETE FROM covoiturage where ID = ?'); $deleteCovoiturage->bindValue(1, $id, PDO::PARAM_INT); $deleteCovoiturage->execute(); } } ?><file_sep>/ecoleg/config/upload_file_config.php <?php /* PARAMETRES FICHIER UPLOADS */ define('UPLOAD_MAX_SIZE', 100000); // Taille max en octets du fichier define('ACCUEIL_SLIDER_DIR', ADRESSE_ABSOLUE_URL . 'uploads/accueil/slider/'); // Repertoire cible slider define('ACCUEIL_PHOTO_PROFIL_DIR', ADRESSE_ABSOLUE_URL . 'uploads/accueil/photo_profil/'); // Repertoire cible photo profil define('ARTICLES_VIGNETTE_DIR', ADRESSE_ABSOLUE_URL . 'uploads/articles/vignette/'); // Repertoire cible vignette define('BIOGRAPHIE_PHOTO_PROFIL_DIR', ADRESSE_ABSOLUE_URL . 'uploads/biographie/photo_profil/'); // Repertoire cible photo profil define('TRAINING_VIGNETTE_DIR', ADRESSE_ABSOLUE_URL . 'uploads/training/vignette/'); // Repertoire cible vignette $extensions_valides = array('jpg','gif','png','jpeg'); // Extensions autorisees ?><file_sep>/ecoleg/js/check_form.js function sure(){ return confirm("T'es sur ??"); } <file_sep>/ecoleg/vue/passagers.php <div class="jumbotron"> <h1>Liste des passagers</h1> <p class="lead"></p> </div> <div class="col-md-12"> <table class="table table-striped custab"> <thead> <a href="<?php echo ADRESSE_ABSOLUE_URL . 'passager'; ?>" class="btn btn-primary btn-xs pull-right"><b>+</b> Nouveau passager</a> <tr> <th>ID</th> <th>Nom</th> <th>Prenom</th> <th class="text-center">Action</th> </tr> </thead> <?php foreach($liste_passager as $passager){ ?> <tr> <td><?php echo $passager->ID; ?></td> <td><?php echo $passager->NOM; ?></td> <td><?php echo $passager->PRENOM; ?></td> <td class="text-center"> <a class='btn btn-info btn-xs' href="<?php echo ADRESSE_ABSOLUE_URL . 'passager/' . $passager->ID; ?>"><span class="glyphicon glyphicon-edit"></span></a> <a href="<?php echo ADRESSE_ABSOLUE_URL . 'passagers/' . $passager->ID; ?>" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span></a></td> </tr> <?php } ?> </table> </div> <file_sep>/ecoleg/controleur/covoiturage.php <?php /**** SESSION ****/ session_start(); /**** CLASS CONTROLEUR ****/ require_once('class/c_session.php'); require_once('class/t_texte.php'); /**** MODELE ****/ require_once('modele/m_session.php'); require_once('modele/m_groupe.php'); require_once('modele/m_groupePassager.php'); require_once('modele/m_covoiturage.php'); /**** OBJETS ****/ $t_texte = new t_texte(); $m_session = new m_session($base_de_donnee); $m_groupePassager = new m_groupePassager($base_de_donnee); $m_groupe = new m_groupe($base_de_donnee); $m_covoiturage = new m_covoiturage($base_de_donnee); $c_session = new c_session($m_session, $t_texte); /**** VERIF SESSION ****/ $c_session->session(); $idGroupe = null; $isConsultation = false; //RECHERCHE les passagers du groupe if(!empty($url_param[0])) { if(preg_match('#^[0-9]{1,}$#', $url_param[0])) { $idGroupe = $url_param[0]; $groupe = $m_groupe->getGroupe($idGroupe); $liste_groupePassager = $m_groupePassager->getPassagerByGroupe($idGroupe); $liste_covoiturage = $m_covoiturage->getCovoiturageByGroupe($idGroupe); $derniereDateCovoiturage = $m_groupe->getDerniereDateCovoiturage($idGroupe); $rest = substr($derniereDateCovoiturage->MAX, 0, 10); $date = date("Y-m-d"); if ($rest == $date){ $isConsultation = true; } } } if(isset($_POST['adresseCovoiturage']) && isset($_POST['idGroupePassager'])){ $idGroupePassager = $_POST['idGroupePassager']; $libelleErreur = ""; if ($_POST['adresseCovoiturage'] == ''){ $libelleErreur = "L'adresse de covoiturage est obligatoire"; } if ($_POST['idGroupePassager'] == ''){ $libelleErreur = $libelleErreur .'<br>Le conducteur est obligatoire'; } if ($libelleErreur == ''){ foreach($liste_groupePassager as $groupePassager){ if ($groupePassager->ID == $idGroupePassager){ $distance1=getDistance($groupePassager->ADRESSE, $_POST['adresseCovoiturage']); $distance2=getDistance($_POST['adresseCovoiturage'], $groupe->DESTINATION); $m_groupePassager->ajouterKmsConducteur($groupePassager->ID, $distance1+$distance2, 0); }else{ $distanceNormale=getDistance($groupePassager->ADRESSE, $groupe->DESTINATION); $distance=getDistance($groupePassager->ADRESSE, $_POST['adresseCovoiturage']); $economie=$distanceNormale-$distance; $m_groupePassager->ajouterKmsPassager($groupePassager->ID, $distance, $economie); } } $liste_groupePassager = $m_groupePassager->getPassagerByGroupe($idGroupe); $isConsultation = true; //header('Location: '.ADRESSE_ABSOLUE_URL.'accueil'); } } function getDistance2($adresse1,$adresse2) { $adresse1 = str_replace(" ", "+", $adresse1); $adresse2 = str_replace(" ", "+", $adresse2); $adresse1 = urlencode($adresse1); $adresse2 = urlencode($adresse2); $proxy = 'ptx.proxy.<EMAIL>'; $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$adresse1."&destinations=".$adresse2."&mode=driving&key=<KEY>"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXYPORT, 80); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); $response = curl_exec($ch); curl_close($ch); $response_a = json_decode($response, true); $distance = $response_a['rows'][0]['elements'][0]['distance']['text']; $distance=str_replace(" km", "", $distance); if ($distance) { return $distance*2; } else { return "0"; } } function getDistance1($adresse1,$adresse2){ $adresse1 = str_replace(" ", "+", $adresse1); $adresse2 = str_replace(" ", "+", $adresse2); $adresse1 = urlencode($adresse1); $adresse2 = urlencode($adresse2); //$data = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/xml?origins='.$adresse1.'&destinations='.$adresse2.'&key=<KEY>'); $data = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/xml?origins=castres&destinations=albi&key=<KEY>"); $data = json_decode($data); $distance = 0; foreach($data->rows[0]->elements as $road) { $distance += $road->distance->value; } $distance=str_replace(" km", "", $distance); if ($data->status == "OK") { return $distance*2; } else { return "0"; } } function getDistance($adresse1,$adresse2){ $adresse1 = str_replace(" ", "+", $adresse1); $adresse2 = str_replace(" ", "+", $adresse2); $adresse1 = urlencode($adresse1); $adresse2 = urlencode($adresse2); $context = stream_context_create([ 'http' => [ 'proxy' => 'ptx.proxy.corp.sopra:8080', 'request_fulluri' => true ], 'ssl' => [ 'verify_peer'=> false, 'verify_peer_name'=> false ] ]); $data = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/xml?origins='.$adresse1.'&destinations='.$adresse2.'&key=<KEY>', true, $context); $root = simplexml_load_string($data); $distance=$root->row->element->distance->text; $distance=str_replace(" km", "", $distance); if ($root->status == "OK") { return $distance*2; } return 0; } ?> <file_sep>/ecoleg/controleur/erreur.php <?php /**** SESSION ****/ session_start(); /**** CLASS CONTROLEUR ****/ require_once('class/c_session.php'); require_once('class/t_texte.php'); /**** MODELE ****/ require_once('modele/m_session.php'); /**** OBJETS ****/ $t_texte = new t_texte(); $m_session = new m_session($base_de_donnee); $c_session = new c_session($m_session, $t_texte); /**** VERIF SESSION ****/ $c_session->session(); ?> <file_sep>/ecoleg/js/bbcode.js function gras(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[b][/b]'); } function italic(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[i][/i]'); } function souligne(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[u][/u]'); } function gauche(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[left][/left]'); } function centré(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[center][/center]'); } function droite(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[right][/right]'); } function justifie(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[justify][/justify]'); } function listePuces(areaAModifier){ var text = "\n[liste]\n"; text = text + "[puce]1[/puce] \n"; text = text + "[puce]2[/puce] \n"; text = text + "[puce]3[/puce] \n"; text = text + '[/liste]'; $(areaAModifier).val($(areaAModifier).val()+ text); } function image(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[img][/img]'); } function lien(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[url][/url]'); } function titre1(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[t1][/t1]'); } function titre2(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[t2][/t2]'); } function titre3(areaAModifier){ $(areaAModifier).val($(areaAModifier).val()+'[t3][/t3]'); } <file_sep>/ecoleg/config/code_retour.php <?php $code_retour[0] = 'OK'; $code_retour[1] = 'Nom de compte ou mot de passe absent'; $code_retour[2] = 'Identifiants incorrectes'; $code_retour[3] = 'Ce compte nécessite d\'être activé'; $code_retour[4] = 'Champ absent'; $code_retour[5] = 'Champ(s) vide(s)'; $code_retour[6] = 'Taille maximum dépassé pour un champ'; $code_retour[7] = 'Valeur du champ incorrecte'; $code_retour[8] = 'Seulement les lettres et espaces sont autorisés'; $code_retour[9] = 'Veuillez saisir une adresse email valide'; $code_retour[10] = 'Mauvais format de l\'url'; $code_retour[11] = 'L\'ajout s\'est bien déroulé !'; $code_retour[12] = 'Problème lors de l\'ajout !'; $code_retour[13] = 'Modification effectuée !'; $code_retour[14] = 'Erreur survenue lors de la modification !'; $code_retour[15] = 'Erreur ! Les mots de passes doivent être identiques !'; /* ### CODE RETOUR FICHIER ### */ $code_retour[16] = 'Erreur : le répertoire cible ne peut-être trouvé !'; $code_retour[17] = 'Transfert réussi'; $code_retour[18] = 'Une erreur interne a empêché l\'uplaod de l\'image'; $code_retour[19] = 'Taille du fichier trop importante !'; $code_retour[20] = 'Extension non valide !'; $code_retour[21] = 'Fichier non émis !'; $code_retour[22] = 'Veuillez attendre 5 min avant de vous reconnecter !'; $code_retour[23] = 'Le mot de passe doit avoir une longueur minimal de 12 caractères !!!'; ?><file_sep>/ecoleg/config/const.php <?php /* CHEMINS */ define('DS', '/'); //DIRECTORY_SEPARATOR define('ROOT', dirname(dirname(__FILE__))); /* BASE DE DONNEE */ define('CONST_DB_HOST', "localhost"); define('CONST_DB_NAME', "covoiturage"); define('CONST_DB_USER', "root"); define('CONST_DB_PASS', ""); /* PARAMETRES */ define('AFFICHER_ERREURS', true); define('PAGE_DEFAUT', 'login'); define('TIMEOUT_CONNEXION', 2592000); define('TIMEOUT_MOBILE_SESSION', 3600); define('NB_ELEMENT_PAGE', 5); define('NB_ELEMENT_PAGE_LISTE_STATISTIQUES', 15); define('NB_TENTATIVE_SOUMISSION', 5); define('TEMPS_AVANT_NOUVELLE_TENTATIVE_SOUMISSION', 5); define('TAILLE_MINIMAL_PASSWORD', 10); /* CHAINES */ define('NOM_PAGE_DEFAUT', ''); define('DESCRIPTION_DEFAUT', ''); define('KEYWORDS_DEFAUTS', ''); /* PATH */ define('BOOTSRAP_CSS', './css/bootstrap.css'); define('STYLE_CSS', './vue/css/style.css'); define('IMAGES_STYLE', './vue/images/'); //define('ADRESSE_ABSOLUE_URL', 'http://192.168.0.100/ecoleg/'); //define('ADRESSE_ABSOLUE_URL', 'http://172.30.252.30/ecoleg/'); define('ADRESSE_ABSOLUE_URL', 'http://172.30.250.28/ecoleg/'); /* INCLUSION DE FICHIERS CONF */ require_once('pages_existantes.php'); require_once('upload_file_config.php'); require_once('code_retour.php'); ?><file_sep>/ecoleg/controleur/class/c_session.php <?php class c_session{ private $modele; private $texte; public function __construct($p_modele, $ptexte){ $this->modele = $p_modele; $this->texte = $ptexte; } /* Vérifie la variable de session id */ public function session(){ if(!isset($_SESSION['id'])){ $_SESSION['id'] = 0; $id = 0; } else { $id = $_SESSION['id']; } } /* Prend en paramètre l'id de session mobile (ou 0) et renvoie l'id après vérification */ public function session_mobile($id){ $ip = $_SERVER['REMOTE_ADDR']; $this->modele->timeout_mobile(); if($id != 0) { $id_verif = $this->modele->verifie_session_mobile($id, $ip); if(empty($id_verif)) { $id = $this->texte->random_generateur(32); $this->modele->nouvelle_session_mobile($id, $ip); } else { $this->modele->update_session_mobile($id, $ip); } } else { $id = $this->texte->random_generateur(32); $this->modele->nouvelle_session_mobile($id, $ip); } return $id; } /* SESSION TIME OUT */ public function sesion_timeout(){ $tempsActuel = time(); if($tempsActuel - $_SESSION['time'] >= 600){ header('Location: deconnexion'); } } /* Compteur d'utilisateurs connectés sur le site */ public function calcul_nb_utilisateurs_connectes($ip){ $isUserExiste = $this->modele->is_utilisateurs_connectes_existe($ip); if($isUserExiste['nb'] > 0){ // Il existe $this->modele->update_nombre_utilisateurs_connectes($ip); }else { // n'existe pas -> on l'ajoute $this->modele->add_utilisateur_connecte($ip); } /* À chaque fois que le visiteur va ouvrir une page, nous allons changer le timestamp de sa dernière activité au timestamp actuel. Nous allons aussi supprimer toutes les entrées qui datent de plus de 5 minutes. */ $times_m_5mins = (time()-(60*5)); $this->modele->delete_utilisateur_connecte($times_m_5mins); $nbUserConnecte = $this->modele->get_nombre_utilisateurs_connectes(); // retourne un objet ['nb'] return $nbUserConnecte; } /* Verification du token */ public function verification_token($p_SESSION, $p_POST){ //Si le jeton est présent dans la session et dans le formulaire if(isset($p_SESSION['token']) && isset($p_SESSION['token_time']) && isset($p_POST['token'])){ //Si le jeton de la session correspond à celui du formulaire if($p_SESSION['token'] == $p_POST['token']){ //On stocke le timestamp qu'il était il y a 15 minutes $timestamp_ancien = time() - (15*60); //Si le jeton n'est pas expiré if($p_SESSION['token_time'] >= $timestamp_ancien){ //Ok return 1; }else{ return -1; } }else{ return -1; } }else{ return -1; } } } ?><file_sep>/ecoleg/vue/login.php <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?php echo $nom_page;?></title> <!-- Bootstrap --> <link href="<?php echo ADRESSE_ABSOLUE_URL . BOOTSRAP_CSS; ?>" rel="stylesheet"> <link href="<?php echo ADRESSE_ABSOLUE_URL . STYLE_CSS; ?>" rel="stylesheet"> </head> <body> <div class="container login"> <form class="form-signin" action="" method="post"> <h2 class="form-signin-heading" style="padding-left:125px"> <img src="<?php echo ADRESSE_ABSOLUE_URL . IMAGES_STYLE; ?>logo.png" alt="" width="200px"/> </h2> <label for="inputEmail" class="sr-only">Adresse email</label> <input type="email" id="inputEmail" name="inputEmail" class="form-control" placeholder="Adresse email" required autofocus> <br> <label for="inputPassword" class="sr-only">Mot de passe</label> <input type="password" id="inputPassword" name="inputPassword" class="form-control" placeholder="Mot de passe" required> <br> <button class="btn btn-lg btn-success btn-block" type="submit">Se connecter</button> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="<?php echo ADRESSE_ABSOLUE_URL . 'js/bootstrap.min.js'; ?>"></script> </body> </html> <file_sep>/ecoleg/controleur/class/t_texte.php <?php class t_texte{ /* Prend en paramètre un timestamp et retourne une date relative */ public function quand($timestamp){ date_default_timezone_set('Europe/Paris'); $superdate = date('d F Y', $timestamp); $superdate = str_replace('January', 'janvier', $superdate); $superdate = str_replace('February', 'février', $superdate); $superdate = str_replace('March', 'mars', $superdate); $superdate = str_replace('April', 'avril', $superdate); $superdate = str_replace('May', 'mai', $superdate); $superdate = str_replace('June', 'juin', $superdate); $superdate = str_replace('July', 'juillet', $superdate); $superdate = str_replace('August', 'aout', $superdate); $superdate = str_replace('September', 'septembre', $superdate); $superdate = str_replace('October', 'octobre', $superdate); $superdate = str_replace('November', 'novembre', $superdate); $superdate = str_replace('December', 'décembre', $superdate); return $superdate; } public function random_generateur($nb_car){ $caractères = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); $generation = ''; for($i = 0; $i < $nb_car; $i++){ $generation .= $caractères[rand(0, count($caractères)-1)]; } return $generation; } /* Permet de parser du code BBCode et le convertir en HTML */ public function convertBBcodeToHtml($texte){ $tmp = stripslashes($texte); // on supprimer les antislash de la chaine $texte = nl2br(htmlentities($tmp)); // rajoute <br /> après chaque retour à la ligne $entree = array( '#\[b\](.*)\[/b\]#Usi', '#\[i\](.*)\[/i\]#Usi', '#\[u\](.*)\[/u\]#Usi', '#\[img\](.*)\[/img\]#Usi', '#\[url\](.*)\[/url\]#Usi', '#\[left\](.*)\[/left\]#Usi', '#\[center\](.*)\[/center\]#Usi', '#\[right\](.*)\[/right\]#Usi', '#\[justify\](.*)\[/justify\]#Usi', '#\[t1\](.*)\[/t1\]#Usi', '#\[t2\](.*)\[/t2\]#Usi', '#\[t3\](.*)\[/t3\]#Usi', '#\[liste\][puce](.*)\[/puce\]\[/liste\]#Usi' ); $sortie = array( '<b class="bbcode-p">$1</b>', '<i class="bbcode-p">$1</i>', '<u class="bbcode-p">$1</u>', '<img src="$1" alt="Image" class="img-responsive" style="margin:auto;" height="500" width="500"/>', '<a class="bbcode-p" href="$1">$1</a>', '<p class="bbcode-p" style="text-align:left;">$1</p>', '<p class="bbcode-p" style="text-align:center;">$1</p>', '<p class="bbcode-p" style="text-align:right;">$1</p>', '<p class="bbcode-p" style="text-align:justify;">$1</p>', '<h1 class="bbcode-h1">$1</h1>', '<h2 class="bbcode-h2">$1</h2>', '<h3 class="bbcode-h3">$1</h3>', '<ul><li>$1</li></ul>' ); $count = count($entree)-1; // On calcule la taille for($i=0;$i<=$count;$i++){ $texte = preg_replace($entree[$i],$sortie[$i],$texte); } return $texte; }// fin de la fonction /* Permet de parser du code BBCode et le convertir en HTML */ public function convertHtmlToBBcode($texte){ $tmp = stripslashes($texte); // on supprimer les antislash de la chaine $texte = str_replace('<br />','',$tmp); // on supprime <br /> et rajoute ' ' $entree = array( '#<b class="bbcode-p">(.*)</b>#Usi', '#<i class="bbcode-p">(.*)</i>#Usi', '#<u class="bbcode-p">(.*)</u>#Usi', '#<img src="(.*)" alt="Image" class="img-responsive" style="margin:auto;" height="500" width="500"/>#Usi', '#<a class="bbcode-p" href="(.*)">(.*)</a>#Usi', '#<p class="bbcode-p" style="text-align:left;">(.*)</p>#Usi', '#<p class="bbcode-p" style="text-align:center;">(.*)</p>#Usi', '#<p class="bbcode-p" style="text-align:right;">(.*)</p>#Usi', '#<p class="bbcode-p" style="text-align:justify;">(.*)</p>#Usi', '#<h1 class="bbcode-h1">(.*)</h1>#Usi', '#<h2 class="bbcode-h2">(.*)</h2>#Usi', '#<h3 class="bbcode-h3">(.*)</h3>#Usi', '#<ul><li>(.*)</li></ul>#Usi' ); $sortie = array( '[b]$1[/b]', '[i]$1[/i]', '[u]$1[/u]', '[img]$1[/img]', '[url]$1[/url]', '[left]$1[/left]', '[center]$1[/center]', '[right]$1[/right]', '[justify]$1[/justify]', '[t1]$1[/t1]', '[t2]$1[/t2]', '[t3]$1[/t3]', '[liste][puce]$1[/puce][/liste]' ); $count = count($entree)-1; // on calcule la taille for($i=0;$i<=$count;$i++){ $texte = preg_replace($entree[$i],$sortie[$i],$texte); } return $texte; }// fin de la fonction } ?><file_sep>/ecoleg/config/pages_existantes.php <?php $pages_existantes = array( 'erreur', 'accueil', 'passagers', 'passager', 'groupes', 'groupe', 'covoiturages', 'covoiturage', 'popupErreur', 'itineraire', 'login' ); ?><file_sep>/ecoleg/controleur/passagers.php <?php /**** SESSION ****/ session_start(); /**** CLASS CONTROLEUR ****/ require_once('class/c_session.php'); require_once('class/t_texte.php'); /**** MODELE ****/ require_once('modele/m_session.php'); require_once('modele/m_passager.php'); /**** OBJETS ****/ $t_texte = new t_texte(); $m_session = new m_session($base_de_donnee); $m_passager = new m_passager($base_de_donnee); $c_session = new c_session($m_session, $t_texte); /**** VERIF SESSION ****/ $c_session->session(); $liste_passager = $m_passager->getAllPassager(); $idPassager = null; if(!empty($url_param[0])) { if(preg_match('#^[0-9]{1,}$#', $url_param[0])) { $idPassager = $url_param[0]; if($idPassager != null){ $m_passager->deletePassager($idPassager); $liste_passager = $m_passager->getAllPassager(); } } } ?> <file_sep>/ecoleg/modele/m_passager.php <?php class m_passager{ private $base_de_donnee; public function __construct($base_de_donnee){ $this->base_de_donnee = $base_de_donnee; } public function getAllPassager(){ $connexion = $this->base_de_donnee->prepare('SELECT * FROM passager'); $connexion->execute(); $retour = $connexion->fetchAll(PDO::FETCH_OBJ); $connexion->closeCursor(); return $retour; } public function getPassager($id){ $requete = $this->base_de_donnee->prepare('SELECT * FROM passager where ID = ?'); $requete->bindValue(1, $id, PDO::PARAM_INT); $requete->execute(); $retour = $requete->fetch(PDO::FETCH_OBJ); $requete->closeCursor(); return $retour; } public function getPassagerByEmail($email){ $requete = $this->base_de_donnee->prepare('SELECT * FROM passager where EMAIL = ?'); $requete->bindValue(1, $email, PDO::PARAM_STR); $requete->execute(); $retour = $requete->fetch(PDO::FETCH_OBJ); $requete->closeCursor(); return $retour; } /* PERMET D'AJOUTER UN PASSAGER */ public function modifierPassager($nom, $prenom, $adresse, $telephone, $email, $id){ $modifierPassager = $this->base_de_donnee->prepare('UPDATE passager SET NOM = ?, PRENOM = ?, ADRESSE = ?, TELEPHONE = ?, EMAIL = ? where ID = ?'); $modifierPassager->bindValue(1, $nom, PDO::PARAM_STR); $modifierPassager->bindValue(2, $prenom, PDO::PARAM_STR); $modifierPassager->bindValue(3, $adresse, PDO::PARAM_STR); $modifierPassager->bindValue(4, $telephone, PDO::PARAM_STR); $modifierPassager->bindValue(5, $email, PDO::PARAM_STR); $modifierPassager->bindValue(6, $id, PDO::PARAM_INT); $modifierPassager->execute(); } /* PERMET DE CREER UN PASSAGER */ public function creerPassager($nom, $prenom, $adresse, $telephone, $email){ $creerPassager = $this->base_de_donnee->prepare('INSERT INTO passager (NOM, PRENOM, ADRESSE, TELEPHONE, EMAIL) values (?, ?, ?, ?, ?) '); $creerPassager->bindValue(1, $nom, PDO::PARAM_STR); $creerPassager->bindValue(2, $prenom, PDO::PARAM_STR); $creerPassager->bindValue(3, $adresse, PDO::PARAM_STR); $creerPassager->bindValue(4, $telephone, PDO::PARAM_STR); $creerPassager->bindValue(5, $email, PDO::PARAM_STR); $creerPassager->execute(); $lastId = $this->base_de_donnee->lastInsertId(); return $lastId; } /* PERMET DE SUPPRESSION D'UN PASSAGER */ public function deletePassager($id){ $deletePassager = $this->base_de_donnee->prepare('DELETE FROM passager where ID = ?'); $deletePassager->bindValue(1, $id, PDO::PARAM_INT); $deletePassager->execute(); } } ?><file_sep>/ecoleg/modele/m_articles.php <?php class m_articles{ private $base_de_donnee; public function __construct($base_de_donnee){ $this->base_de_donnee = $base_de_donnee; } /* PERMET DE LISTE L'ENSEMBLE DES ARTICLEs */ public function liste_articles($numPage) { // Calcul num page - 1 * nbr element par page $calcul = ($numPage - 1) * NB_ELEMENT_PAGE; $liste_articles = $this->base_de_donnee->prepare('SELECT * FROM articles LIMIT ?, '.NB_ELEMENT_PAGE); $liste_articles->bindValue(1, $calcul, PDO::PARAM_INT); $liste_articles->execute(); $retour = $liste_articles->fetchAll(PDO::FETCH_OBJ); $liste_articles->closeCursor(); return $retour; } /* PERMET DE RECHERCHER DES ARTICLEs */ public function rechercher_articles($recherche){ //permet de stocker le résultat dans un tableau, on supprime les espaces $s = explode(" ", $recherche); // On stocke notre requête dans une variable qu'on pourra modifier en fonction des résultats $sqlAND = "SELECT * FROM articles"; $sqlOR = "SELECT * FROM articles"; $i=0; // indice // On va parcourir le tableau $s foreach($s as $mots){ // pour éviter injection sql $mots = addslashes($mots); if(strlen($mots)>3){ // pour éviter les petits mots comme le de etc... if($i==0){ $sqlAND.= " WHERE "; $sqlOR.= " WHERE "; } else{ $sqlAND.= " AND "; $sqlOR.= " OR "; } // On met en place enfin la requête sql $sqlAND.="detailBien like '%$mots%'"; $sqlOR.="detailBien like '%$mots%'"; // On incrémente l'indice $i++; } // UNION des 2 requêtes AND et OR $sql = $sqlAND ." UNION ".$sqlOR; // Traitement requête $rechercher_articles = $bdd->prepare($sql); $rechercher_articles->execute(); $retour = $rechercher_articles->fetch(PDO::FETCH_OBJ); return $retour; } } /* PERMET D'OBTENIR UN ARTICLE */ public function get_articles($id){ $afficher_articles = $this->base_de_donnee->prepare('SELECT * FROM articles WHERE id=?'); $afficher_articles->bindValue(1, $id, PDO::PARAM_INT); $afficher_articles->execute(); $retour = $afficher_articles->fetch(PDO::FETCH_OBJ); $afficher_articles->closeCursor(); return $retour; } /* PERMET D'AJOUTER UN ARTICLE */ public function add_articles($titre, $texte, $description, $url, $date, $auteur){ $ajouter_articles = $this->base_de_donnee->prepare('INSERT INTO articles (titre, texte, description, url, datePublication, auteur) values (?, ?, ?, ?, ?, ?) '); $ajouter_articles->bindValue(1, $titre, PDO::PARAM_STR); $ajouter_articles->bindValue(2, $texte, PDO::PARAM_STR); $ajouter_articles->bindValue(3, $description, PDO::PARAM_STR); $ajouter_articles->bindValue(4, $url, PDO::PARAM_STR); $ajouter_articles->bindValue(5, $date, PDO::PARAM_INT); $ajouter_articles->bindValue(6, $auteur, PDO::PARAM_STR); $ajouter_articles->execute(); } /* PERMET D'AJOUTER UN ARTICLE */ public function update_articles($id, $titre, $texte, $description, $url, $date, $auteur){ $update_articles = $this->base_de_donnee->prepare('UPDATE articles SET titre = ?, texte = ?, description = ?, url = ? , datePublication = ? , auteur = ? WHERE id = ?'); $update_articles->bindValue(1, $titre, PDO::PARAM_STR); $update_articles->bindValue(2, $texte, PDO::PARAM_STR); $update_articles->bindValue(3, $description, PDO::PARAM_STR); $update_articles->bindValue(4, $url, PDO::PARAM_STR); $update_articles->bindValue(5, $date, PDO::PARAM_INT); $update_articles->bindValue(6, $auteur, PDO::PARAM_STR); $update_articles->bindValue(7, $id, PDO::PARAM_STR); $update_articles->execute(); } /* PERMET DE SUPPRIMER UN ARTICLE */ public function delete_articles($id){ $delete_articles = $this->base_de_donnee->prepare('DELETE FROM articles WHERE id = ?'); $delete_articles->bindValue(1, $id, PDO::PARAM_INT); $delete_articles->execute(); } } ?><file_sep>/ecoleg/controleur/login.php <?php /**** SESSION ****/ session_start(); /**** CLASS CONTROLEUR ****/ require_once('class/c_session.php'); require_once('class/t_texte.php'); /**** MODELE ****/ require_once('modele/m_session.php'); require_once('modele/m_passager.php'); /**** OBJETS ****/ $t_texte = new t_texte(); $m_session = new m_session($base_de_donnee); $c_session = new c_session($m_session, $t_texte); $m_passager = new m_passager($base_de_donnee); /**** VERIF SESSION ****/ $c_session->session(); if(isset($_POST['inputEmail']) && isset($_POST['inputPassword'])){ if ($_POST['inputEmail'] == ''){ $libelleErreur = 'Le login est obligatoire.'; } if ($_POST['inputPassword'] == ''){ $libelleErreur = 'Le mot de passe est obligatoire.'; } $passager = $m_passager->getPassagerByEmail($_POST['inputEmail']); if ($passager == null || $passager->ID == null){ $libelleErreur = 'Utilisateur introuvable !!'; }else{ $_SESSION['user'] = $passager; header('Location: '.ADRESSE_ABSOLUE_URL.'accueil'); } } ?> <file_sep>/ecoleg/vue/groupe.php <?php if($idGroupe != null){ ?> <!-- modification un groupe --> <div class="jumbotron"> <h1>Modification du groupe</h1> <p class="lead"><i>Un groupe de covoiturage est defini par une destination, une liste de 'point de covoiturage' et une liste de conducteur</i></p> </div> <div class="container"> <form class="form-horizontal" method="post" action=""> <div class="col-md-12"> <div class="form-group"> <span style="clear:both"></span> <p> Libellé : <input type="text" class="form-control" id="libelle" name="libelle" value="<?php echo $groupe->LIBELLE; ?>" placeholder="Libellé" required> </p> <p> <span clas="form-control"> Destination : </span> </p> <p> <input type="text" id="destination" name="destination" value="<?php echo $groupe->DESTINATION; ?>" class="form-control form-control-inline" onfocus="javascript:$('#myModal').modal('show');" readonly /> </p> </div> <div class="form-group"> <div class="col-sm-offset-6"> <input type="submit" class="btn btn btn-success" value="Enregistrer"/> </div> </div> </div> </form> </div> <div class="container"> <div class="row col-md-12"> <div class="panel panel-default"> <div class="panel-heading"><b>Liste des points de covoiturage</b></div> <div class="panel-body"> <table class="table table-striped custab"> <thead> <tr> <th>ADRESSE</th> <th class="text-center">Action</th> </tr> </thead> <?php foreach($liste_covoiturage as $covoiturage){ ?> <tr> <td><?php echo $covoiturage->ADRESSE; ?></td> <td class="text-center"> <a href="<?php echo ADRESSE_ABSOLUE_URL . 'groupe/' . $groupe->ID . '/deleteCovoiturage/' . $covoiturage->ID; ?>" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span></a></td> </tr> <?php } ?> </table> <form class="form-horizontal" method="post" action=""> <p> Adresse : <input type="text" id="adresseCovoiturage" name="adresseCovoiturage" class="form-control form-control-inline" onfocus="javascript:$('#myModalCovoiturage').modal('show');" placeholder="Recherchez votre point de covoiturage" readonly /> </p> <input type="submit" class="btn btn btn-success" value="+"/> </form> </div> </div> </div> </div> <div class="container"> <div class="row col-md-12"> <div class="panel panel-default"> <div class="panel-heading"><b>Liste des passagers</b></div> <div class="panel-body"> <table class="table table-striped custab"> <thead> <tr> <th>NOM</th> <th>PRENOM</th> <th class="text-center">Action</th> </tr> </thead> <?php foreach($liste_groupePassager as $groupePassager){ ?> <tr> <td><?php echo $groupePassager->NOM; ?></td> <td><?php echo $groupePassager->PRENOM; ?></td> <td class="text-center"> <a href="<?php echo ADRESSE_ABSOLUE_URL . 'groupe/' . $groupe->ID . '/deletePassager/' . $groupePassager->ID; ?>" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span></a></td> </tr> <?php } ?> </table> <form class="form-horizontal" method="post" action=""> <select id="idPassagerAjouter" name="idPassagerAjouter"> <option value="" selected="selected"></option> <?php foreach($liste_passager as $passager){ ?> <option value="<?php echo $passager->ID; ?>"><?php echo $passager->NOM . ' ' . $passager->PRENOM; ?></option> <?php } ?> </select> <input type="submit" class="btn btn btn-success" value="+"/> </form> </div> </div> </div> </div> <?php }else{ ?> <!-- creation un groupe --> <div class="jumbotron"> <h1>Création du groupe</h1> <p class="lead"><i>Un groupe de covoiturage est defini par une liste de 'point de covoiturage' et une liste de conducteur</i></p> </div> <div class="container margin-auto"> <form class="form-horizontal" method="post" action=""> <div class="row col-md-12"> <div class="form-group"> <span style="clear:both"></span> <p> Libellé : <input type="text" class="form-control" id="libelle" name="libelle" placeholder="libelle" required> </p> <p> <span clas="form-control"> Destination : </span> </p> <p> <input type="text" id="destination" name="destination" class="form-control form-control-inline" onfocus="javascript:$('#myModal').modal('show');" readonly /> </p> </div> <div class="form-group"> <div class="col-sm-offset-6"> <input type="submit" class="btn btn btn-success" value="Enregistrer"/> </div> </div> </div> </form> </div> <?php } ?> <!-- Modal destination --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title" id="myModalLabel">Rechercher votre destination</h4> </div> <div class="modal-body"> <input type="text" id="adresseRecherchee" placeholder="Recherchez votre destination" class="form-control form-control-inline"/> <a href="#" onclick="showLocation('adresseRecherchee', 'destination');javascript:$('#myModal').modal('hide');"><span class="glyphicon glyphicon-map-marker form-control-inline"></a> </div> </div> </div> </div> <!-- Modal point de covoiturage --> <div class="modal fade" id="myModalCovoiturage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title" id="myModalLabel">Rechercher votre point de covoiturage</h4> </div> <div class="modal-body"> <input type="text" id="rechercheCovoiturage" placeholder="Recherchez votre point de covoiturage" class="form-control form-control-inline"/> <a href="#" onclick="showLocation('rechercheCovoiturage', 'adresseCovoiturage');javascript:$('#myModalCovoiturage').modal('hide');"><span class="glyphicon glyphicon-map-marker form-control-inline"></a> </div> </div> </div> </div><file_sep>/ecoleg/controleur/passager.php <?php /**** SESSION ****/ session_start(); /**** CLASS CONTROLEUR ****/ require_once('class/c_session.php'); require_once('class/t_texte.php'); require_once('class/f_formulaire.php'); //require('phpmailer/class.phpmailer.php'); require('phpmailer/PHPMailerAutoload.php'); /**** MODELE ****/ require_once('modele/m_session.php'); require_once('modele/m_passager.php'); /**** OBJETS ****/ $t_texte = new t_texte(); $f_formulaire = new f_formulaire(); $m_session = new m_session($base_de_donnee); $m_passager = new m_passager($base_de_donnee); $c_session = new c_session($m_session, $t_texte); /**** VERIF SESSION ****/ $c_session->session(); $idPassager = null; if(!empty($url_param[0])) { if(preg_match('#^[0-9]{1,}$#', $url_param[0])) { $idPassager = $url_param[0]; $passager = $m_passager->getPassager($idPassager); } } //redirection -> Accueil /* if($idPassager == null){ header('Location: '.ADRESSE_ABSOLUE_URL.'accueil'); exit; }*/ //ENREGISTRER le passager if(isset($_POST['nom']) && isset($_POST['prenom']) && isset($_POST['adresse'])){ if ($_POST['nom'] == ''){ $libelleErreur = 'Le nom est obligatoire.'; } if ($_POST['prenom'] == ''){ $libelleErreur = 'Le prénom est obligatoire.'; } if ($_POST['adresse'] == ''){ $libelleErreur = 'L adresse est obligatoire.'; } if ($libelleErreur == ''){ $nom = $f_formulaire->testInputData($_POST['nom']); $prenom = $f_formulaire->testInputData($_POST['prenom']); $adresse = $f_formulaire->testInputData($_POST['adresse']); $telephone = $f_formulaire->testInputData($_POST['telephone']); $email = $f_formulaire->testInputData($_POST['email']); if($idPassager == null){ $idPassager = $m_passager->creerPassager($nom, $prenom, $adresse, $telephone, $email); /*$mail = new PHPmailer(); //ici ce qui t'interesse $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Host = "smtp.free.fr"; //$mail->SMTPSecure = "ssl"; //$mail->Port = 465; $mail->Username = 'ecoleg.covoiturage'; $mail->Password = '<PASSWORD>'; //$mail->Host = "ptx.send.corp.sopra"; $mail->Port = 587; //$mail->Username = 'svalery'; //$mail->Password = '<PASSWORD>'; $mail->SMTPDebug = 2; //fin $mail->From='<EMAIL>'; //$mail->From='<EMAIL>'; $mail->AddAddress($email); $mail->AddReplyTo('<EMAIL>'); //$mail->AddReplyTo('<EMAIL>'); $mail->Subject='test envoi mail'; $mail->Body='Voici un exemple d\'e-mail au format Texte'; if(!$mail->Send()){ //Teste le return code de la fonction echo $mail->ErrorInfo; } else{ echo 'Mail envoyé avec succès'; } $mail->SmtpClose(); unset($mail); */ header('Location: '.ADRESSE_ABSOLUE_URL.'passager/'.$idPassager); }else{ $id = $idPassager; $miseAjour = $m_passager->modifierPassager($nom, $prenom, $adresse, $telephone, $email, $id); } $passager = $m_passager->getPassager($idPassager); } } ?> <file_sep>/ecoleg/vue/header.php <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="<?php echo $meta_description; ?>"> <meta name="keywords" content="<?php echo $meta_keywords; ?>"> <meta name="Author" content="<NAME>" /> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title><?php echo $nom_page;?></title> <!-- Bootstrap --> <link href="<?php echo ADRESSE_ABSOLUE_URL . BOOTSRAP_CSS; ?>" rel="stylesheet"> <link href="<?php echo ADRESSE_ABSOLUE_URL . STYLE_CSS; ?>" rel="stylesheet"> <script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=<KEY>"></script> <script type="text/javascript"> var geocoder, location1, location2, gDir, map, panel, direction; var sec=0; function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; }); panel = document.getElementById('panel'); direction = new google.maps.DirectionsRenderer({ map : map, panel : panel }); } function showLocation(adresseR, adresseC) { var depart=document.getElementById(adresseR).value; geocoder.getLocations(depart, function (response) { if (!response || response.Status.code != 200) { alert("nous ne parvenons pas à localiser votre adresse"); document.getElementById(adresseC).value = ''; } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; document.getElementById(adresseC).value = location1.address; } }); } function distanceAParcourir(adresseTo) { var adresseFrom = document.getElementById('adresseCovoiturage').value; gDir.load('from: ' + adresseFrom + ' to: ' + adresseTo); } function calculate(){ origin = document.getElementById('origin').value; // Le point départ destination = document.getElementById('destination').value; // Le point d'arrivé if(origin && destination){ var request = { origin : origin, destination : destination, travelMode : google.maps.DirectionsTravelMode.DRIVING // Mode de conduite } var directionsService = new google.maps.DirectionsService(); // Service de calcul d'itinéraire directionsService.route(request, function(response, status){ // Envoie de la requête pour calculer le parcours if(status == google.maps.DirectionsStatus.OK){ direction.setDirections(response); // Trace l'itinéraire sur la carte et les différentes étapes du parcours console.debug('reponse:' + response.routes); } }); } }; </script> </head> <body onload="initialize();"> <div class="container page"> <!-- menu --> <div class="masthead"> <img src="<?php echo ADRESSE_ABSOLUE_URL . IMAGES_STYLE; ?>logo.png" alt="" width="200px"/> <nav class="navbar navbar-inverse navbar-inverse-color"> <ul class="nav navbar-nav"> <li <?php if($page=='accueil'){echo 'class="active"';}?> ><a href="<?php echo ADRESSE_ABSOLUE_URL; ?>accueil"><span class="glyphicon glyphicon-home"> Accueil</a></li> <li <?php if($page=='passagers' || $page=='passager'){echo 'class="active"';}?> ><a href="<?php echo ADRESSE_ABSOLUE_URL; ?>passagers"><span class="glyphicon glyphicon-user"> Passagers</a></li> <li <?php if($page=='groupes' || $page=='groupe'){echo 'class="active"';}?> ><a href="<?php echo ADRESSE_ABSOLUE_URL; ?>groupes"><span class="glyphicon glyphicon-cog"> Groupes</a></li> <li <?php if($page=='covoiturages' || $page=='covoiturage'){echo 'class="active"';}?> ><a href="<?php echo ADRESSE_ABSOLUE_URL; ?>covoiturages"><span class="glyphicon glyphicon-road"> Covoiturage</a></li> <li <?php if($page=='itineraire'){echo 'class="active"';}?> ><a href="<?php echo ADRESSE_ABSOLUE_URL; ?>itineraire"><span class="glyphicon glyphicon-flag"> Itinéraire</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a style="margin-right:10px; color:white; text-decoration: none;" href="<?php echo ADRESSE_ABSOLUE_URL;?>passager/<?php echo$_SESSION['user']->ID; ?>"><?php echo 'Bonjour, ' . $_SESSION['user']->PRENOM; ?></a></li> <li><a style="margin-right:10px; color:white; text-decoration: none;" href="<?php echo ADRESSE_ABSOLUE_URL; ?>accueil"><span class="glyphicon glyphicon-calendar">&#8239;<?php echo date("d/m/y");?></a></li> </ul> </nav> </div><file_sep>/ecoleg/controleur/groupe.php <?php /**** SESSION ****/ session_start(); /**** CLASS CONTROLEUR ****/ require_once('class/c_session.php'); require_once('class/t_texte.php'); require_once('class/f_formulaire.php'); /**** MODELE ****/ require_once('modele/m_session.php'); require_once('modele/m_groupe.php'); require_once('modele/m_groupePassager.php'); require_once('modele/m_passager.php'); require_once('modele/m_covoiturage.php'); /**** OBJETS ****/ $t_texte = new t_texte(); $f_formulaire = new f_formulaire(); $m_session = new m_session($base_de_donnee); $m_groupe = new m_groupe($base_de_donnee); $m_groupePassager = new m_groupePassager($base_de_donnee); $m_passager = new m_passager($base_de_donnee); $m_covoiturage = new m_covoiturage($base_de_donnee); $c_session = new c_session($m_session, $t_texte); /**** VERIF SESSION ****/ $c_session->session(); //$idGroupe = null; $liste_passager = $m_passager->getAllPassager(); //RECHERCHE GROUPE if(!empty($url_param[0])) { if(preg_match('#^[0-9]{1,}$#', $url_param[0])) { $idGroupe = $url_param[0]; $groupe = $m_groupe->getGroupe($idGroupe); $liste_groupePassager = $m_groupePassager->getPassagerByGroupe($idGroupe); $liste_covoiturage = $m_covoiturage->getCovoiturageByGroupe($idGroupe); } } //ACTION if(!empty($url_param[1]) && !empty($url_param[2])) { if(preg_match('#^[0-9]{1,}$#', $url_param[2])) { $action = $url_param[1]; $idSupprime = $url_param[2]; echo $action . '/' . $idSupprime; if ($action == 'deletePassager'){ $m_groupePassager->deleteGroupePassager($idSupprime); $liste_groupePassager = $m_groupePassager->getPassagerByGroupe($idGroupe); header('Location: '.ADRESSE_ABSOLUE_URL.'groupe/'.$idGroupe); } else if ($action == 'deleteCovoiturage'){ $m_covoiturage->deleteCovoiturage($idSupprime); $liste_covoiturage = $m_covoiturage->getCovoiturageByGroupe($idGroupe); header('Location: '.ADRESSE_ABSOLUE_URL.'groupe/'.$idGroupe); } } } //Si ENREGISTREMENT if(isset($_POST['libelle']) && isset($_POST['destination'])){ $libelle = $f_formulaire->testInputData($_POST['libelle']); $destination = $f_formulaire->testInputData($_POST['destination']); if ($_POST['libelle'] == ''){ $libelleErreur = 'Le libellé est obligatoire.'; } if ($_POST['destination'] == ''){ $libelleErreur = 'La destination est obligatoire.'; } if ($libelleErreur == ''){ if(!isset($idGroupe)){ $idGroupe = $m_groupe->creerGroupe($libelle, $destination); header('Location: '.ADRESSE_ABSOLUE_URL.'groupe/'.$idGroupe); }else{ $miseAjour = $m_groupe->modifierGroupe($libelle, $destination, $idGroupe); } $groupe = $m_groupe->getGroupe($idGroupe); } } //SI AJOUT PASSAGER if(isset($_POST['idPassagerAjouter']) && $_POST['idPassagerAjouter'] != ''){ $idPassagerAjouter = $_POST['idPassagerAjouter']; try { $idGroupePassager = $m_groupePassager->ajouterGroupePassager($idGroupe, $idPassagerAjouter); } catch (Exception $e) { $libelleErreur = $e->getMessage(); } $liste_groupePassager = $m_groupePassager->getPassagerByGroupe($idGroupe); } //SI AJOUT POINT DE COVOITURAGE if(isset($_POST['adresseCovoiturage']) && $_POST['adresseCovoiturage'] != ''){ $adresseCovoiturage = $_POST['adresseCovoiturage']; try { $idCovoiturage = $m_covoiturage->ajouterCovoiturage($idGroupe, $adresseCovoiturage); } catch (Exception $e) { $libelleErreur = $e->getMessage(); } $liste_covoiturage = $m_covoiturage->getCovoiturageByGroupe($idGroupe); } //RECHERCHE GROUPE if(isset($idGroupe) && $idGroupe != null) { $groupe = $m_groupe->getGroupe($idGroupe); $liste_groupePassager = $m_groupePassager->getPassagerByGroupe($idGroupe); $liste_covoiturage = $m_covoiturage->getCovoiturageByGroupe($idGroupe); }else{ $idGroupe = null; } ?>
0b97450f7cd1642efe2f63cdca96b3c690265d4d
[ "JavaScript", "SQL", "PHP" ]
33
PHP
Palamax/ecoleg
d59cc1c31a626b8e75a44183e77c487ae5264ae8
fbfc81524ec1625d7e70e5ea7f08449ffbdf46ca